Quick revision
The short answer
The deadlocks come from concurrent transfers in opposite directions: A to B locks A then B, while B to A locks B then A, so each holds the row the other needs. We confirm it from the database's deadlock report, then fix it by always locking the two accounts in a fixed order, such as ascending id, keeping the transaction short, and retrying the rare deadlock that remains. We also check that foreign keys and missing indexes are not adding locks we did not expect.
What to remember
In this answer, we saw why locking accounts in (from, to) order deadlocks when two transfers run in opposite directions, and how the PostgreSQL log or SHOW ENGINE INNODB STATUS confirms it with a mirror-image pair of statements. The fix is to lock both accounts in a fixed order such as ascending id, keep the transaction short, retry the rare deadlock from outside the transaction, and check foreign keys and indexes for locks that were not visible in our code.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The deadlocks come from concurrent transfers in opposite directions: A to B locks A then B, while B to A locks B then A, so each holds the row the other needs. We confirm it from the database's deadlock report, then fix it by always locking the two accounts in a fixed order, such as ascending id, keeping the transaction short, and retrying the rare deadlock that remains. We also check that foreign keys and missing indexes are not adding locks we did not expect.
Why this question is asked
Money transfer is the textbook deadlock, and it still appears in real systems because the obvious code is the wrong code: lock the source, lock the target, move the money. It works perfectly until two customers send money to each other at the same moment, or a busy merchant account receives and refunds at once. Interviewers like this question because it tests a full debugging loop: reading the evidence, finding the cause, fixing it at the root and adding a safety net. In this answer, we will see why (from, to) ordering deadlocks, read the deadlock reports in PostgreSQL and MySQL, apply the ordering fix in Spring, and then look at the other sources of locks that can keep deadlocks alive after the fix.
1Why Locking in (from, to) Order Deadlocks
A transfer has to change two rows, so it locks both, usually with SELECT ... FOR UPDATE or simply by updating them. The current code locks the from account first and the to account second. For a single transfer that is harmless. The trouble starts when two transfers run at the same time in opposite directions.
Transfer 1 sends money from account 7 to account 9, so it locks 7 and then asks for 9. Transfer 2 sends money from 9 to 7, so it locks 9 and then asks for 7. If both get their first lock before either asks for the second, each waits for a row the other holds. That is a cycle, and the database must abort one of them. The busier the accounts, the more often two such transfers overlap, which is why the error appears daily rather than once a year.
6 messages in order. Play them, or step through them one at a time.
2Confirming It From the Deadlock Report
Before changing code, we confirm the theory with the database's own report, because a deadlock can also come from statements we did not write, such as a cascade or a batch job. In PostgreSQL, every deadlock is written to the server log with the processes, the locks and the statements involved. Setting log_lock_waits = on also logs any wait longer than deadlock_timeout, which shows near misses. In MySQL, SHOW ENGINE INNODB STATUS prints the latest detected deadlock, and innodb_print_all_deadlocks = ON writes every one of them to the error log.
Notice the shape of the evidence: the same statement on the same table, with the two ids swapped. The ShareLock on transaction in the PostgreSQL message looks odd, but it is how PostgreSQL waits for a row lock: it waits for the transaction that holds the row to finish. When we see this mirror image, the opposite-order theory is confirmed.
3Fix: Lock the Accounts in a Consistent Order
A cycle needs at least one transaction to lock rows in a different order from another. If every transfer locks the lower account id first and the higher id second, no matter which way the money flows, both transfers ask for account 7 first. The second one simply waits for the first to finish, and there is no cycle.
The money still moves from the right account to the right account; only the locking order changed. Notice that the locks are taken by the explicit reads at the start. If we relied on the UPDATE statements that Hibernate sends at flush time to take the locks, the order would depend on the order of entities in the persistence context, which is not something to rely on. Locking at read time with PESSIMISTIC_WRITE makes the order visible in our code.
4Keep Transactions Short and Add a Retry
Locks are held until commit, so anything slow inside the transaction stretches the window in which other transfers can collide. Calling a fraud service, writing to Kafka or rendering a receipt inside the transfer transaction turns a 5 millisecond lock into a 500 millisecond lock. We do those things before the transaction or after it commits.
Even with consistent ordering, other code paths may still lock accounts in a different order, so we keep a small retry around the whole transaction. It catches PessimisticLockingFailureException, waits a few random milliseconds and runs the transfer again in a new transaction. A retry is only safe if the transfer is idempotent at the API level, for example keyed by a transfer id, so that a client retry after a timeout cannot move the money twice.
5Check Foreign Keys and Indexes for Hidden Locks
If deadlocks continue after the fix, the remaining locks often come from places we did not write a lock for. Inserting a row into a transfer_log table with a foreign key to account makes the database lock the parent account row in a shared mode while it checks the reference: PostgreSQL takes a FOR KEY SHARE lock and InnoDB takes a shared lock. That shared lock can meet our exclusive lock in a new cycle.
Missing indexes are the other classic. In InnoDB, a locking read or update that cannot use an index scans and locks every row it examines, not just the rows it changes, so a query on an unindexed column can lock thousands of rows and collide with everything. In PostgreSQL, deleting a parent row with a foreign key whose child column has no index forces a full scan of the child table while locks are held. The deadlock report tells us which statements are involved, and EXPLAIN tells us whether they use the index we expect.
6Follow-up questions
Why not use optimistic locking with a version column instead?
It avoids deadlocks because no row locks are held while the application thinks, but under contention many transfers fail with an optimistic lock error and must retry, which can be worse for hot accounts. For money movement on busy accounts, short pessimistic locks in a consistent order are usually simpler and more predictable.
Could a single UPDATE avoid the problem?
A single statement such as UPDATE account SET balance = CASE ... END WHERE id IN (7, 9) still locks two rows, and the order in which the database visits them is not guaranteed, so it can still deadlock with another transfer. Explicit ordered locking is the reliable approach.
How do we know the fix worked?
We watch the deadlock count before and after the release. PostgreSQL exposes it in pg_stat_database.deadlocks and MySQL in the Innodb_deadlocks status counter. The number should drop to near zero, and any remaining reports should show different statements, which point to the next cause.
7Conclusion
In this answer, we saw why locking accounts in (from, to) order deadlocks when two transfers run in opposite directions, and how the PostgreSQL log or SHOW ENGINE INNODB STATUS confirms it with a mirror-image pair of statements. The fix is to lock both accounts in a fixed order such as ascending id, keep the transaction short, retry the rare deadlock from outside the transaction, and check foreign keys and indexes for locks that were not visible in our code.
Open with
The pattern is classic. A transfer from A to B locks A and then B, and a concurrent transfer from B to A locks B and then A.
Then, if they want more
If both get their first lock before asking for the second, they wait for each other and the database kills one of them.
Before changing anything, I would confirm it from the database: in PostgreSQL the server log shows every deadlock with the processes and statements, and log_lock_waits helps too; in MySQL I would look at the latest detected deadlock in SHOW ENGINE INNODB STATUS and turn on innodb_print_all_deadlocks.
If I see the same SELECT FOR UPDATE on account with the two ids swapped, the theory is confirmed. The fix is to lock in a consistent order regardless of direction, for example lower account id first, using explicit PESSIMISTIC_WRITE reads at the start of the transaction so the order is visible in the code.
Then I would keep the transaction short, moving remote calls outside it, and add a small retry on PessimisticLockingFailureException around the whole transaction, with the transfer keyed by an id so a retry cannot double-pay.
Finally, if deadlocks remain, I would check foreign keys, which take shared locks on the parent account, and missing indexes, which make InnoDB lock more rows than intended.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Deadlocks appear daily in a service that transfers money between two accounts by locking...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/5a9f6d8767/