Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A PostgreSQL service logs 'ERROR: deadlock detected' (SQLSTATE 40P01) several times an hour. The detail shows two transactions each updating rows in the accounts table for a transfer between the same two accounts in opposite directions. Explain the cause and the fixes.

A transfer from A to B locks account A and then B, while a simultaneous transfer from B to A locks B and then A; each ends up waiting for the lock the other holds, a cycle that can never resolve. PostgreSQL checks for such cycles after deadlock_timeout, 1 second by default, and aborts one transaction with SQLSTATE 40P01. The fix is to always lock the accounts in the same order, for example by id, keep the transactions short, and still retry the occasional victim.

Why this question is asked

Deadlocks look alarming in logs, but they are one of the most fixable concurrency problems, because the database tells us exactly which statements were involved. The transfer between two accounts is the textbook case, and interviewers ask it because the fix, a consistent lock order, is a principle that applies to every system that locks more than one thing. In this answer, we will recap how row locks work during an UPDATE, reproduce the deadlock, see how PostgreSQL detects it, and then go through the fixes and the tools for finding the statements.

1A Quick Recap of Row Locks in an UPDATE

When a PostgreSQL transaction updates a row, it takes an exclusive row lock on it and keeps that lock until the transaction commits or rolls back. Another transaction that wants to update the same row must wait. That is normal and usually short. A deadlock is the special case where two transactions wait for each other, so neither can ever continue.

2Reproducing the Deadlock

A typical transfer debits one account and credits the other in one transaction. Two transfers between the same pair, in opposite directions, run at the same moment.

Java
-- Transfer 1: A (id 1) -> B (id 2) -- Transfer 2: B (id 2) -> A (id 1)
BEGIN; BEGIN;
UPDATE accounts SET balance = balance - 10
WHERE id = 1; -- locks row 1
UPDATE accounts SET balance = balance - 5
WHERE id = 2; -- locks row 2
UPDATE accounts SET balance = balance + 10
WHERE id = 2; -- waits for transfer 2
UPDATE accounts SET balance = balance + 5
WHERE id = 1; -- waits for transfer 1
-- after about 1 second, one of them gets:
-- ERROR: deadlock detected (SQLSTATE 40P01)
-- DETAIL: Process 4711 waits for ShareLock on transaction 9021; blocked by process 4712.
-- Process 4712 waits for ShareLock on transaction 9020; blocked by process 4711.
Step throughTwo transfers in opposite directions
Transfer A to BPostgreSQLTransfer B to A
UPDATE id 1: lock row 1
UPDATE id 2: lock row 2
UPDATE id 2: wait for B to A
UPDATE id 1: wait for A to B
after deadlock_timeout: cycle found
ERROR 40P01, rolled back
lock on row 2 granted, continue

7 messages in order. Play them, or step through them one at a time.

Notice that each transfer locks its source account first. Transfer 1 holds row 1 and wants row 2; transfer 2 holds row 2 and wants row 1. Neither will release its lock until it commits, and neither can commit until it gets the other lock.

3How PostgreSQL Detects It

Checking for cycles on every lock wait would be expensive, and most waits end quickly. So PostgreSQL waits for deadlock_timeout, 1 second by default, and only then builds the wait-for graph, which records who waits for whom. If it finds a cycle, it aborts one of the transactions in it, which releases that transaction's locks and lets the others continue. The aborted one gets SQLSTATE 40P01 and its whole transaction is rolled back. The DETAIL and CONTEXT lines in the server log name the processes, the lock types and, with default logging, the statements involved.

4Fix 1: Lock the Rows in a Consistent Order

A cycle needs two transactions that take the same locks in different orders. If every transfer locks the lower account id first, whatever the direction, both transfers want row 1 first; the second simply waits for the first to finish, and no cycle can form.

SQL
BEGIN;
SELECT id FROM accounts WHERE id IN (:from, :to) ORDER BY id FOR UPDATE; -- locks 1 then 2, always
UPDATE accounts SET balance = balance - :amount WHERE id = :from;
UPDATE accounts SET balance = balance + :amount WHERE id = :to;
COMMIT;
-- transfer 2 now waits at the SELECT until transfer 1 commits; no deadlock

