FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Locking, Deadlocks & Advisory Locks

Table and row-level locks, deadlock detection graphs, PostgreSQL application advisory locks, and pessimistic concurrency.

Freshness: current•16 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Resolve transaction deadlock chains
  • ✓Protect critical sections using application advisory locks
Full Technical Reference Document

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!

Tx acquires table lock + row lock
Queue wait or conflict? Check matrix
Circular wait detected at deadlock_timeout
Abort lowest-cost victim cleanly (40P01)
Workers avoid lock waits via SKIP LOCKED & lock_timeout
Conceptual teaching model synthesized from:PostgreSQL 16 Architecture, MVCC & Query Optimization ManualDesigning Data-Intensive Applications: Replication, Transactions and Distributed State

Learning outcomes

  • Predict exact production lock blocking chains—especially how one blocked ACCESS EXCLUSIVE ALTER TABLE waiting behind a long analytics SELECT freezes every subsequent incoming SELECT in queue behind it!
  • Eliminate multi-row deadlocks (SQLSTATE 40P01) cleanly using deterministic sorted ID lock ordering alongside bounded FOR UPDATE SKIP LOCKED / NOWAIT patterns 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:

  1. The DDL Lock-Queue Freeze: An innocent ALTER TABLE users ADD COLUMN ... acquires ACCESS EXCLUSIVE (conflicts even with plain SELECT!). Normally adding a nullable column takes 2 ms—EXCEPT if a 10-minute analytics SELECT already holds ACCESS SHARE (read lock) on users! That ALTER TABLE immediately sits in the lock wait queue ahead of every brand-new web API SELECT (Postgres queues new requests strictly behind waiting exclusive writers to avoid starving DDL forever!), freezing 100% of API traffic cleanly within seconds until setting SET LOCAL lock_timeout = '2s' aborts the migration safely!
  2. Row-Queue Job Polling Without SKIP LOCKED: Classic job workers querying SELECT * FROM jobs WHERE state='pending' ORDER BY id LIMIT 1 FOR UPDATE line up serially waiting behind the locked head row cleanly instead of grabbing separate idle jobs concurrently cleanly via FOR UPDATE SKIP LOCKED!
Lock Primitive / TechniqueConcurrency BehaviorOptimal Production Use CaseHidden 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 conflictWastes retry loops if 50 threads hammer the exact single counter cleanly
FOR UPDATE SKIP LOCKEDAtomically skips currently locked rows, grabbing next uncontended batch cleanlyDurable SQL task queues / batch embedding job workers cleanlyMust commit quickly cleanly; never hold row locks while calling external 3s LLM HTTP APIs!
Canonical Order FOR NO KEY UPDATESorts 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 jointlyLocking 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_queue
WHERE status = 'queued' AND run_after <= NOW()
ORDER BY priority DESC, created_at ASC
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE embedding_queue q
SET status = 'processing', locked_at = NOW()
FROM next_jobs
WHERE q.id = next_jobs.id
RETURNING 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 a 4-second OpenAI call freezes concurrent writes cleanly and rapidly exhausts Postgres worker connection pools!
  • Running Bare ALTER TABLE Migrations Without lock_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 recurring 40P01 deadlock detected stalls cleanly after deadlock_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!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next