Sub topic 5
Waiting for locks: the queue and how blocking chains form
This chapter assumes you know how locks last until the end of a transaction, and you know the table-level lock modes and the row-level FOR clauses from the earlier chapters. You should be able to run two or three psql sessions side by side. Here you will see what happens when a lock request cannot be granted immediately, why one stuck session can stop many others, and how to recognize the shape of a blocking chain.
What a lock wait is
When a statement asks for a lock that conflicts with a lock another transaction holds, PostgreSQL does not return an error. The session goes to sleep and waits until the lock is released or a timeout fires. From the client's side the statement simply hangs. In pg_stat_activity the session shows state = 'active' and wait_event_type = 'Lock'.
A wait ends in one of these ways:
- The holder commits or rolls back, and the lock is granted.
- A timeout fires (
lock_timeoutorstatement_timeout), and the waiter gets an error. - The client cancels the query.
- The deadlock detector aborts one transaction (covered in later chapters).
A wait is not a failure. Short waits are normal in any busy database. The trouble starts when the holder is slow or idle, because every session that needs the same lock then piles up behind it.
Every lockable object has a queue
For each lockable object (a table, a transaction ID, a tuple), PostgreSQL's lock manager keeps the granted locks and a queue of waiting requests. When a new request arrives, PostgreSQL checks it against two things:
- The locks already granted on that object.
- The requests already waiting in the queue ahead of it.
The second check is the part that surprises people. A new request that does not conflict with any granted lock still has to wait if it conflicts with a request that is already waiting. This keeps a stream of compatible requests from starving a waiting request that needs a stronger lock.
Waiters are served roughly in arrival order. PostgreSQL may reorder the queue when that lets it avoid a deadlock, but you should treat the order as first come, first served.
Blocking chains with row locks
Take the accounts table from the earlier chapters and run three sessions against the same row.
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B (blocks, waiting for A)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- Session C (blocks, waiting for B)
UPDATE accounts SET balance = balance + 7 WHERE id = 1;A holds the row lock because it has an uncommitted update on the row. B finds that the row version is being modified by A's transaction and waits for A's transaction to finish. C arrives while B is already waiting.
Row locks are not stored in the shared lock table the way table locks are. They are recorded in the row itself, as the ID of the transaction that locked it. So when B has to wait, it waits for a lock on A's transaction ID, which A holds until it ends. To keep many waiters from all contending on that one transaction ID, PostgreSQL first takes a short-lived lock on the tuple (the row version) itself. B holds that tuple lock while it waits for A. C cannot get the tuple lock, so C waits for B.
You can see this in pg_locks:
| Session | Waiting for | `locktype` in `pg_locks` |
|---|---|---|
| B | A's transaction to end | `transactionid` |
| C | B to release the tuple lock | `tuple` |
The result is a chain: C waits for B, and B waits for A. When A commits, B wakes up, performs its update, and commits. Only then can C proceed. Throughput on that row is one transaction at a time, and each one waits for everything ahead of it.
The session at the right end of a chain is the root blocker. It is not waiting for anything. It holds a lock and has not finished. Fixing a chain means dealing with the root blocker, not the sessions at the left.
Why the root blocker is often idle
A root blocker is frequently not running a query at all. It may be a session that ran BEGIN, did some work, and then stopped. The application might be waiting on an HTTP call, a user, or a crashed worker that never sent COMMIT. Its pg_stat_activity.state is idle in transaction.
SELECT pid, state, xact_start, now() - xact_start AS xact_age,
left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;The query column shows the last statement the session ran, not what it is doing now, because it is doing nothing. Row locks and table locks taken by that transaction stay held. Nothing in PostgreSQL releases them until the transaction ends or the connection drops. The idle_in_transaction_session_timeout setting exists for this case and is covered in the chapter on timeouts.
The table-level queue and the pile-up behind DDL
The queue rule has its most damaging effect with table locks. Most ALTER TABLE forms need an ACCESS EXCLUSIVE lock, which conflicts with every other mode, including the ACCESS SHARE lock that a plain SELECT takes.
-- Session 1: a long report that has not finished
BEGIN;
SELECT count(*) FROM accounts;
-- the transaction stays open; ACCESS SHARE is held until it ends
-- Session 2: a schema change
ALTER TABLE accounts ADD COLUMN note text;
-- waits: ACCESS EXCLUSIVE conflicts with session 1's ACCESS SHARE
-- Session 3: an ordinary query from the application
SELECT * FROM accounts WHERE id = 1;
-- waits tooSession 3's SELECT asks for ACCESS SHARE. That mode does not conflict with session 1's ACCESS SHARE, so on its own it would run immediately. But session 2's ACCESS EXCLUSIVE request is already in the queue, and session 3's request conflicts with it. Session 3 therefore waits behind session 2.
From then on, every new query on accounts joins the queue. The ALTER TABLE may need only a few milliseconds of actual work, but it has made the table unavailable to all other queries while it waits for one slow transaction.
A short lock_timeout on the migration limits the damage. If the ALTER TABLE cannot get its lock within two seconds, it fails and leaves the queue, and the waiting application queries continue.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;The migration can then be retried when the long transaction is gone. The safe migration chapter returns to this pattern.
Chains can mix lock types
A real chain often combines lock kinds. For example:
- A batch job holds row locks on many rows and stays open.
- An application request updates one of those rows and waits for the batch job.
- A migration requests
ACCESS EXCLUSIVEon the table. It waits for the application request, which holds aROW EXCLUSIVEtable lock while it is blocked. - Every other query on the table then queues behind the migration.
Nothing here is a deadlock, because nothing waits in a circle. It is a long chain with a single root blocker, the batch job. The picture looks alarming because the sessions at the end of the chain are the ones users notice, while the cause is far away from them.
Reading a chain with pg_blocking_pids()
The function pg_blocking_pids(pid) returns the process IDs that a session is waiting for. That includes sessions holding a conflicting lock and sessions ahead of it in the queue with a conflicting request. For the three-session row example, the answer for session C is B, and the answer for B is A.
SELECT a.pid,
pg_blocking_pids(a.pid) AS blocked_by,
a.state,
a.wait_event_type,
a.wait_event,
left(a.query, 60) AS query
FROM pg_stat_activity AS a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;To find the root blockers, look for PIDs that appear in a blocked_by array but are not themselves blocked. The next chapter builds on this query and on pg_locks to do that systematically.
Common mistakes
- Treating the waiting session as the problem. Cancelling or restarting waiters does nothing for the root blocker, and the next requests simply queue again.
- Running a migration without
lock_timeout. The migration waits indefinitely, and with it everything that needs the table. - Wrapping slow external work in a transaction. Calling an API, sending an email, or waiting for user input between statements keeps locks held for as long as that takes.
- Assuming a non-conflicting query will always run. Under the queue rule, a request that conflicts with nothing granted can still wait behind a queued stronger request.
- Running a long
SELECTinside a transaction that stays open. A transaction that read from a table holdsACCESS SHAREon it until the end. This is harmless until someone needs a stronger lock.
Summary of the working model
- A request that cannot be granted waits in a per-object queue.
- A new request must be compatible with granted locks and with waiters ahead of it.
- Row-lock waiters line up behind the first waiter through a tuple lock, and the first waiter waits on the holder's transaction ID.
- A chain has one root blocker, which holds a lock and is not waiting. It is often
idle in transaction. - A queued
ACCESS EXCLUSIVErequest turns a harmless long read into a table-wide stall. - A circular wait is a deadlock. A chain with no cycle is only a slow release and ends when the root blocker finishes.
Exercise
Session 1 runs BEGIN and SELECT count() FROM orders, then stays idle. Session 2 runs ALTER TABLE orders ADD COLUMN flag boolean and hangs. Session 3 then runs SELECT FROM orders WHERE id = 5 and also hangs, even though session 1's read and session 3's read are compatible. Explain why session 3 hangs, name the root blocker, and give one change to the migration that would stop the pile-up.
Show answer
Session 3 hangs because the queue rule makes it conflict with session 2's waiting ACCESS EXCLUSIVE request, even though it does not conflict with session 1's granted ACCESS SHARE lock. Session 1 is the root blocker: it holds a lock, waits for nothing, and its open transaction keeps the lock until it ends. Setting a short locktimeout for the migration (for example SET LOCAL locktimeout = '2s' inside the transaction) makes the ALTER TABLE fail and leave the queue if it cannot get its lock quickly, so session 3 and later queries are released. Ending session 1's transaction also clears the chain.
Exercise
Three sessions update the same row. Session A holds the update, B updates first after A, and C after B. Which session waits on A's transaction ID, which session waits on a tuple lock, and which session is the root blocker?
Show answer
B waits on A's transaction ID (a transactionid wait), and C waits on the tuple lock that B holds while it waits. Session A is the root blocker because it holds the row lock and is not waiting for anything. When A commits, B proceeds, and C proceeds after B finishes.