The SELECT ... ORDER BY id FOR UPDATE takes both row locks up front in id order; once a transaction holds both, the updates cannot block. In application code without the SELECT, the same idea is to sort the two ids and update the lower one first. With JPA, we can load both accounts with a PESSIMISTIC_WRITE lock in id order.

5Fix 2 and 3: Short Transactions and a Retry

The longer a transaction holds locks, the more likely another transaction collides with it. So no user think time, remote HTTP calls or message sends while row locks are held: compute and validate first, then open the transaction, lock, update and commit within milliseconds.

Even with a consistent order, deadlocks cannot be eliminated completely: other code paths, foreign key checks, triggers and ORM flush order can still lock rows in unexpected orders. So the transfer still runs inside a retry wrapper that catches 40P01, which Spring translates into a ConcurrencyFailureException subtype such as CannotAcquireLockException (check your version), and re-runs the whole transaction a few times. A deadlock is safe to retry, because the victim was rolled back completely.

6Finding the Statements Involved

Turning on log_lock_waits = on makes PostgreSQL log every lock wait longer than deadlock_timeout, including waits that end without a deadlock, which shows the hot spots. The deadlock message itself names the processes and statements. pg_locks joined with pg_stat_activity, or pg_blocking_pids(pid), shows live waits. In MySQL InnoDB, SHOW ENGINE INNODB STATUS prints a LATEST DETECTED DEADLOCK section with both transactions, the locks they held and the ones they waited for, and innodb_print_all_deadlocks = ON writes every deadlock to the error log.

7Follow-up questions

Why can Hibernate's flush order cause deadlocks you did not write?

Hibernate does not send updates when we call a setter. At flush time it emits the UPDATE statements in the order of entities in the persistence context, roughly the order they were loaded or attached, grouped by action type (inserts, updates, collection changes, then deletes). So two transactions that load the same two accounts in different orders, for example because one queried by name and one by id, can update them in different orders even though the Java code looks symmetric. Setting hibernate.order_updates=true makes Hibernate sort updates by entity type and primary key, which gives a consistent order, and locking rows explicitly in id order at the start of the transaction is even safer.

Should we lower deadlock_timeout?

Usually not. It only delays detection of real deadlocks, which are rare after the fix. Lowering it makes PostgreSQL run the detector more often on ordinary waits, which costs CPU.

Does READ COMMITTED versus SERIALIZABLE matter here?

No. Deadlocks come from exclusive row locks taken by writes, and those are the same at every isolation level.

8Conclusion

In this answer, we saw that two opposite transfers deadlock because each locks its source account first and then waits for the other's. PostgreSQL detects the cycle after deadlock_timeout, 1 second by default, and aborts one with 40P01. Locking both accounts in a consistent order, for example with SELECT ... ORDER BY id FOR UPDATE, removes the cycle; short transactions make collisions rarer; and a retry still handles the deadlocks that remain. log_lock_waits and the deadlock detail, or SHOW ENGINE INNODB STATUS in MySQL, show the statements.

What to say in the interviewAbout 80 seconds aloud

Open with

This is a classic lock-order deadlock. A transfer from A to B updates A first and takes its row lock, then updates B. A transfer from B to A at the same moment locks B first, then wants A.

Then, if they want more

Now each holds the lock the other needs, and since row locks are held until commit, neither can continue. PostgreSQL waits deadlock_timeout, one second by default, then checks the wait-for graph, finds the cycle and aborts one transaction with deadlock detected, SQLSTATE 40P01.

The main fix is a consistent lock order: at the start of the transaction I'd select both accounts where id in from and to, order by id, for update, so every transfer locks the lower id first regardless of direction. Then the second transfer just waits for the first instead of deadlocking.

I'd keep the transaction short, with no remote calls or user think time while holding locks. And I'd still retry the aborted transaction a few times, because deadlocks can't be eliminated entirely; things like foreign key checks or Hibernate's flush order can lock in unexpected orders.

To investigate, I'd turn on log_lock_waits and read the deadlock detail in the log, and in MySQL I'd look at SHOW ENGINE INNODB STATUS for the latest deadlock.

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.
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 "A PostgreSQL service logs 'ERROR: deadlock detected' (SQLSTATE 40P01) several times an...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/41cef3e85a/