WORKINGCHAPTER 13

Locking, deadlocks and lock escalation

Eight table lock modes, four row lock modes, one queue, and the ALTER TABLE that takes the site down while waiting for a SELECT

50 MINDATABASESUPDATED 2026-11-02
PREDICT

Session 1 runs BEGIN; SELECT count(*) FROM orders; and stays open. Session 2 runs ALTER TABLE orders ADD COLUMN note text; Session 3 then runs SELECT * FROM orders WHERE id = 1; What happens to session 3?

The chapter on transactions from the outside showed that two transactions updating the same row cannot both proceed. The MVCC chapter showed that readers do not block writers. This chapter is about the part of concurrency control that does block: the locks Postgres takes on tables and rows, the order in which waiting requests are granted, what happens when two transactions wait for each other, and how to see all of it from SQL while it is happening. The general theory of deadlock, the four conditions and the wait-for graph, is in the deadlock lesson; this chapter applies it to a database.

Table locks: eight modes and one matrix

Every statement takes a lock on every table it touches, held until the transaction ends. There are eight modes. The names are historical and misleading (ROW EXCLUSIVE is a table lock), so learn them by which commands take them:

mode taken by
ACCESS SHARE SELECT
ROW SHARE SELECT ... FOR UPDATE / FOR NO KEY UPDATE / FOR SHARE / FOR KEY SHARE
ROW EXCLUSIVE INSERT, UPDATE, DELETE, MERGE
SHARE UPDATE EXCLUSIVE VACUUM (not FULL), ANALYZE, CREATE INDEX CONCURRENTLY, REINDEX CONCURRENTLY, ALTER TABLE ... VALIDATE CONSTRAINT
SHARE CREATE INDEX (not CONCURRENTLY)
SHARE ROW EXCLUSIVE CREATE TRIGGER, ALTER TABLE ... ADD FOREIGN KEY (on both tables)
EXCLUSIVE REFRESH MATERIALIZED VIEW CONCURRENTLY
ACCESS EXCLUSIVE DROP TABLE, TRUNCATE, VACUUM FULL, CLUSTER, REINDEX, most ALTER TABLE forms including ADD COLUMN, LOCK TABLE with no mode

Which modes conflict (X means the requested mode must wait for the held one):

requested \ held AS RS RE SUE S SRE E AE
ACCESS SHARE X
ROW SHARE X X
ROW EXCLUSIVE X X X X
SHARE UPDATE EXCLUSIVE X X X X X
SHARE X X X X X
SHARE ROW EXCLUSIVE X X X X X X
EXCLUSIVE X X X X X X X
ACCESS EXCLUSIVE X X X X X X X X

Three facts in that matrix explain most production incidents. Only ACCESS EXCLUSIVE blocks a plain SELECT. A plain CREATE INDEX takes SHARE, which blocks every INSERT, UPDATE and DELETE on the table for as long as the build takes, minutes on a large table; CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, which does not, at the cost of two table scans and a failure mode that leaves an invalid index to drop. And SHARE UPDATE EXCLUSIVE conflicts with itself, so a manual VACUUM and an autovacuum on the same table cannot run together, and a CREATE INDEX CONCURRENTLY waits for an autovacuum. When an autovacuum worker blocks another statement for deadlock_timeout, the waiting backend cancels the autovacuum, except an anti-wraparound one, which does not yield.

The low modes are what Gray, Lorie and Putzolu called intention locks in 1975: ROW SHARE and ROW EXCLUSIVE say “I hold or will hold row locks inside this table”, so that a request for the whole table (ACCESS EXCLUSIVE, SHARE) can be refused by looking at one table-level entry, without checking every row.

Row locks, stored in the row

Row locks have four modes of their own:

requested \ held KEY SHARE SHARE NO KEY UPDATE UPDATE
FOR KEY SHARE X
FOR SHARE X X
FOR NO KEY UPDATE X X X
FOR UPDATE X X X X

