It is 2 pm and you ship a migration. One line: ALTER TABLE orders ADD COLUMN note text;.
On a table with millions of rows this takes a few milliseconds. You have run
a hundred like it.
Today the site stops. Pages hang, the connection pool fills up, and the alerts
start. The ALTER TABLE did not do anything wrong. It is just waiting. An
analyst started a report on orders four minutes ago, and the ALTER is stuck
behind it. Worse, every new query on orders is now stuck behind the ALTER.
This outage is common, and it is always a surprise the first time. The cause
is a lock request waiting in line. The cure is a short lock_timeout on every
migration, plus a query that shows who is blocking whom.
Short version:
- A lock request waits in line. A waiting
ACCESS EXCLUSIVErequest (the lock mostALTER TABLEcommands need) blocks every query that arrives after it, even plainSELECTs. - Find the blocker with
pg_stat_activityandpg_blocking_pids(). Setlock_timeoutin every migration, and retry when it fires. - Deadlocks come from taking locks in different orders. Lock rows in the same order everywhere, and retry the transaction when PostgreSQL aborts one.
The outage: a queue, not a crash
Here is the whole outage as a timeline:
Three facts add up to this:
- A plain
SELECTtakes a lock on the table (ACCESS SHARE) and keeps it until its transaction ends. A report that runs for four minutes holds it for four minutes. ALTER TABLEneedsACCESS EXCLUSIVE. That mode conflicts with every other mode, includingACCESS SHARE. So theALTERmust wait for the report.- The
ALTERjoins the line. Queries that arrive later would be fine with the report, but they are not fine with a waitingALTERahead of them. They wait too.
I reproduced this on PostgreSQL 17 with three sessions. This is what
pg_locks showed:
locktype | relation | mode | granted | pid
----------+----------+---------------------+---------+-----
relation | orders | AccessShareLock | t | 87 <- the slow report
relation | orders | AccessExclusiveLock | f | 94 <- the ALTER, waiting
relation | orders | AccessShareLock | f | 101 <- a plain SELECT, waiting
The last row is the surprise. A plain read is waiting, and nothing that holds
a lock conflicts with it. It waits only because the ALTER is ahead of it.
Table-level lock modes
PostgreSQL has 8 table-level lock modes. You do not need to memorise them. You
need to know which commands take which mode, and which pairs conflict.
PostgreSQL takes these locks for you. You only name one when you run
LOCK TABLE.
| Mode | Taken by (from the docs) |
|---|---|
ACCESS SHARE | SELECT, and any query that only reads |
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, CREATE STATISTICS, COMMENT ON, some ALTER TABLE forms |
SHARE | CREATE INDEX (without CONCURRENTLY) |
SHARE ROW EXCLUSIVE | CREATE TRIGGER, some ALTER TABLE forms |
EXCLUSIVE | REFRESH MATERIALIZED VIEW CONCURRENTLY |
ACCESS EXCLUSIVE | DROP TABLE, TRUNCATE, REINDEX, CLUSTER, VACUUM FULL, REFRESH MATERIALIZED VIEW, many ALTER TABLE forms, and LOCK TABLE with no mode |
Here is which pairs conflict. A filled cell means two transactions cannot hold those two modes on the same table at the same time:
Five patterns to remember from that grid:
- Reads and writes do not block each other at table level.
ACCESS SHAREandROW EXCLUSIVEdo not conflict, and twoROW EXCLUSIVElocks do not conflict either. Any number ofUPDATEs can run on one table. Two of them only wait for each other when they touch the same row (see the next section). - Only
ACCESS EXCLUSIVEblocks a plainSELECT. The docs say so directly. CREATE INDEXwithoutCONCURRENTLYblocks writes. It takesSHARE, which conflicts withROW EXCLUSIVE. Reads still work.- Any open transaction that wrote to the table also blocks an
ALTER.ROW EXCLUSIVE(andROW SHARE, fromSELECT ... FOR UPDATE) conflicts withACCESS EXCLUSIVE, and it stays untilCOMMIT. A forgottenBEGINafter anUPDATEis as bad as a slow report. - A few modes conflict with themselves.
SHARE UPDATE EXCLUSIVEis why twoVACUUMs, or aVACUUMand aCREATE INDEX CONCURRENTLY, cannot run on the same table together.
A lock is held until the transaction ends. A transaction never conflicts with itself.
The lock queue
When a lock request cannot be granted, it waits. Everything that arrives later
and conflicts with that waiting request waits behind it, even if it would
have been fine with the lock holders. The PostgreSQL docs call this a “soft
block” in the page for pg_blocking_pids(): a process is blocked by someone who
is waiting for a conflicting lock and is ahead of it in the wait queue.
That is why the outage happens, and why it is so quick. The ALTER itself is
fast. What hurts is the time it spends in line, because it holds up everybody
behind it.
Some ALTER TABLE forms need weaker locks, so they cause less trouble:
ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE, and VALIDATE CONSTRAINT takes
SHARE UPDATE EXCLUSIVE. The docs say that ACCESS EXCLUSIVE is the rule
unless a page says otherwise, so read the page for each command before you run
it.
Row-level locks
Table locks are about commands that change the table’s shape. Row locks are
about two transactions that want the same row. They are separate: an UPDATE
takes a ROW EXCLUSIVE lock on the table and a row lock on each row it
changes.
There are 4 row lock modes, from strongest to weakest:
| Row lock | Taken by |
|---|---|
FOR UPDATE | SELECT ... FOR UPDATE, every DELETE, and an UPDATE that changes a column with a unique index that a foreign key could use |
FOR NO KEY UPDATE | SELECT ... FOR NO KEY UPDATE, and every other UPDATE |
FOR SHARE | SELECT ... FOR SHARE |
FOR KEY SHARE | SELECT ... FOR KEY SHARE, and foreign key checks on the referenced row |
The point of the two weak modes is foreign keys. When you insert a row into
order_items, PostgreSQL checks that the matching row in orders exists. It
takes FOR KEY SHARE on that orders row while it checks, so nobody can
delete the order underneath you. An UPDATE orders SET status = 'paid' only
takes FOR NO KEY UPDATE, which does not conflict with FOR KEY SHARE. So
updating an order never blocks inserts of its items. (This arrived in
PostgreSQL 9.3. I checked it on PostgreSQL 17: an insert into the child table
waited on a parent row held with FOR UPDATE, and went straight through when
the parent row was held with FOR NO KEY UPDATE.)
Other things worth knowing:
- Row locks do not block plain
SELECTs. They block only writers and other lockers of the same row. - Row locks are not in
pg_locks. They live on disk, not in memory. A session waiting for a row shows up as waiting for the transaction ID of the session that holds the row. That is whywait_eventsaystransactionid. - There is no lock escalation. The docs say there is no limit on the number of rows locked at once. Locking a million rows does not turn into a table lock. It does cost disk writes, though.
- Row locks wait forever by default.
SELECT ... FOR UPDATE NOWAITerrors at once instead of waiting, andSKIP LOCKEDskips locked rows. The job queue post builds a whole queue onSKIP LOCKED.
Find the blocker
When the site is slow and you suspect locks, you want one answer: who is
blocking whom? pg_locks has the raw rows, but the docs themselves call
joining it to itself “very difficult to get right in detail”. Use
pg_blocking_pids() instead. It takes the PID of a waiting session and returns
the PIDs of the sessions in its way.
Copy this query:
SELECT
blocked.pid AS blocked_pid,
blocked.wait_event_type,
blocked.wait_event,
now() - blocked.query_start AS waiting_for,
left(blocked.query, 40) AS blocked_query,
blocker.pid AS blocker_pid,
blocker.state AS blocker_state,
now() - blocker.xact_start AS blocker_xact_age,
left(blocker.query, 40) AS blocker_last_query
FROM pg_stat_activity AS blocked
CROSS JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid)
LEFT JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
WHERE blocked.wait_event_type = 'Lock'
ORDER BY waiting_for DESC;
This is what it printed for the outage above:
blocked_pid | 94
wait_event | relation
waiting_for | 00:00:03.03
blocked_query | alter table orders add column note text;
blocker_pid | 87
blocker_state | active
blocker_xact_age | 00:00:04.04
blocker_last_query | select pg_sleep(20);
blocked_pid | 101
wait_event | relation
waiting_for | 00:00:02.01
blocked_query | select * from orders where id=1;
blocker_pid | 94
blocker_state | active
blocker_last_query | alter table orders add column note text;
How to read it:
- Follow the chain to the root. Here 101 waits for 94, and 94 waits for 87. The root is 87, a PID that blocks others but is not blocked. Fixing 87 frees everyone.
- Look at
blocker_state.activemeans a slow query.idle in transactionmeans the session ran something, then stopped withoutCOMMIT. For a session that is not running a query,queryshows the last statement it ran, which is often a hint about which code forgot to commit. - A blocker PID of 0 is a prepared transaction. It has no row in
pg_stat_activity, so theLEFT JOINkeeps it in the output. Look atpg_prepared_xacts.
Then you can act. Both functions need the right to signal that backend: the
same role, a role that is a member of it, or pg_signal_backend.
SELECT pg_cancel_backend(87); -- cancels the running query, keeps the session
SELECT pg_terminate_backend(87); -- ends the session and rolls back its transaction
Cancel first. A session that is idle in transaction has no query to cancel,
so that one needs pg_terminate_backend.
The docs warn that calling pg_blocking_pids() often can slow the database a
little, because it needs short exclusive access to the lock manager’s shared
state. Run it when you investigate. Do not run it every second from a monitor.
For a lighter, always-on signal, set log_lock_waits = on. It writes a log
line when a session waits longer than deadlock_timeout (1 second by default).
Timeouts: stop waiting forever
By default PostgreSQL waits forever for a lock. Three settings fix that. They
all default to 0, which means disabled.
| Setting | What it stops | Error you see |
|---|---|---|
lock_timeout | A statement that waits too long for a lock. Only counts waiting, not running | canceling statement due to lock timeout (55P03) |
statement_timeout | A statement that runs too long, for any reason | canceling statement due to statement timeout (57014) |
idle_in_transaction_session_timeout | A session that sits in an open transaction doing nothing | The connection is closed (25P03) |
Use each one where it fits:
-- At the top of every migration:
SET lock_timeout = '2s';
-- For the app's role: kill sessions that hold a transaction open and do nothing.
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';
-- For a role that runs reports: a ceiling so one report cannot run for hours.
ALTER ROLE reporting SET statement_timeout = '5min';
The numbers are examples, not advice for your system. Pick them from how long your normal queries take. Two rules from the docs:
- Do not put
lock_timeoutorstatement_timeoutinpostgresql.conf. It would hit every session, includingVACUUMand your own admin work. Set them per session or per role. - If
statement_timeoutis set, alock_timeoutequal to it or larger is pointless, because the statement timeout always fires first.
The statement_timeout on the report role is what would have prevented the
outage from the start. The analyst’s query would have been cancelled after a
few minutes, instead of holding a lock until the whole site fell over.
Deadlocks
A deadlock is two transactions that each hold a lock the other one wants. No one can ever finish by waiting.
You can try it with two sessions:
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 500), (2, 500);
-- Session A -- Session B
BEGIN; BEGIN;
UPDATE accounts SET balance = balance - 100
WHERE id = 1;
UPDATE accounts SET balance = balance - 50
WHERE id = 2;
UPDATE accounts SET balance = balance + 100
WHERE id = 2; -- waits for B
UPDATE accounts SET balance = balance + 50
WHERE id = 1; -- waits for A: deadlock
About a second later, one session gets this (the PIDs and transaction numbers will differ):
ERROR: deadlock detected
DETAIL: Process 137 waits for ShareLock on transaction 753; blocked by process 130.
Process 130 waits for ShareLock on transaction 754; blocked by process 137.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,1) in relation "accounts"
What is going on:
- PostgreSQL does not check for a deadlock the moment a session starts to wait.
The check is costly. It waits
deadlock_timeoutfirst (default 1 second) and checks only if the lock is still not free. Most waits end sooner, so most waits never pay for the check. - The detector aborts one transaction in the cycle and lets the others go on. The docs say you cannot predict which one, and you should not rely on it.
- The error code is
40P01. Everything the aborted transaction did is rolled back. - Deadlocks do not need
LOCK TABLE. Plain row updates, as above, are enough.
To find the two statements behind a real one, and the foreign key and batch shapes, see ERROR: deadlock detected.
How to prevent them, in order of value:
Take locks in the same order everywhere. This is the docs’ best defence. If both sessions above had updated account 1 first, one would have waited for the other, and there would be no cycle. When you move money between two accounts, always touch the lower id first, or lock both rows up front in a fixed order:
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR NO KEY UPDATE;Take the strongest lock you need first. The docs advise that the first lock on an object should be the most restrictive one you will need. Two sessions that start with
FOR SHAREand both try to upgrade will deadlock.Keep transactions short. Less time holding locks means fewer chances to meet.
Retry. If you cannot be sure about the order, catch
40P01and run the whole transaction again. This is only safe when the transaction can run twice without a bad effect, which is the same problem the post on idempotency keys solves.
Do not raise deadlock_timeout to hide deadlocks. A higher value only slows
the report of real ones. The deadlock is still there; you hear about it later. The docs suggest raising it on a heavily loaded
server, so that it is longer than your usual transaction time.
Idle in transaction: the quiet lock holder
A session in state idle in transaction ran BEGIN, ran some statements, and
is now waiting for the client to send the next command. Every lock it took is
still held. If the client forgot to commit, the locks stay until someone
notices.
The usual causes:
- Code that opens a transaction, then calls a slow web service before it commits.
- A developer who ran
BEGINin a console and went to lunch. - A connection pool or ORM that leaves a transaction open after an error.
Find them:
SELECT pid, now() - xact_start AS open_for, state, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY xact_start;
Set idle_in_transaction_session_timeout on the app role, as shown above. The
docs say the setting exists to make sure idle sessions do not hold locks for an
unreasonable time. It also helps with bloat. An open transaction stops VACUUM
from removing recently dead rows that only it can still see.
The fix in code is to keep slow work outside the transaction. If you must call another service after a write, save an event row in the same transaction and send it later. That is the transactional outbox pattern.
A pile of these sessions also uses up connection slots. When the database starts refusing logins, see FATAL: sorry, too many clients already.
Safe migrations
Now you can see why the dangerous part of a migration is rarely the work. It is the wait for the lock. The recipes below keep both small.
1. Set lock_timeout and retry
A short lock_timeout turns “queue everyone behind me” into “give up quickly
and try again”:
for i in 1 2 3 4 5; do
psql -v ON_ERROR_STOP=1 \
-c "SET lock_timeout = '2s'; ALTER TABLE orders ADD COLUMN note text;" \
&& break
sleep $((i * 5))
done
If the table has a slow query on it, the ALTER fails after 2 seconds, and
the retry loop waits and tries again. The cost is that the ALTER still holds
up other queries for up to those 2 seconds. Keep the timeout small. The
numbers here are a starting point, not a rule.
2. Add a column with a constant default
Since PostgreSQL 11, ADD COLUMN ... DEFAULT with a constant does not rewrite
the table. The value goes into the catalog and is read back for old rows. The
current docs word it as “non-volatile”, which also covers now():
-- Fast: no rewrite
ALTER TABLE orders ADD COLUMN status text NOT NULL DEFAULT 'new';
-- Slow: a volatile default rewrites the whole table
ALTER TABLE orders ADD COLUMN token uuid DEFAULT gen_random_uuid();
Even the fast form takes ACCESS EXCLUSIVE for a moment, so it still needs
the lock_timeout from recipe 1. For the volatile case, add the column with no
default, then fill it in small batches.
3. Create indexes with CONCURRENTLY
A plain CREATE INDEX takes SHARE, which blocks all writes for as long as
the build lasts. CONCURRENTLY avoids that:
CREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id);
It has a price and some limits, all from the docs:
- It scans the table twice and waits for every existing transaction that could use the index. It takes longer and does more work than a plain build.
- It cannot run inside a transaction block. Some migration tools wrap each file in a transaction, so turn that off for this file.
- Only one concurrent build can run on a table at a time.
- It is not supported on a partitioned table. Build it on each partition, then create the index on the parent. That last step only changes metadata.
- If it fails (a deadlock, or a duplicate in a unique index), it leaves an
INVALIDindex behind. Queries ignore it, but writes still pay to keep it up to date. Drop it and try again.
Find leftovers:
SELECT indexrelid::regclass AS index_name FROM pg_index WHERE NOT indisvalid;
I tested this with a unique index on a column that had duplicates. The build
failed with could not create unique index ... is duplicated, and the index
showed up in that query with indisvalid = false.
4. Add constraints with NOT VALID
A plain ADD CONSTRAINT ... CHECK scans the whole table while it holds
ACCESS EXCLUSIVE. Split it in two:
-- Instant. New and changed rows are checked from now on.
ALTER TABLE orders ADD CONSTRAINT status_not_empty
CHECK (status <> '') NOT VALID;
-- Scans old rows. Takes SHARE UPDATE EXCLUSIVE, so reads and writes continue.
ALTER TABLE orders VALIDATE CONSTRAINT status_not_empty;
This works for foreign keys too. ADD FOREIGN KEY ... NOT VALID skips the
scan, and VALIDATE CONSTRAINT does it later with weaker locks (plus a
ROW SHARE lock on the referenced table).
There is a related trick for SET NOT NULL. The docs say the table scan is
skipped when a valid CHECK constraint already proves no NULL exists. So add
CHECK (col IS NOT NULL) NOT VALID, validate it, then run
SET NOT NULL. That last step still takes ACCESS EXCLUSIVE, but now it is
quick.
5. Do not change a column type in place
ALTER COLUMN ... TYPE normally rewrites the whole table and its indexes while
it holds ACCESS EXCLUSIVE. A few binary-compatible changes skip the rewrite,
but you should check the docs for the exact pair of types first. For anything
else, add a new column, copy the data in batches, and switch the code over.
Advisory locks
Advisory locks are locks that PostgreSQL does not use itself. You pick a number, and your code decides what it means. Typical use: make sure only one copy of a cron job runs.
-- Returns true if you got the lock, false at once if someone else has it.
SELECT pg_try_advisory_lock(42);
Two kinds exist:
- Session level (
pg_advisory_lock). Held until you release it by hand (each lock function has a matching release function) or the session ends. It ignores transactions. A lock taken inside a transaction that rolls back is still held. - Transaction level (
pg_advisory_xact_lock). Released when the transaction ends. There is no manual release.
Prefer the transaction-level kind. It cannot outlive the transaction by
mistake. They show up in pg_locks with locktype = 'advisory', so the blocker
query above sees them. They share the same shared memory as normal locks, so do
not take hundreds of thousands of them.
A plain SELECT that was not blocked by anything starts waiting, because it
lined up behind the ALTER, and the ALTER is lined up behind one open
report. The migration itself took a few milliseconds.
Questions people ask
Does a SELECT block an ALTER TABLE?
Yes. A SELECT holds ACCESS SHARE until its transaction ends, and
ALTER TABLE usually needs ACCESS EXCLUSIVE, which conflicts with it. A slow
report or an idle in transaction session that once ran a SELECT is enough.
Use lock_timeout so the ALTER gives up instead of making a queue.
How do I see which locks are held in PostgreSQL?
Query pg_locks. One row is one lock that is held (granted = true) or
waited for (granted = false). Join it to pg_stat_activity on pid to see
the query. To find who is blocking whom, use pg_blocking_pids() as shown
above, because joining pg_locks to itself is easy to get wrong.
How do I kill a blocking query?
Find the root blocker, then run SELECT pg_cancel_backend(pid) to cancel its
current query. If it is idle in transaction, there is no query to cancel, so
use SELECT pg_terminate_backend(pid), which ends the session and rolls back
its transaction.
Does PostgreSQL turn row locks into a table lock? No. The docs say there is no limit on the number of rows locked at one time, and there is no escalation. SQLite is different, because it locks the whole database. See how SQLite locks work.
Cheat sheet
Further reading
- PostgreSQL docs: explicit locking
- PostgreSQL docs: the pg_locks view
- PostgreSQL docs: pg_blocking_pids and other session information functions
- PostgreSQL docs: client connection defaults (lock_timeout, statement_timeout, idle_in_transaction_session_timeout)
- PostgreSQL docs: CREATE INDEX, building indexes concurrently
- PostgreSQL docs: ALTER TABLE
- Postgres as a job queue with SKIP LOCKED on this site
- The transactional outbox pattern on this site
- Idempotency keys explained on this site
- How SQLite locks work on this site
- A double-entry ledger in Postgres on this site, which locks account rows in id order to avoid deadlocks