Skip to content

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 1234

log_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 id inside the update, or SELECT ... WHERE id = ANY($1) ORDER BY id FOR UPDATE. The rule is boring and it eliminates the entire bug class.
  • NOWAIT for interactive paths. FOR UPDATE NOWAIT errors instead of queueing — better to fail fast on a contended row than hold a connection hostage.
  • lock_timeout on 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.