An UPDATE that does not change a column in a unique index usable by a foreign key takes FOR NO KEY UPDATE; DELETE, and an UPDATE that changes such a column, take FOR UPDATE. A foreign-key check takes FOR KEY SHARE on the referenced row. The point of the split shows up in the shop: inserting an order_items row checks that its product_id exists by taking FOR KEY SHARE on that products row, and a concurrent UPDATE products SET price_cents = ... takes FOR NO KEY UPDATE. Those two do not conflict, so repricing a product does not block orders for it. Before Postgres 9.3 they did.

Postgres does not keep row locks in memory. A row lock is written into the locked tuple’s xmax (with a multixact id when several transactions share a lock), which is why SELECT ... FOR UPDATE dirties pages and generates WAL, and why there is no limit on how many rows one transaction can lock. A transaction that wants a row someone else has locked looks at xmax, sees the holder’s transaction id, and waits on a lock on that transaction id in the shared lock table. In pg_locks that appears as locktype = 'transactionid', mode = 'ShareLock', granted = false, not as a lock on the row. The waiter also takes a tuple lock on the row so that several waiters queue in order.

This is also why Postgres has no lock escalation. SQL Server keeps row and page locks in memory and, when one statement holds about 5000 locks on one table reference, or lock memory crosses a threshold, converts them into a single table lock, which can suddenly block every other session. Postgres’s equivalent knob, max_locks_per_transaction (default 64), sizes the shared table for object locks (tables, indexes, partitions), not rows; you meet it when one query touches thousands of partitions and fails with out of shared memory. The one place Postgres does promote is SERIALIZABLE’s predicate locks, from tuple to page to relation, covered in the previous chapter.

The lock queue and the migration trap

When a request conflicts with a lock that is held, it waits. When a request conflicts with a request that is already waiting, it also waits, even if it would be compatible with every lock currently held. Waiters are granted roughly in arrival order. Without that rule a stream of SELECTs, each compatible with the last, would starve an ALTER TABLE forever.

The consequence is the Predict above. An ALTER TABLE ... ADD COLUMN note text on orders takes milliseconds once it has the lock: since Postgres 11, adding a column with no default or a non-volatile default is a catalog change with no rewrite. But it needs ACCESS EXCLUSIVE, and if a ten-minute report holds ACCESS SHARE on orders, the ALTER waits ten minutes, and every query on orders that arrives in those ten minutes waits behind it. Connections pile up, the pool is exhausted, and the whole application stops, not only the parts that use orders.

The fix is to make the migration give up instead of waiting:

SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN note text;
-- ERROR:  canceling statement due to lock timeout   (SQLSTATE 55P03)

lock_timeout (default 0, disabled) bounds each single lock wait. The migration fails, nothing queued behind it for more than three seconds, and the migration tool retries a few times with a pause. Tools like Rails’s strong_migrations set it by default. Pair it with killing or avoiding the long transaction that held the lock: idle_in_transaction_session_timeout and transaction_timeout from the MVCC chapter help here too. For the operations that do need long strong locks, use the variants that avoid them: CREATE INDEX CONCURRENTLY; ADD CONSTRAINT ... NOT VALID then VALIDATE CONSTRAINT, which takes only SHARE UPDATE EXCLUSIVE for the scan; pg_repack instead of VACUUM FULL. The chapter on zero-downtime migrations in module four builds on this.

Deadlocks and the detector

A deadlock needs a cycle of waits. With row locks the classic shape is two transactions touching the same rows in opposite orders. Postgres does not check for cycles on every wait, because almost all waits end on their own. A waiting backend sleeps for deadlock_timeout (default 1 s) and only then builds the wait-for graph from the shared lock table. If it finds a cycle, it aborts one transaction in it, usually the one that ran the check, with:

ERROR:  deadlock detected
DETAIL:  Process 4121 waits for ShareLock on transaction 1530; blocked by process 4118.
Process 4118 waits for ShareLock on transaction 1531; blocked by process 4121.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "inventory"

