Quick revision
The short answer
T1 locks account 1 and then needs account 2, while T2 locks account 2 and then needs account 1, so each waits for a lock the other holds: a cycle, which is a deadlock. The database detects the cycle and aborts one transaction, the victim, with 'deadlock detected'. The fix is to lock rows in one consistent order, for example ascending account id, whichever direction the transfer goes, and to retry the aborted transaction, because deadlocks can be made rare but never impossible.
What to remember
In this answer, we saw that two transfers in opposite directions each hold one row lock and wait for the other, forming a cycle in the wait-for graph. PostgreSQL finds it after deadlock_timeout and InnoDB immediately, and each aborts a victim with 40P01 or 1213. Locking rows in ascending id order, for example with SELECT ... WHERE id IN (1, 2) ORDER BY id FOR UPDATE, removes this deadlock, and a bounded retry of the whole transaction, triggered by Spring's translated PessimisticLockingFailureException, handles the ones we cannot rule out.
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.
T1 locks account 1 and then needs account 2, while T2 locks account 2 and then needs account 1, so each waits for a lock the other holds: a cycle, which is a deadlock. The database detects the cycle and aborts one transaction, the victim, with 'deadlock detected'. The fix is to lock rows in one consistent order, for example ascending account id, whichever direction the transfer goes, and to retry the aborted transaction, because deadlocks can be made rare but never impossible.
Why this question is asked
Deadlocks in money transfers are the classic example in every database course, and they still appear in real systems because the code that causes them looks completely natural. Interviewers ask it to check whether we understand why the cycle forms, what the database does about it, and that the fix belongs in the application's lock order and retry handling. In this answer, we will reproduce the deadlock step by step, see how PostgreSQL and MySQL detect it and pick a victim, fix it with a consistent lock order, lock both rows up front, and then handle the retry in Spring.
1Reproducing the Deadlock
An UPDATE takes an exclusive lock on the row it changes and keeps it until the transaction ends. T1 transfers from account 1 to account 2, and T2 transfers from 2 to 1 at the same moment. Let's follow the locks.
6 messages in order. Play them, or step through them one at a time.
A cycle in who-waits-for-whom is a deadlock; one side must be aborted.
Notice that each transaction is correct on its own and each statement is ordinary. The problem is only the order: T1 takes 1 then 2, T2 takes 2 then 1. If they interleave as above, neither can continue, and without help they would wait forever.
2How the Database Detects It and Picks a Victim
The database keeps track of who waits for whom, which we can picture as a wait-for graph: an arrow from T1 to T2 means T1 waits for a lock T2 holds. A deadlock is a cycle in that graph. No amount of waiting can break a cycle, so the database aborts one transaction, called the victim, which releases its locks and lets the other proceed.
PostgreSQL does not check on every wait, because the check is relatively expensive. A waiting transaction runs the check only after it has waited deadlock_timeout, 1 second by default; most waits end sooner by themselves. The transaction that ran the check is usually the one aborted, with SQLState 40P01. MySQL InnoDB checks immediately when a transaction starts waiting, as long as innodb_deadlock_detect is on (the default), and rolls back the transaction it considers smaller, measured by rows changed and locked, with error 1213 (SQLState 40001). If detection is turned off, InnoDB relies on innodb_lock_wait_timeout instead.
3Fix 1: Always Lock in the Same Order
A cycle needs two transactions that take the same locks in different orders. If every transfer locks the lower account id first, both T1 and T2 start with account 1. Whichever gets it first continues; the other waits on account 1 before holding anything, so no cycle can form. The amounts and directions stay the same; only the order of the statements changes.
4Fix 2: Lock Both Rows Up Front
A neat variant is to lock both rows in one statement, sorted, before doing any updates. The database returns, and locks, the rows in the order of the ORDER BY, so every transaction acquires them in ascending id order.
This also gives us both balances before we change anything, so we can check for insufficient funds without an extra round trip. The same rule applies to any multi-row operation: sort the keys, then lock.
5Fix 3: Retry the Victim
Lock ordering removes this deadlock, but in a real system other code paths, index locks, foreign keys and triggers can still produce cycles we did not foresee. So the application must treat a deadlock as a retryable error: roll back, wait a little, and run the whole transaction again. Retrying only the failed statement is wrong, because the victim's earlier work was rolled back with it.
Spring translates the vendor error for us. The SQLState 40P01 from PostgreSQL or error 1213 from MySQL becomes a PessimisticLockingFailureException subclass, in recent versions usually CannotAcquireLockException (check your version), which is a TransientDataAccessException. That is what we retry on, from a bean outside the transactional one, so each attempt starts a fresh transaction.
6Follow-up questions
How does Spring translate a deadlock error, and how would you retry it?
Spring's exception translator maps the vendor code (PostgreSQL SQLState 40P01, MySQL error 1213) to a PessimisticLockingFailureException subclass, typically CannotAcquireLockException in current versions, part of the TransientDataAccessException family; with JPA, Hibernate's lock exceptions are translated similarly. I would retry with Spring Retry's @Retryable, or the retry support in Spring Framework 7, on a method in a separate bean that calls the @Transactional method, so every attempt runs in a new transaction. Limit attempts to about three, use backoff with jitter, and make sure the transaction has no external side effects that a retry would repeat.
Would a higher deadlock_timeout prevent the deadlock?
No. deadlock_timeout only controls how long PostgreSQL waits before checking for a cycle. A higher value means deadlocks are detected later, so both transactions sit blocked longer; a lower value finds them sooner but runs the check more often on ordinary waits.
Can a single UPDATE statement deadlock with another?
Yes. An UPDATE that changes several rows locks them in the order it visits them, so two UPDATEs over overlapping rows in different orders, or an UPDATE and a DELETE through different indexes, can form a cycle. Consistent access paths and small transactions reduce the chance, and retry handles the rest.
7Conclusion
In this answer, we saw that two transfers in opposite directions each hold one row lock and wait for the other, forming a cycle in the wait-for graph. PostgreSQL finds it after deadlock_timeout and InnoDB immediately, and each aborts a victim with 40P01 or 1213. Locking rows in ascending id order, for example with SELECT ... WHERE id IN (1, 2) ORDER BY id FOR UPDATE, removes this deadlock, and a bounded retry of the whole transaction, triggered by Spring's translated PessimisticLockingFailureException, handles the ones we cannot rule out.
Open with
T1 locks account 1 with its first update and then needs account 2; T2 does the opposite, locks 2 and then needs 1. Each is waiting for a lock the other holds, which is a cycle in the wait-for graph, so neither can ever proceed.
Then, if they want more
The database detects that. PostgreSQL checks after deadlock_timeout, one second by default, and InnoDB checks immediately with innodb_deadlock_detect. It aborts one transaction as the victim, giving 40P01 in PostgreSQL or error 1213 in MySQL, and the other carries on.
The fix is to make every transfer take its locks in the same order, for example lower account id first regardless of direction. The simplest way is to start with SELECT ... WHERE id IN (from, to) ORDER BY id FOR UPDATE, which locks both rows in id order and gives me both balances for the funds check.
Then the second transfer just waits on the first row instead of deadlocking. But deadlocks can still come from paths I haven't thought of, so I'd also retry the whole transaction, not the statement, a few times with jittered backoff. Spring translates the error into a PessimisticLockingFailureException, and I'd retry on that from a bean outside the transactional method.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 7
- 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
- PostgreSQL documentation, MySQL reference manual
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 "Two transactions run at the same time. T1:": https://scrivio-interview-library.netlify.app/databases/database-locking/6f090d2640/