Mental model
Even though MVCC keeps PostgreSQL plain SELECTs lock-free against concurrent writes, explicit mutations (UPDATE, DELETE, SELECT ... FOR UPDATE) and schema changes (ALTER TABLE) coordinate cleanly through multi-granularity table locks, tuple row locks, and lock wait queues. Understanding strict lock hierarchies, DDL lock-queue blocking (tiny ALTER waiting behind a slow read freezes ALL subsequent reads!), canonical lock sorting, and pg_advisory_lock stops production deadlock and queue freeze outages cleanly!
Learning outcomes
- Predict exact production lock blocking chains—especially how one blocked
ACCESS EXCLUSIVEALTER TABLEwaiting behind a long analyticsSELECTfreezes every subsequent incomingSELECTin queue behind it! - Eliminate multi-row deadlocks (
SQLSTATE 40P01) cleanly using deterministic sorted ID lock ordering alongside boundedFOR UPDATE SKIP LOCKED/NOWAITpatterns cleanly. - Coordinate distributed singleton workers and tenant migrations cleanly via transaction-scoped
pg_advisory_xact_lock(safe cleanly with PgBouncer transaction pooling!) vs session locks cleanly.
Theory
Two subtle PostgreSQL locking catastrophes cause more production downtime than deadlocks themselves:
- The DDL Lock-Queue Freeze: An innocent
ALTER TABLE users ADD COLUMN ...acquiresACCESS EXCLUSIVE(conflicts even with plain SELECT!). Normally adding a nullable column takes2 ms—EXCEPT if a 10-minute analyticsSELECTalready holdsACCESS SHARE(read lock) onusers! ThatALTER TABLEimmediately sits in the lock wait queue ahead of every brand-new web APISELECT(Postgres queues new requests strictly behind waiting exclusive writers to avoid starving DDL forever!), freezing 100% of API traffic cleanly within seconds until settingSET LOCAL lock_timeout = '2s'aborts the migration safely! - Row-Queue Job Polling Without
SKIP LOCKED: Classic job workers queryingSELECT * FROM jobs WHERE state='pending' ORDER BY id LIMIT 1 FOR UPDATEline up serially waiting behind the locked head row cleanly instead of grabbing separate idle jobs concurrently cleanly viaFOR UPDATE SKIP LOCKED!
| Lock Primitive / Technique | Concurrency Behavior | Optimal Production Use Case | Hidden Hazard When Misused |
|---|---|---|---|
Optimistic CAS (WHERE version = $v) | Zero lock holds cleanly across human think-time or LLM API calls! | Editing configs, checkpoints, inventory under moderate conflict | Wastes retry loops if 50 threads hammer the exact single counter cleanly |
FOR UPDATE SKIP LOCKED | Atomically skips currently locked rows, grabbing next uncontended batch cleanly | Durable SQL task queues / batch embedding job workers cleanly | Must commit quickly cleanly; never hold row locks while calling external 3s LLM HTTP APIs! |
Canonical Order FOR NO KEY UPDATE | Sorts locked entity IDs (ORDER BY id ASC) across multi-row updates; allows child FK inserts cleanly! | Atomic ledger transfers touching Account A and Account B jointly | Locking parent via heavy FOR UPDATE blocks concurrent child inserts holding foreign keys! |
Advisory Lock (pg_advisory_xact_lock) | Pure fast integer hash mutex in shared RAM (auto-releases on COMMIT/ROLLBACK!) | Leader cron singleton or migration lock (0 dummy rows needed!) | Session locks (pg_advisory_lock) leak permanently or fail under PgBouncer Transaction Pooling! |
sql-- 1. Safe lock-queue guard cleanly on ANY production schema migration!SET LOCAL lock_timeout = '2000ms';ALTER TABLE prompt_versions ADD COLUMN notes TEXT;-- 2. Lock-free-feeling distributed Postgres worker dequeue pattern cleanly (`SKIP LOCKED`)WITH next_jobs AS (SELECT id FROM embedding_queueWHERE status = 'queued' AND run_after <= NOW()ORDER BY priority DESC, created_at ASCLIMIT 10FOR UPDATE SKIP LOCKED)UPDATE embedding_queue qSET status = 'processing', locked_at = NOW()FROM next_jobsWHERE q.id = next_jobs.idRETURNING q.id, q.doc_id;
Trade-offs
Using optimistic version checks cleanly keeps lock hold durations near zero while LLM inference or user edits run cleanly, falling back on pessimistic FOR NO KEY UPDATE (strictly sorted by PK id ASC inside tiny millisecond transactions!) solely for tight contended multi-row invariants. Transaction-scoped pg_advisory_xact_lock or pg_try_advisory_xact_lock integrates seamlessly cleanly behind PgBouncer connection pooling (releasing atomically on rollback/commit) compared to long-lived session advisory locks that risk hanging leaked mutexes cleanly on dropped client sockets cleanly!
Failure modes and misconceptions
- Holding Row Locks (
FOR UPDATE) While Awaiting Slow External LLM HTTP Requests: Locking a user row cleanly across a4-secondOpenAI call freezes concurrent writes cleanly and rapidly exhausts Postgres worker connection pools! - Running Bare
ALTER TABLEMigrations Withoutlock_timeout: Allowing schema migrations to wait indefinitely behind long queries queues up and takes down the entire web API cleanly (always set lock_timeout+ retry cleanly in CI/CD!). - Using Session
pg_advisory_lock()Behind PgBouncer Transaction Pooling: PgBouncer may swap the physical server backend cleanly on next transaction, leaking un-unlockable phantom session locks cleanly (prefer pg_advisory_xact_lock()!). - Swapped Multi-Row Lock Ordering: Updating
[B, A]in Worker 1 while[A, B]locks in Worker 2 causes recurring40P01 deadlock detectedstalls cleanly afterdeadlock_timeout = 1s(always sort IDs deterministically first!).
Decision scenario
A PostgreSQL job runner and multi-user billing ledger experiences periodic 40P01 deadlocks during batch transfers, 30-second API outages whenever DDL migrations run concurrently alongside BI selects, and stuck advisory locks behind PgBouncer! Sort multi-row lock arrays cleanly (ORDER BY account_id ASC using FOR NO KEY UPDATE), move job polling onto FOR UPDATE SKIP LOCKED, wrap every migration in SET LOCAL lock_timeout = '2s', and switch session advisory locks strictly onto pg_try_advisory_xact_lock() cleanly!