SQLSTATE 40P01. The other transaction gets its lock and proceeds. The victim’s work is rolled back and the application must re-run the whole transaction, exactly as for a serialization failure; most retry wrappers treat 40001 and 40P01 the same way. The server log has both queries, which the client-side message does not.

The simulation below runs the transfer deadlock with the timing modelled: watch the clock tick to deadlock_timeout before the detector fires. Then run SLOW, NOT DEADLOCKED, which is the more common production case: one transaction holds a row lock while it calls a slow payment API, the other waits, the detector finds no cycle, and nothing aborts. A deadlock is resolved in one second. A long lock wait is resolved when the holder finishes, which may be never. The last two scenarios are the two fixes: touch rows in key order, or lock everything up front with one SELECT ... ORDER BY id FOR UPDATE.

▶ SIMULATION
T1: transfer 10 from 1 to 2
holds row locks: —
waits for: —
idle
accounts (row locks)
id 1: balance 100 · unlocked
id 2: balance 100 · unlocked
WAIT-FOR GRAPH · clock 0 ms
(no edges)
T2: transfer 25 from 2 to 1
holds row locks: —
waits for: —
idle
✓ no cycle in the wait-for graph✓ no transaction waits longer than 2000 ms for a row lock
SCHEDULE
01[T1]T1: UPDATE accounts SET balance = balance - 10 WHERE id = 1
02[T2]T2: UPDATE accounts SET balance = balance - 25 WHERE id = 2
03[T1]T1: UPDATE accounts SET balance = balance + 10 WHERE id = 2 → row 2 held by T2, WAIT
04[T2]T2: UPDATE accounts SET balance = balance + 25 WHERE id = 1 → row 1 held by T1, WAIT
05[DB]clock +500 ms
06[DB]clock +500 ms → deadlock_timeout: detector runs, picks a victim
07[T1]T1: COMMIT
08[T2]T2: app catches the error and RETRIES the transaction
09[T2]T2: UPDATE accounts SET balance = balance - 25 WHERE id = 2
10[T2]T2: UPDATE accounts SET balance = balance + 25 WHERE id = 1
11[T2]T2: COMMIT
Start of deadlock scenario. 11 steps.
-- T1: transfer 10 from 1 to 2         -- T2: transfer 25 from 2 to 1
BEGIN;                                 BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
                                       UPDATE accounts SET balance = balance - 25 WHERE id = 2;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;   -- waits for T2
                                       UPDATE accounts SET balance = balance + 25 WHERE id = 1;   -- waits for T1
-- ERROR 40P01 deadlock detected (one of them, after deadlock_timeout)
BREAK IT NOT YET

T1 updates row 1 then row 2. T2 updates row 2 then row 1. Interleave their statements so each one is waiting for a row the other holds.

GOAL: a cycle appears in the wait-for graph

The ordering rule is the one the deadlock lesson proves: if every transaction acquires locks in one global order, the wait-for graph cannot contain a cycle. In application code that means sorting the ids before a multi-row update (UPDATE ... WHERE product_id = ANY($1) locks rows in the order the scan finds them, which is not guaranteed to be your order; SELECT ... WHERE product_id = ANY($1) ORDER BY product_id FOR UPDATE first is). It also means one consistent order across tables: if checkout locks inventory then orders, refunds must not lock orders then inventory.

Lowering deadlock_timeout makes deadlocks resolve faster and makes every ordinary lock wait run the detector sooner. One second is about the smallest sensible value. Turn on log_lock_waits (default off) so that every wait longer than deadlock_timeout is logged with the blocking process; it is the cheapest lock diagnostics there is.

Advisory locks and SKIP LOCKED

Sometimes the thing you need to lock is not a row. Advisory locks are locks on an application-chosen 64-bit number, held in the same lock table and visible in pg_locks as locktype = 'advisory':

