skip to content

inside the deadlock detector

wait-for graphs, deadlock_timeout, soft edges, and how a victim gets chosen.

address
everything.locking.deadlock_detection
part
part 15, locks and concurrency control
chapter
chapter 7 of 10
reading time
10 min

postgres doesn't prevent deadlocks, it detects them. a backend that has waited deadlock_timeout (1 s by default) for a lock builds the wait-for graph and looks for a cycle that includes itself. a cycle of hard waits: it cancels its own transaction with 40P01. a cycle that runs through a soft edge (someone only queued ahead, not holding): it reorders the queue and nobody dies.

the picture

you know the deadlock from the app's side: two transfers in opposite directions, one gets 40P01, retry. this is the other side: who notices, when, and how they decide who loses.

think of a traffic warden who only shows up at a jam after cars have been stuck for a while. at most jams, traffic starts moving again before the warden arrives, so not checking right away saves effort. if it's still stuck, the warden traces who's waiting on whom. a real gridlock: someone has to reverse. a car that's only stuck because it politely stayed behind a truck: wave it through.

three transfers, three accounts, each taking money from one and paying the next: alice → bob, bob → carol, carol → alice. each holds its source row and waits for the next session's.

T1
·
T2
·
T3
·
1
BEGIN; UPDATE accounts SET balance = balance - 10 WHERE id = 1→ UPDATE 1
transaction id locks (pg_locks)
  • T1ExclusiveLockxid 759

T1 moves money out of alice: it holds alice's row.

step 1/9
real output, a postgres 18.6 server · deadlock-three
step through. each UPDATE that waits asks for a ShareLock on the holder's transaction id. after step 5 there's a chain T1 → T2 → T3, no cycle. step 6 closes it, and T3, the session with the 10 ms timeout, gets 40P01. the other two then finish in order.

the wait-for graph

nodes are transactions, an edge A → B means "A waits for a lock B holds". a deadlock is a cycle. here's the one T3 found, drawn from nothing but its error's DETAIL lines:

waits forwaits forwaits forT3xid 761T1xid 759T2xid 760
waits forthe cycle: a deadlock
real output, a postgres 18.6 server · deadlock-three
each box is a session and the transaction id it holds a lock on. each "waits for" is a ShareLock request on the next session's. the dashed waits close a three-way cycle.
T3: UPDATE accounts SET balance = balance + 10 WHERE id = 1
  1. ERROR: deadlock detected
  2. DETAIL: Process T3 waits for ShareLock on transaction 759; blocked by process T1.
  3. Process T1 waits for ShareLock on transaction 760; blocked by process T2.
  4. Process T2 waits for ShareLock on transaction 761; blocked by process T3.
real output, a postgres 18.6 server · deadlock-three
T3's error, word for word, SQLSTATE 40P01. the DETAIL is the cycle, one wait per line, starting from the session that found it. (on a real server the "process" names are pids; the capture swaps in session names.)

the check runs late, and in the waiter

nobody checks for cycles when a lock is requested. checking means locking every partition of the lock table and walking the graph, and nearly every wait ends on its own within milliseconds. so a backend that has to wait sets a timer for deadlock_timeout and sleeps. if the lock comes first, no check ever happens. if the timer fires, that backend runs the check, once, looking for a cycle that leads back to itself.

that's why the capture gives T3 10 ms and the others 10 s. T1 and T2 started waiting first, but their timers are long; when T3 closes the cycle, its timer is the first to fire. T3 finds the cycle and cancels itself: the detector never kills another backend. so the victim is simply whoever's check runs first after the cycle closes, with no notion of which transaction did less work.

sqlempty db
SHOW deadlock_timeout;
output, from postgres 18.6
SHOW
deadlock_timeouttext
1s
(1 row)
predict the output
three sessions close a deadlock cycle. T1 and T2 run with deadlock_timeout = 10s, T3 with 10ms. T1 started waiting first. who gets 40P01?
sql
-- T1 waits for T2, T2 waits for T3, then T3 waits for T1
SET deadlock_timeout = '10s';   -- T1, T2
SET deadlock_timeout = '10ms';  -- T3

