skip to content

deadlocks

two transfers in opposite directions, a cycle, and the transaction postgres kills. lock ordering as the fix.

address
everything.transactions.deadlocks
part
part 11, transactions and isolation
chapter
chapter 10 of 11
reading time
7 min

a deadlock is two transactions each holding a lock the other one is waiting for. neither can ever move. postgres notices after deadlock_timeout (1 s by default), cancels one of them with SQLSTATE 40P01, and the other carries on. the fix is boring and it works: take locks in the same order everywhere, and retry the 40P01s that still happen.

the picture

you know the corridor dance: two people meet in a narrow hallway, each steps aside for the other, in the same direction, forever. a deadlock is that, minus the stepping aside. each one holds its ground and waits for the other.

two transfers run at once. T1 moves 10 from alice to bob, T2 moves 30 from bob to alice. each takes money from its source first, which locks that row. then each needs the other's source row.

lock order =
T1
snapshot 759:759:
T2
·
1
BEGIN
lock manager
  • no locks

T1 moves 10 from alice to bob.

step 1/9
real output, a postgres 18.6 server · deadlock
step through both. in opposite order, T1 waits for T2, T2 waits for T1, and postgres cancels T2. in lower id first, T2 queues behind T1 on alice's row and nobody is cancelled. the list on the right is pg_locks after each step: held, or dashed and waiting.

what postgres saw

a row lock wait is really a wait for a transaction. T1 can't touch bob's row until T2 ends, so it asks for a ShareLock on T2's transaction id, which T2 holds exclusively until it commits or rolls back. (how row locks are stored explains why it's the xid and not the row.) once T2 asks for T1's transaction id the same way, the waits form a loop:

held byheld bywaits forwaits forT2xid 759wanted: ShareLockT1xid 760wanted: ShareLock
held bywaits forthe cycle: a deadlock
real output, a postgres 18.6 server · deadlock
the wait-for graph at the moment of the deadlock, built from the error's DETAIL lines. each session holds its own transaction id lock and waits for the other's. the dashed waits close a cycle.

and here's what T2 got, word for word. on a real server the two "process" names are pids; the capture swaps them for session names so it repeats exactly:

T2: UPDATE accounts SET balance = balance + 30 WHERE id = 1
  1. ERROR: deadlock detected
  2. DETAIL: Process T2 waits for ShareLock on transaction 759; blocked by process T1.
  3. Process T1 waits for ShareLock on transaction 760; blocked by process T2.
T2's error, SQLSTATE 40P01. the DETAIL lines are the cycle, one wait per line.

nobody checks for cycles on every lock request. that would be expensive, and almost every wait ends on its own. instead a backend that has been waiting for deadlock_timeout runs the check itself, and if it finds a cycle, the transaction it cancels is its own. that's why this capture gives T2 a 10 ms timeout and T1 ten seconds: T2's check runs first, so T2 is the one cancelled, every run. on your server, don't count on which one it'll be. inside the deadlock detector has the rest.

sqlempty db
SHOW deadlock_timeout;
output, from postgres 18.6
SHOW
deadlock_timeouttext
1s
(1 row)
predict the output
T2 was cancelled after it had already taken 30 from bob. what happens to that first UPDATE?
sql
/* T2 */ BEGIN;
/* T2 */ UPDATE accounts SET balance = balance - 30 WHERE id = 2;  -- UPDATE 1
/* T2 */ UPDATE accounts SET balance = balance + 30 WHERE id = 1;  -- ERROR 40P01
/* T2 */ ROLLBACK;

the fix: same order, every time

a cycle needs two transactions that take the same locks in different orders. take them in one global order (lower account id first, say) and the second transaction blocks on the first lock it needs, while holding nothing the other one wants. it waits, it doesn't deadlock. that's the second run in the figure.

in a transfer that means: lock both rows up front, in id order, then do the updates in whatever order reads naturally. ORDER BY ... FOR UPDATE does the locking in one statement:

sqldb=bank
BEGIN;
SELECT id, owner, balance FROM accounts
WHERE id IN (2, 1)
ORDER BY id
FOR UPDATE;
UPDATE accounts SET balance = balance - 30.00 WHERE id = 2;
UPDATE accounts SET balance = balance + 30.00 WHERE id = 1;
COMMIT;
output, from postgres 18.6
#1 · BEGIN
#2 · SELECT 2
idint4ownertextbalancenumeric
1alice100.00
2bob100.00
(2 rows)
#3 · UPDATE 1
#4 · UPDATE 1
#5 · COMMIT

the order matters because of where the locking happens. the LockRows node sits on top of the plan and locks each row as it comes out, so it locks in the order the rows arrive:

sqldb=bank
EXPLAIN (COSTS OFF)
SELECT id FROM accounts WHERE id IN (2, 1) ORDER BY id FOR UPDATE;
output, from postgres 18.6
EXPLAIN
LockRows -> Index Scan using accounts_pkey on accounts Index Cond: (id = ANY ('{2,1}'::integer[]))

see? LockRows on top, and under it an index scan on the primary key, which hands the rows over in id order whatever order the IN list says. so alice is locked before bob, in every transfer that asks this way.

and still retry

ordering removes the deadlocks you can see. the ones left (a trigger, a foreign key, two code paths someone forgot to align) show up as 40P01, and a 40P01 means the same as a 40001: nothing happened, run the whole transaction again. the postgres manual suggests retrying deadlock failures too. retrying serialization failures has the loop. if what you want instead is to give up waiting after a while, that's lock_timeout, a different tool: it fires on any long wait, cycle or not (the lock queue).

keylines

  • a deadlock is a cycle of waits. nobody in it can move on their own.
  • postgres checks after deadlock_timeout, finds the cycle, and cancels one transaction: 40P01.
  • a row lock wait is a wait for the holder's transaction id. the DETAIL lines say so.
  • take locks in one order everywhere: lower id first, or SELECT ... ORDER BY id FOR UPDATE.
  • 40P01 means nothing happened. retry the whole transaction.