Part 12 / Topic 8 of 9
Deadlocks
A waits for B while B waits for A: a deadlock — neither can ever proceed. Postgres detects the cycle (after deadlock_timeout, default 1s) and shoots one participant. Real transcript — two sessions updating the same two rows in opposite orders:
-- Session A -- Session B
BEGIN; BEGIN;
UPDATE products SET stock = stock UPDATE products SET stock = stock
WHERE product_id = 1; -- locks row 1 WHERE product_id = 2; -- locks row 2
UPDATE products SET stock = stock
WHERE product_id = 2; -- waits for B…
UPDATE products SET stock = stock
WHERE product_id = 1; -- waits for A: cycle!
ERROR: deadlock detected
DETAIL: Process 77495 waits for ShareLock on transaction 1967; blocked by process 77494.
Process 77494 waits for ShareLock on transaction 1966; blocked by process 77495.
UPDATE 1 ← B proceeds and commits fine
One session dies (its transaction rolls back — retry it), the other sails through. Prevention is a convention, not a tool: every transaction takes its locks in the same order (by id ascending, say). Same-order lockers can queue but never cycle. Keep transactions short and the window shrinks further; let the retry handle the rare rest.
🧪 Quick quiz — answer from memory, then check.
- How does Postgres resolve a deadlock?
- The one convention that prevents most of them?
Show the answers
- Detects the wait cycle and aborts one transaction with
deadlock detected; the app retries it. - Acquire locks in a fixed global order (e.g., ascending id) in every transaction.
Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.