Lesson 3 of 14 · 16m
Deadlocks, Lock Waits, and Lock Ordering
Postgres never escalates locks — deadlocks come from inconsistent ordering, and the fix is a convention, not a setting.
Every deadlock in Postgres is the same shape: transaction A holds a lock and wants one B holds; B holds it and wants one A holds. Postgres detects the cycle — deadlock_timeout (default 1s) is how long a backend waits before the deadlock detector runs — and kills one transaction with ERROR: deadlock detected, SQLSTATE 40P01. The victim is essentially arbitrary. Your retry loop should expect it.
The wrong mental model: lock escalation
Engineers arriving from SQL Server or DB2 carry a model where row locks "escalate" to page or table locks under pressure. Postgres does not escalate locks. A row lock is a marking on the tuple (xmax set to the locking transaction) plus a lock queue; a million row locks are a million marked tuples, not a table lock. This means two things in opposite directions: you never get surprised by escalation — and lock memory pressure is a real thing, because every lock lives in the shared lock table sized by max_locks_per_transaction × (max_connections + max_prepared_transactions). Exhaust that and you get out of shared memory, not escalation.
The mechanism: what actually deadlocks
-- txn 1 -- txn 2
UPDATE accounts SET ... UPDATE accounts SET ...
WHERE id = 1; WHERE id = 2;
UPDATE accounts SET ... UPDATE accounts SET ...
WHERE id = 2; WHERE id = 1;Txn 1 holds row 1, txn 2 holds row 2, each wants the other's. Detector fires, one aborts. Multi-row UPDATE ... WHERE id IN (...) without ORDER BY is the same bug at scale: two sessions update the same row set in different physical order and meet in the middle.
The hidden source is foreign keys: inserting a child row takes a FOR KEY SHARE lock on the parent row, and ON DELETE CASCADE locks dependents. An innocuous-looking insert can queue behind — or deadlock with — an unrelated transaction holding the parent. Row locks aren't the only player. FOR UPDATE also takes the tuple's lock; DDL (ALTER TABLE, DROP INDEX) needs ACCESS EXCLUSIVE on the table lock, which conflicts with everything including plain SELECTs. A migration waiting on ACCESS EXCLUSIVE behind one long-running query is a "soft deadlock" the detector can't help with — it isn't a cycle, it's a queue, and every later write joins it behind the migration.
The diagnostic queries
SELECT pid, wait_event, query FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
SELECT pg_blocking_pids(1234); -- who is blocking pid 1234log_lock_waits = on (Postgres 14+) logs any statement that waited past deadlock_timeout for a lock — the single best signal for "queries are slow because they're queued, not running." deadlock_timeout itself is detection latency, not prevention: raising it delays detection, lowering it burns CPU re-checking lock graphs. Leave it at 1s.
The practice
- Lock in a canonical order. Update/lock rows sorted by a stable key —
ORDER BY idinside the update, orSELECT ... WHERE id = ANY($1) ORDER BY id FOR UPDATE. The rule is boring and it eliminates the entire bug class. NOWAITfor interactive paths.FOR UPDATE NOWAITerrors instead of queueing — better to fail fast on a contended row than hold a connection hostage.lock_timeouton migrations.SET lock_timeout = '2s'means the migration fails fast instead of queueing a pile of writes behind its lock request. Retry it, don't let it wait.- Retry
40P01. A deadlock abort is a normal event under contention; the transaction is retryable by definition. If your code doesn't retry it, your code turns routine contention into user-facing 500s. - Advisory locks for app-level mutexes —
pg_advisory_xact_lock(key)serializes "rebuild this cache," "process this tenant" without touching table locks at all.
Deadlocks are a protocol bug, not a Postgres bug. Impose an order and the cycle can't form.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
MySQL, PostgreSQL, Redis, and MongoDB End-of-Life Dates in 2026
Four major open source databases are hitting end-of-life milestones in 2026, and MySQL 8.0 has already crossed that line. Here's a practical, code-first look at how to audit what you're running, back it up properly, and migrate before the risk compounds.