the lock queue
a long SELECT, an ALTER TABLE behind it, and every query behind that frozen. lock_timeout saves the day.
- address
- everything.locking.lock_queue
- part
- part 15, locks and concurrency control
- chapter
- chapter 6 of 10
- reading time
- 10 min
a lock request doesn't just check the locks that are held. it also checks the ones that are queued. so an ALTER TABLE waiting behind one slow read makes every query after it wait too, even plain SELECTs that don't conflict with the read at all. one migration, a whole table frozen. the fix: run DDL with lock_timeout, so it gives up after a moment, and retry.
the picture
you know the migration that "only adds a column"? it runs in a few milliseconds on staging. in production, the site goes down for a minute, and the ALTER wasn't slow at all. it was waiting.
think of a one-lane bridge with a single rule: first come, first served. a cyclist (a long report) is on the bridge. a truck (the ALTER, which needs the whole bridge) pulls up and waits. a second cyclist arrives. there's plenty of room beside the first cyclist, but the truck is ahead in line, so the second cyclist waits behind the truck. so does everyone after.
here it is on a real postgres 18.6 server with four sessions: a report holding a read lock, a migration, and two ordinary reads.
T1 is a report. it opens a transaction and reads accounts, so it holds ACCESS SHARE on the table until it ends.
that's the whole outage. T2's ALTER needs ACCESS EXCLUSIVE, the one table lock mode that conflicts with everything, including the ACCESS SHARE every SELECT takes. it can't have it while T1's report is open, so it waits. that part is fine. the problem is T3: its ACCESS SHARE is compatible with T1's, and it waits anyway.
why the reader waits
postgres's lock manager keeps one queue per locked object. a new request is granted only if it conflicts with nothing held and with nothing already waiting ahead of it. T3's ACCESS SHARE conflicts with T2's queued ACCESS EXCLUSIVE, so T3 goes to the back of the line.
that rule is on purpose. without it, a steady stream of readers would keep the table permanently share-locked, and the ALTER would starve: wait forever while reader after reader slipped past. first come, first served means the ALTER does get its turn. the price is that while it waits, it blocks like it already had the lock.
you can watch the chain form. pg_blocking_pids(pid) lists the sessions blocking a given one, both kinds: those holding a lock it needs, and those queued ahead of it for a lock it conflicts with. here's that query at step 5, with each pid swapped for its session name:
SELECT a.application_name AS session, l.mode, l.granted,
ARRAY(SELECT b.application_name FROM pg_stat_activity b
WHERE b.pid = ANY (pg_blocking_pids(a.pid))
ORDER BY b.application_name) AS blocked_by
FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.locktype = 'relation' AND l.relation = 'accounts'::regclass
ORDER BY l.granted DESC, l.waitstart NULLS FIRST, a.application_name;| sessiontext | modetext | grantedbool | blocked_by_text |
|---|---|---|---|
| T1 | AccessShareLock | t | {} |
| T2 | AccessExclusiveLock | f | {T1} |
| T3 | AccessShareLock | f | {T2} |
| T4 | AccessShareLock | f | {T2} |
waitstart (when each wait began) gives the queue order. the manual calls T2's block on T3 a "soft" block, and watching locks with pg_locks turns this query into one you can keep in your pocket.
/* T1 */ BEGIN; SELECT sum(balance) FROM accounts; -- holds ACCESS SHARE
/* T2 */ ALTER TABLE accounts ADD COLUMN note text; -- waiting
/* T3 */ SELECT balance FROM accounts WHERE id = 1; -- ?lock_timeout saves the day
the dangerous part isn't the ALTER. adding a nullable column is a catalog change that takes milliseconds once the lock is granted. the dangerous part is the waiting. so cap it:
SHOW lock_timeout;
SET lock_timeout = '2s';
SHOW lock_timeout;| lock_timeouttext |
|---|
| 0 |
| lock_timeouttext |
|---|
| 2s |
0 means no limit, which is the default. with a limit, a statement that waits longer than that for any one lock gives up. that's round two in the figure: T2 queued for two seconds, gave up, and the moment it left the queue, T3 got its ACCESS SHARE. T1's report never noticed a thing. this is what T2 got:
- ERROR: canceling statement due to lock timeout
two seconds of blocked reads instead of an outage that lasts as long as the slowest report. pick the number by asking how long your app can tolerate every query on that table stalling: often well under a second.
the safe migration
a migration that can time out needs to be retried. the pattern: short lock_timeout, try, and on 55P03 wait a bit and try again, a bounded number of times. most migration tools can do this; in plain SQL it's a loop:
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric(12,2) NOT NULL);
DO $$
BEGIN
FOR attempt IN 1..5 LOOP
BEGIN
SET LOCAL lock_timeout = '500ms';
ALTER TABLE accounts ADD COLUMN note text;
RETURN; -- got the lock, done
EXCEPTION WHEN lock_not_available THEN
PERFORM pg_sleep(attempt); -- back off, then try again
END;
END LOOP;
RAISE EXCEPTION 'could not get the lock after 5 tries';
END $$;
SELECT column_name FROM information_schema.columns
WHERE table_name = 'accounts' ORDER BY ordinal_position;| column_namename |
|---|
| id |
| balance |
| note |
in the browser nothing else holds the table, so it gets the lock on the first try. on a busy server, each failed attempt costs at most half a second of queued reads, and the sleeps in between let the queue drain. (SET LOCAL keeps the timeout to this transaction. a DO block is one transaction, so on a retry the earlier attempt's work is already rolled back to the savepoint the BEGIN ... EXCEPTION block makes.)
the rest of the checklist:
- one lock-heavy statement per transaction. a migration that runs
ALTER TABLEand then spends ten seconds backfilling inside the same transaction holds ACCESS EXCLUSIVE for ten seconds. commit the DDL, backfill in batches afterwards. - look before you leap. a session that's been
idle in transactionfor an hour holds its locks for an hour, and the ALTER will queue behind it.pg_stat_activityandpg_locksshow you who's there (pg_locks), andidle_in_transaction_session_timeoutstops them piling up (idle in transaction). - pick the weaker lock when there is one.
CREATE INDEX CONCURRENTLYinstead ofCREATE INDEX,ADD CONSTRAINT ... NOT VALIDthenVALIDATE CONSTRAINT(SHARE UPDATE EXCLUSIVE, which lets reads and writes go on). table lock modes shows which statement takes which.
one level deeperwhat about autovacuum?
autovacuum holds SHARE UPDATE EXCLUSIVE while it works on a table, and an ALTER conflicts with that. the manual says a conflicting lock request interrupts autovacuum, so the ALTER only waits a moment. the exception is an autovacuum running to prevent transaction id wraparound (its query in pg_stat_activity ends with "(to prevent wraparound)"): that one isn't interrupted, and a migration queued behind it freezes the table like a long report would. one more reason for lock_timeout. freezing and wraparound has the rest.
keylines
- a lock request has to get past the holders and the queue. a waiting ACCESS EXCLUSIVE blocks every reader behind it.
- the queue is first come, first served so the ALTER can't starve. the cost: while it waits, it blocks like a holder.
- the ALTER is fast. the wait is the outage.
- SET lock_timeout before DDL. 55P03 means nothing happened: wait, retry.
- one lock-heavy statement per transaction, and look for idle transactions first.