← Lessons

quiz vs the machine

Gold1320

Concurrency

The Bank Account Transfer Deadlock

Transferring money between accounts can deadlock when two transfers cross paths.

4 min read · core · beat Gold to climb

The scenario

A transfer locks the source account, locks the destination account, moves money, then unlocks both. This keeps each balance consistent. The trouble starts with two transfers in opposite directions running at once.

The crossing deadlock

Thread A transfers from account 1 to account 2 and locks account 1. Thread B transfers from account 2 to account 1 and locks account 2. Now A waits for account 2 while B waits for account 1. Neither can proceed. This is a circular wait on two locks.

The fix is lock ordering

Always acquire account locks in a consistent global order, for example by ascending account id:

  • Determine which account has the smaller id.
  • Lock that one first regardless of transfer direction.
  • Then lock the other.

With a total order on locks no cycle can form, so deadlock is impossible. If ids can be equal you must guard against locking the same account twice.

Key idea

Two crossing transfers deadlock through circular lock wait, and acquiring account locks in a fixed global order eliminates the cycle.

Check yourself

Answer to earn rating on the learn ladder.

1. What creates the deadlock between two opposite transfers?

2. How does lock ordering prevent the deadlock?