SELECT pg_advisory_xact_lock(hashtext('nightly-report'));   -- waits; released at COMMIT
SELECT pg_try_advisory_lock(42);                            -- true or false at once; held until unlock or disconnect

The _xact_ forms release at transaction end and are the ones to prefer. The session forms survive ROLLBACK, stack (lock twice, unlock twice), and are released only by pg_advisory_unlock or disconnecting, which interacts badly with transaction-mode connection poolers like PgBouncer: the lock stays with a server connection your client no longer owns. Use advisory locks for “only one instance of this cron job runs at a time”; do not use them where a row lock would do.

The other tool is SKIP LOCKED. A job queue in a table is usually written as “take the oldest queued job”:

SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE;

With four workers, all four want the same head row. One gets it; three wait on it. When the first commits, the other three re-check, find the row no longer queued, and move on to the next one, where they collide again. Four workers process jobs at the speed of one. FOR UPDATE SKIP LOCKED makes each worker skip rows another transaction has locked and take the next free one, so four workers take four different jobs at once. NOWAIT is the other option: fail with SQLSTATE 55P03 instead of waiting. The Postgres documentation warns that SKIP LOCKED gives an inconsistent view of the table, which is exactly what a queue wants and exactly what a report does not.

Seeing locks while they happen

pg_locks has one row per lock held or awaited. Joined to pg_stat_activity and pg_blocking_pids(), it answers “who is waiting, for what, behind whom”:

SELECT a.pid, a.state, now() - a.xact_start AS xact_age,
       a.wait_event_type, a.wait_event,
       pg_blocking_pids(a.pid) AS blocked_by,
       left(a.query, 60) AS query
