Video in progress
Even on a small table `SELECT count(*)` is slow, and `pg_stat_activity` shows the query waiting on a "Lock". How do you find out who is blocking whom?
The pg_blocking_pids(pid) function returns the processes blocking a waiting session. By joining pg_locks and pg_stat_activity, I find the session at the head of the chain, its query, and its transaction age. Often a DDL statement or a forgotten transaction sits at the head of the chain.
📖 Answer
A SELECT normally waits for nobody, thanks to MVCC. If it is waiting on a lock, it means someone asked for ACCESS EXCLUSIVE on the table (a migration, for example), and that request is itself waiting for somebody else. A chain has formed.
Quick diagnostics:
SELECT a.pid,
pg_blocking_pids(a.pid) AS blocked_by,
a.state,
a.wait_event_type,
now() - a.xact_start AS tx_age,
left(a.query, 80) AS query
FROM pg_stat_activity a
WHERE a.pid IN (
SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity
) OR cardinality(pg_blocking_pids(a.pid)) > 0
ORDER BY a.xact_start;
In the result, the session whose blocked_by is empty but which blocks others is the root of the chain. Usually that is:
- an application connection in the
idle in transactionstate; - a long report query, with an
ALTER TABLEbehind it, and everyone behind that; - a transaction someone started with
BEGINin a hand-opened psql session and forgot.
The decision: if the root query isn't important, pg_cancel_backend(pid) (cancels only the query), and if that doesn't help, pg_terminate_backend(pid) (drops the connection). If it's a DDL, it's usually better to stop the DDL and then restart it with lock_timeout.
For the future: set log_lock_waits = on. Then every case that waits longer than deadlock_timeout is written to the log, and you can analyze it after the incident.
Sign up to mark studied questions and save your progress.