Sub topic 9
Finding blocked and blocking sessions
This chapter assumes you can run two psql sessions side by side. It also assumes you know that row locks and table locks last until the end of a transaction, and that a waiting lock request can queue behind other requests. Here you learn how to see who is waiting, who is blocking them, and what to do about it.
What you are looking for
When an application "hangs", the cause is often one session waiting for a lock that another session holds. The waiting session is not busy. It is idle in the sense that it uses no CPU, but it still holds its connection and any locks it already got. Your job is to answer three questions:
- Which sessions are waiting?
- Which sessions are they waiting for?
- What is the blocking session doing, and is it safe to stop it?
PostgreSQL gives you three tools for this: the pg_stat_activity view, the pg_locks view, and the function pg_blocking_pids().
Setting up a blocked session
Use the accounts table from earlier chapters. Open two sessions. In session A, start a transaction and leave it open:
CREATE TABLE IF NOT EXISTS accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100)
ON CONFLICT DO NOTHING;
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- do not commit yetIn session B, run an update on the same row. It blocks:
-- Session B (blocks until session A commits or rolls back)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;Now open a third session, C, for diagnosis. Keep A and B as they are.
pg_stat_activity: what is each session doing?
pg_stat_activity has one row per server process. The columns that matter for lock problems are:
| Column | Meaning |
|---|---|
| `pid` | Process ID of the backend serving the session |
| `state` | `active`, `idle`, `idle in transaction`, and others |
| `wait_event_type` | Category of what the session waits for. `Lock` means a heavyweight lock |
| `wait_event` | The specific wait, such as `transactionid`, `tuple` or `relation` |
| `xact_start` | When the current transaction began |
| `query_start` | When the current or last query began |
| `query` | The current query, or the last one if the session is idle |
A session waiting on a lock shows wait_event_type = 'Lock'. The wait_event tells you which kind of lock:
transactionid: waiting for another transaction to finish, typical when two sessions update the same row.tuple: waiting for a lock on a specific row version, typical when several sessions queue for the same row.relation: waiting for a table-level lock, typical for DDL orLOCK TABLE.
pg_blocking_pids(): who is blocking whom?
You could join pg_locks to itself to find blockers, but pg_blocking_pids(pid) does that work for you. It returns an array of process IDs that the given session is waiting on. An empty array means the session is not blocked.
SELECT a.pid,
pg_blocking_pids(a.pid) AS blocked_by,
a.state,
a.wait_event_type,
a.wait_event,
left(a.query, 80) AS query
FROM pg_stat_activity AS a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;With A and B open, session C sees one row: the pid of B, blocked_by containing the pid of A, wait_event_type = Lock and wait_event = transactionid.
The array can have more than one pid. A session can wait on several holders, and it can also be blocked by a session that is itself only waiting ahead of it in the queue. This is why the array may include sessions that hold no conflicting lock yet. Recall from the lock queue chapter that PostgreSQL grants locks in queue order for conflicting requests.
Reading the blocker
Once you have a blocker's pid, look at it directly:
SELECT pid, state, xact_start, now() - xact_start AS xact_age,
wait_event_type, wait_event, left(query, 80) AS last_query
FROM pg_stat_activity
WHERE pid = 12345; -- replace with a pid from blocked_byPay attention to state:
idle in transactionmeans the client opened a transaction, ran something, and is not sending more commands. Thequerycolumn shows the last statement it ran. This is the most common cause of long blocks. The application forgot to commit, or it is waiting on something slow such as an HTTP call.activemeans the blocker is running a query right now. It may be slow, or it may itself be waiting on a third session.
If the blocker is itself waiting, follow the chain. Keep looking up the blocker's own pg_blocking_pids() result until you reach a session that is not blocked. That session is the root of the chain, and it is the one you need to act on.
Finding the root of a blocking chain
The following query lists blocked sessions together with their direct blockers. To find the root, look for pids that appear in blocked_by but are not themselves blocked.
WITH blocked AS (
SELECT pid, unnest(pg_blocking_pids(pid)) AS blocker
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
)
SELECT DISTINCT b.blocker AS root_pid,
a.state,
now() - a.xact_start AS xact_age,
left(a.query, 80) AS query
FROM blocked AS b
JOIN pg_stat_activity AS a ON a.pid = b.blocker
WHERE b.blocker NOT IN (SELECT pid FROM blocked);This returns only blockers that are not waiting themselves. In a pile-up of fifty stuck sessions, this often reduces the list to one or two sessions.
This diagram shows a common pattern. Session 300 holds a lock and has gone quiet. A DDL statement in session 200 queues behind it. Ordinary queries in session 100 then queue behind the DDL. Fixing the chain means dealing with session 300.
pg_locks: the raw lock table
pg_locks has one row per lock held or requested. Use it when you want to know exactly which object is locked and in what mode.
SELECT locktype, relation::regclass AS relation, mode, granted, pid
FROM pg_locks
WHERE NOT granted;Rows with granted = false are waiting requests. The useful columns are:
locktype:relation(a table or index),transactionid,tuple,advisory, and others.relation: the object ID of the table. Casting toregclassshows its name.mode: for exampleRowExclusiveLockorAccessExclusiveLock.granted:trueif held,falseif waiting.
A row-level wait does not show a table name in the way you might expect. When session B waits for a row updated by A, B's ungranted lock is of locktype = transactionid, because B is waiting for A's transaction to end. The row itself is not listed in pg_locks. Row locks are stored in the row's header on disk, not in shared memory. This is why pg_locks alone cannot tell you which row is contended, and why pg_blocking_pids() is easier for row-level problems.
To see everything held by a suspected blocker:
SELECT locktype, relation::regclass AS relation, mode, granted
FROM pg_locks
WHERE pid = 12345 -- replace with the blocker pid
ORDER BY granted DESC, locktype;Every session holds a virtualxid lock on its own virtual transaction ID. Ignore that row. A session that has written data also holds a transactionid lock on its own transaction ID. That is the lock other sessions wait on.
Common errors when diagnosing
- Looking only at
state = 'active'. The most harmful blockers are oftenidle in transaction, so filter on the wait columns instead. - Reading
queryof an idle session as current. For an idle or idle-in-transaction session,queryis the last statement, not what it is doing now. - Treating the first blocked session as the cause. Always follow the chain to the root.
- Expecting
pg_locksto name the row. It will not. Usepg_blocking_pids()and the blocker'squery. - Missing sessions because of permissions. Without superuser or the
pg_read_all_statsrole, you seequeryand other details only for your own sessions. Other users' rows show empty values. - Running a slow diagnostic query during an incident. Both views are cheap to read, but
pg_lockstakes internal locks briefly. Query it once and keep the result, rather than polling in a tight loop.
Acting on what you found
Choose the least disruptive step that works:
- Wait or contact the owner. If the blocker is a legitimate long job, it may finish soon.
- Cancel the current query with
pg_cancel_backend(pid). This sends a cancel signal. The query stops, but the session and its transaction stay open. If the blocker isidle in transaction, there is no running query, so cancelling does nothing useful. - Terminate the session with
pg_terminate_backend(pid). This closes the connection and rolls back its transaction, which releases its locks.
SELECT pg_cancel_backend(12345); -- stop the running query only
SELECT pg_terminate_backend(12345); -- end the session and roll backTerminating loses uncommitted work and the client will see a dropped connection, so confirm what the session is doing first. Then fix the cause in the application: shorter transactions, no waiting on external calls inside a transaction, and timeouts such as idle_in_transaction_session_timeout, covered in the next chapter.
For a real-time view while the problem is happening, set log_lock_waits = on. PostgreSQL then writes a log line whenever a session waits longer than deadlock_timeout, naming the waiter, the blockers and the statement. This helps with problems you missed live.
Clean up the experiment
In session A, run ROLLBACK;. Session B's update then completes. Roll back or commit B as well, so the table is not left locked.
Exercise
Session C runs the blocked-sessions query and shows pid 410 blocked by pid 388. Pid 388 has state "idle in transaction" and a query column showing "UPDATE accounts SET balance = balance - 10 WHERE id = 1". Pid 388 is not in the blocked list. Which pid is the root of the chain, why does calling pgcancelbackend(388) not help, and what should you call to release the lock?
Show answer
Pid 388 is the root because it appears as a blocker and is not blocked itself. It is idle in transaction, so it has no running query, and the query column only shows its last statement. pgcancelbackend has nothing to cancel. Call pgterminatebackend(388), which closes the session and rolls back its transaction, releasing the row lock. Check first that losing its uncommitted work is acceptable.
Exercise
Why does pg_locks not show which row session B is waiting for when it updates a row that session A has already updated?
Show answer
Row locks are recorded in the row's header on disk, not in the shared lock table. Session B waits for session A's transaction to end, so pglocks shows an ungranted lock of locktype transactionid for A's transaction ID. Use pgblocking_pids() to find the blocker, then look at the blocker's query to infer the row.