FROM pg_stat_activity a
WHERE a.wait_event_type = 'Lock' OR a.pid IN (
  SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
ORDER BY a.xact_start;

SELECT l.pid, l.locktype, l.relation::regclass, l.transactionid, l.mode, l.granted, l.waitstart
FROM pg_locks l WHERE l.pid <> pg_backend_pid() ORDER BY l.granted, l.waitstart;

pg_blocking_pids handles the conflict rules and queue order for you, including the soft block where a session waits behind another waiter rather than a holder; writing that self-join on pg_locks by hand is hard to get right, which the documentation says outright. waitstart (since Postgres 14) tells you how long each waiter has waited. Calling pg_blocking_pids takes a brief exclusive lock on the lock manager’s state, so run it when diagnosing, not every second from a monitoring agent. Once you know the root blocker, pg_cancel_backend(pid) cancels its current query and pg_terminate_backend(pid) ends its session, which releases every lock it held.

LAB Deadlock the shop, read the locks, then build a queue ~40 MIN
YOU NEEDDocker Compose with the labs/databases stack running (Postgres 17, docs/LABS.md)Python 3.10+ with psycopg 3 (pip install 'psycopg[binary]')three terminals

1. Produce a deadlock. Open psql in terminals 1 and 2 with docker compose exec db psql -U atlas shop. Run these in the order of the comments; the third statement blocks, the fourth completes the cycle.

-- T1
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;
-- T2
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 2;
-- T1  (blocks: row 2 is T2's)
UPDATE inventory SET on_hand = on_hand + 1 WHERE product_id = 2;

Before running the last statement, go to terminal 3.

T1 hangs on its second update. Nothing is wrong yet: this is an ordinary lock wait, and it would end as soon as T2 committed.

2. Read the wait while it is happening. In terminal 3, open a third psql and run:

SELECT pid, wait_event_type, wait_event, pg_blocking_pids(pid) AS blocked_by, left(query, 50) AS query
FROM pg_stat_activity WHERE datname = 'shop' AND pid <> pg_backend_pid();

SELECT pid, locktype, relation::regclass, transactionid, mode, granted, waitstart
FROM pg_locks WHERE pid <> pg_backend_pid() AND locktype IN ('relation', 'transactionid', 'tuple')
ORDER BY granted, pid;
The first query shows T1 with wait_event_type = Lock, wait_event = transactionid, and blocked_by containing T2’s pid. The second shows one row with granted = f: T1 asking for ShareLock on T2’s transaction id, with a waitstart. You also see each session holding ExclusiveLock on its own transaction id, RowExclusiveLock on inventory and its primary key index, and T1 holding a tuple lock on inventory (its place in the queue for that row). There is no lock on row 2 itself; it is recorded in the row.

3. Close the cycle. In terminal 2:

-- T2
UPDATE inventory SET on_hand = on_hand + 1 WHERE product_id = 1;
About one second later (deadlock_timeout), one of the two sessions gets ERROR: deadlock detected with the DETAIL lines naming both processes and transaction ids, and CONTEXT: while updating tuple (...) in relation "inventory". Usually it is T2, which ran the check. The other session’s blocked statement completes. Type ROLLBACK; in the failed one and COMMIT; in the other. Run docker compose logs db | grep -A4 "deadlock detected" to see both full queries in the server log.

4. Fix by ordering. Repeat step 1 and 3, but make both transactions touch product_id = 1 first.

-- T1
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;
-- T2  (blocks on row 1, holding nothing)
BEGIN;
UPDATE inventory SET on_hand = on_hand + 1 WHERE product_id = 1;
-- T1
UPDATE inventory SET on_hand = on_hand + 1 WHERE product_id = 2;
COMMIT;
-- T2 continues
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 2;
COMMIT;
T2 waits on its first statement until T1 commits, then runs to completion. No error. T2 never held a lock T1 wanted, so no cycle could form. In application code, sort the ids before you update, or lock them all first with SELECT ... WHERE product_id = ANY('{2,1}') ORDER BY product_id FOR UPDATE.

5. The migration trap, and lock_timeout. Three terminals.

-- terminal 1: a long reader
BEGIN; SELECT count(*) FROM orders;
-- terminal 2: the migration
ALTER TABLE orders ADD COLUMN note text;
-- terminal 3: ordinary traffic
SELECT id, status FROM orders WHERE id = 1;
Terminal 2 hangs, and so does terminal 3, a primary-key lookup that should take a millisecond. pg_blocking_pids for terminal 3’s pid lists terminal 2’s pid (a soft block: it is queued behind a waiter, not a holder). COMMIT; in terminal 1 and both complete at once. Now run ALTER TABLE orders DROP COLUMN note;, start the reader again in terminal 1, and in terminal 2 run SET lock_timeout = '2s'; ALTER TABLE orders ADD COLUMN note text;. It fails after 2 seconds with canceling statement due to lock timeout, and a lookup in terminal 3 started during those 2 seconds waits at most that long. End terminal 1’s transaction when you are done.

6. A job queue with SKIP LOCKED. In any psql session, create a queue of 1000 jobs from paid orders:

CREATE TABLE jobs (id bigserial PRIMARY KEY, order_id bigint NOT NULL,
                   status text NOT NULL DEFAULT 'queued', worker int, attempts int NOT NULL DEFAULT 0);
INSERT INTO jobs (order_id) SELECT id FROM orders WHERE status = 'paid' ORDER BY id LIMIT 1000;

Save this as worker.py on the host:

import sys, threading, time
import psycopg

DSN = "postgresql://atlas:atlas@localhost:5432/shop"   # your SHOP_PORT instead of 5432 if you set one
SKIP = "" if "--no-skip" in sys.argv else " SKIP LOCKED"

def worker(n):
    with psycopg.connect(DSN, autocommit=True) as conn:
        while True:
            with conn.transaction():
                row = conn.execute(
                    f"SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE{SKIP}"
                ).fetchone()
                if row is None:
                    return
                time.sleep(0.01)                       # the work: 10 ms per job
                conn.execute("UPDATE jobs SET status = 'done', worker = %s, attempts = attempts + 1 WHERE id = %s",
                             (n, row[0]))

t0 = time.perf_counter()
threads = [threading.Thread(target=worker, args=(n,)) for n in range(4)]
[t.start() for t in threads]; [t.join() for t in threads]
print(f"elapsed {time.perf_counter() - t0:.1f}s")
with psycopg.connect(DSN) as conn:
    print(conn.execute("SELECT worker, count(*), max(attempts) FROM jobs GROUP BY worker ORDER BY worker").fetchall())
    conn.execute("UPDATE jobs SET status = 'queued', worker = NULL, attempts = 0")
python3 worker.py
python3 worker.py --no-skip
With SKIP LOCKED: elapsed about 3 s (1000 jobs at 10 ms each, divided across 4 workers, plus round trips), roughly 250 jobs per worker, and max(attempts) of 1 for every worker, so no job ran twice. With --no-skip: about 11 s or more, the same as one worker, because all four queue on the head row and only one is ever doing work; the counts per worker are uneven. The script resets the queue after each run. While the --no-skip run is going, the step 2 query in a psql session shows three sessions waiting on a transactionid.
Drop the ORDER BY id from the worker’s SELECT and run the SKIP LOCKED version again: it still works, but jobs are no longer taken oldest first, which matters if your queue promises order. Then change the worker to hold its transaction open across a 2-second sleep and kill the script with Ctrl-C midway: the jobs those workers had locked return to queued the moment the connections close, because a row lock dies with its transaction. That is the property that makes a table-backed queue safe, and the reason not to replace the row lock with a status = 'running' update committed before the work. Drop the table with DROP TABLE jobs;.
DECIDE

You need a new index on order_items(product_id) for a product page query. order_items has 6 million rows and takes about 300 inserts per second during the day. A plain CREATE INDEX takes 40 seconds on a staging copy. Your migration tool wraps every migration in a transaction and sets lock_timeout = 5s. What do you run?

READING
  1. DOC
    Explicit Locking

    The table and row lock modes, both conflict matrices, deadlocks and advisory locks, from the source. Read all of section 13.3, then keep Table 13.2 open whenever you write a migration.

  2. DOC
    pg_locks

    What each column means, why row locks appear as transactionid waits, and why you should call pg_blocking_pids rather than writing your own self-join. Short; read the notes at the end.

  3. POST
    Zero-downtime Postgres migrations: the hard parts Chris Sinjakli (GoCardless)

    The lock-queue outage from the Why, told by the team it happened to, with the lock chain drawn out and the lock_timeout fix. Read it for the diagnosis; the specific lock modes are from an older Postgres version.

  4. PAPER
    Granularity of Locks in a Shared Data Base Jim Gray, Raymond Lorie and Gianfranco Putzolu, 1975

    Where intention locks and the lock compatibility matrix come from. Postgres's ROW SHARE and ROW EXCLUSIVE are this paper's IS and IX. Read the hierarchy and compatibility sections; the DAG-of-resources generalisation can be skipped. Read: the sections on hierarchical locks, intention modes and the compatibility matrix.

  5. BOOK
    PostgreSQL 14 Internals Egor Rogov, 2022

    Part III shows the lock manager from the inside: the shared lock table, fast-path locks, how row locks become multixacts in xmax, and how the wait queue is ordered. Free PDF; the clearest account of why a row lock appears as a transactionid wait. Read: Part III: Relation-Level Locks, Row-Level Locks, Miscellaneous Locks, Locks in Memory.

  6. CODE
    strong_migrations Andrew Kane

    A catalogue of which schema changes take which locks on Postgres and MySQL, with the safe alternative for each and a default lock_timeout. Useful even if you do not use Rails: read the README's list of dangerous operations as a checklist.

  7. DOC
    Transaction locking and row versioning guide (SQL Server)

    The lock escalation section describes the 5000-lock threshold and memory-based escalation that Postgres does not have. Read only that section, to understand the behaviour colleagues coming from SQL Server expect.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: The query planner: statistics, cost, join algorithms →