raising deadlock_timeout makes real deadlocks take longer to resolve and saves checks on busy servers with lots of short waits. lowering it below the typical lock wait means paying for a check that finds nothing. 1 s is a fine default. (it's also the threshold for log_lock_waits.)

soft edges

not every cycle is a deadlock. lock queues add a second kind of edge: if B is queued ahead of A for a lock A conflicts with, A waits for B too, though B holds nothing A wants. that's a soft edge, and it's the lock queue's rule showing up in the graph. a soft edge is only a matter of queue order, so the detector can fix a cycle that runs through one by reordering the queue.

here's one, captured. T1 reads accounts. T2's ALTER queues behind it. T3 takes advisory lock 1 and then queues to read accounts, behind T2. then T1 asks for advisory lock 1:

hardACCESS EXCLUSIVE on accountssoftACCESS SHARE on accountshardExclusive on advisory 1T1T2T3
hard: waits for a lock the other one holdssoft: the other one is only queued ahead
real output, a postgres 18.6 server · soft-edge
the graph after T1's last request, edges classified from pg_locks: an edge is hard if the blocker holds a granted lock on what the waiter wants, soft if it's only queued ahead. T1 → T3 → T2 → T1 is a cycle with one soft edge.

T3's ACCESS SHARE doesn't conflict with T1's ACCESS SHARE at all; it waits only because T2 is ahead of it. so when T1's check finds the cycle, it moves T3 in front of T2, T3 gets its lock, and the cycle is gone:

T1
·
T2
·
T3
·
1
BEGIN; SELECT count(*) FROM accounts→ 2
table and advisory locks
  • T1ACCESS SHAREaccounts

T1 reads accounts in an open transaction: ACCESS SHARE.

step 1/7
real output, a postgres 18.6 server · soft-edge
step through. at step 5 T1 waits for the advisory lock, and in the same step T3's read wakes up: the queue was rearranged. T3 commits, which hands T1 the advisory lock; T1 commits, and T2's ALTER finally runs. no 40P01 anywhere.

the server log says so in plain words (log_lock_waits was on for T1):

server log
  1. LOG: process T1 avoided deadlock for ExclusiveLock on advisory lock [5,0,1,1] by rearranging queue order after <t> ms
  2. STATEMENT: SELECT pg_advisory_xact_lock(1)
  3. LOG: process T1 still waiting for ExclusiveLock on advisory lock [5,0,1,1] after <t> ms
  4. STATEMENT: SELECT pg_advisory_xact_lock(1)
real output, a postgres 18.6 server · soft-edge
T1's lines in the server log, wait times masked. "avoided deadlock ... by rearranging queue order" is the soft-edge fix; T1 itself keeps waiting, now on an ordinary chain.
quick check
in the soft-edge capture, why couldn't the detector fix the cycle by moving T1 instead?
one level deeperwhat the check actually does

the backend whose timer fired takes every partition lock of the lock table (so the graph can't change under it), then searches outward from itself along wait-for edges, hard and soft. if it gets back to itself through hard edges only, that's a deadlock: it releases the partitions and aborts its transaction with 40P01. if every cycle it finds has a soft edge, it tries rearranging the wait queues involved (a waiter that would be granted earlier is moved up) until no cycle is left, and wakes whoever can now proceed. the search covers heavyweight locks only: latches and LWLocks are never part of it, and a cycle through them would just hang, which is why postgres's code is written so they can't form one.

keylines

  • a deadlock is a cycle in the wait-for graph. postgres finds it, it doesn't prevent it.
  • the check runs only after deadlock_timeout, in the waiting backend, once.
  • the victim is the backend that ran the check. it aborts itself.
  • a soft edge means "queued behind", not "held by". a cycle through one is fixed by reordering the queue.
  • the 40P01 DETAIL lists the cycle. read it before you retry.