PostgreSQL Lock Waits: Find Blocking Sessions
Find blocking sessions in PostgreSQL with pg_blocking_pids, measure lock wait time, and reproduce a blocked update in a three-session SQL lab.
Use pg_stat_activity to find sessions waiting on locks, then call pg_blocking_pids to find their immediate blockers. Follow those edges to the head of the chain. Use pg_locks.waitstart to measure the current lock wait separately from the age of the query or transaction.
Find the session behind a slow query
An update that normally finishes in milliseconds is hanging. Its connection is active, but another transaction may own the row it needs. Searching for the longest running query can miss the session that matters: the blocker may have stopped issuing SQL while leaving its transaction open.
Open a separate monitoring connection to the same primary database. Run this query in autocommit so repeated checks do not reuse the same transaction’s activity snapshot. It starts with sessions waiting on PostgreSQL heavyweight locks, then uses pg_blocking_pids to identify each immediate blocker. A query marked active can still be waiting: state describes what the backend is doing overall, while the wait fields describe what it is waiting for right now.
Use a role with approved monitoring access. Ordinary roles may see sessions they do not own but have limited access to their details; pg_read_all_stats is one way to grant broader visibility. Treat captured SQL as sensitive because it can contain application values. The result is a sample: a wait that already ended will not appear, and sessions can change during the query.
SELECT w.pid AS waiting_pid,
w.application_name AS waiting_app,
w.wait_event,
clock_timestamp() - w.query_start AS query_age,
edge.blocker_pid,
b.application_name AS blocker_app,
b.state AS blocker_state,
clock_timestamp() - b.xact_start AS blocker_xact_age,
left(w.query, 160) AS waiting_sql,
left(b.query, 160) AS blocker_current_or_last_sql
FROM pg_stat_activity AS w
CROSS JOIN LATERAL (
SELECT DISTINCT pid AS blocker_pid
FROM unnest(pg_blocking_pids(w.pid)) AS x(pid)
) AS edge
LEFT JOIN pg_stat_activity AS b ON b.pid = edge.blocker_pid
WHERE w.datname = current_database()
AND w.wait_event_type = 'Lock'
AND w.pid <> pg_backend_pid()
ORDER BY query_age DESC, waiting_pid, edge.blocker_pid;Source: PostgreSQL monitoring: pg_stat_activity and wait events ↗
Read the rows as a blocking chain
Each row says waiting_pid is waiting behind blocker_pid. A blocker may hold a conflicting lock, or it may be ahead in the queue waiting for a conflicting lock of its own. If the output shows 8103 → 8102 and 8102 → 8101, inspect 8101 before intervening on 8102. The PIDs are illustrative. A session can have several immediate blockers, so follow each branch.
For example, a long transaction reads a table, a migration queues for an exclusive lock, and a later reader queues behind the migration. The two readers could coexist if the migration were not waiting. That distinction matters: if the migration can be retried safely, its owner may choose to cancel it and clear the queue without interrupting the original reader.
DISTINCT collapses duplicate blocker PIDs that can arise with parallel workers, and the LEFT JOIN keeps blockers without a corresponding activity row. A blocker PID of zero represents a prepared transaction, which has no backend to signal. Inspect pg_prepared_xacts and use the transaction coordinator’s recovery process. A positive PID without details may have disappeared during sampling; take a fresh sample.
Query age measures time since the waiting statement began. Blocker transaction age may include several completed statements. For a blocker that is idle in transaction, the SQL column shows its last statement, which may differ from the statement that acquired the lock. Use the application name and transaction age to identify an owner, then consult the application logs for the transaction boundary.
Source: PostgreSQL system information functions: pg_blocking_pids ↗
Measure how long the current lock request has waited
Look at the ungranted pg_locks row for the waiting session. Replace 8103 with a waiting PID from your report. The elapsed time is for the current lock request. A statement can wait for more than one lock during its lifetime, and waitstart can briefly be null at the beginning of a wait.
An update that needs a row another transaction changed often waits on transactionid. Row locks are normally recorded on disk, so pg_locks may show a wait on the holder’s transaction ID without naming the affected row or table. Use the SQL and application context to identify the operation. For a relation lock, resolve the relation OID in the correct database, because relation OIDs are database-local.
Use pg_locks for request details and pg_blocking_pids for blocker identity. A naive join of granted and ungranted rows can miss blockers ahead in the queue. If several sampled sessions share the same wait event, trace their edges before deciding whether they are part of the same incident.
SELECT pid, locktype, mode, database, relation, transactionid,
waitstart, clock_timestamp() - waitstart AS current_wait
FROM pg_locks
WHERE pid = 8103
AND NOT granted;Lab: hold a row lock open
Open three independent connections to the same disposable database. Use a fresh database where lock_wait_lab does not exist. In session A, execute the following statements one at a time with autocommit enabled so CREATE TABLE and INSERT finish before BEGIN. The update completes, but the open transaction retains its lock. Leave A connected without committing.
SET application_name = 'lock_lab_holder';
CREATE TABLE lock_wait_lab (id integer PRIMARY KEY, quantity integer NOT NULL);
INSERT INTO lock_wait_lab VALUES (1, 10);
BEGIN;
UPDATE lock_wait_lab SET quantity = quantity - 1 WHERE id = 1;Source: PostgreSQL explicit locking: row locks, table locks, and deadlocks ↗
Lab: observe the waiter and release the lock
Run the next block in session B. Its update waits for A to finish, with a 60-second limit on this lock attempt. While it waits, run the first diagnostic query in session C. Find lock_lab_waiter behind lock_lab_holder and confirm that the holder is idle in transaction. Substitute B’s PID in the second query to see the lock request and its wait start.
Run ROLLBACK in A. If B is still waiting, its update can proceed. Run ROLLBACK in B too; if B hit the timeout first, this clears its failed transaction. In C, rerun the diagnostic to verify the edge is gone. Both updates were rolled back, so quantity should still be 10. Use DROP TABLE lock_wait_lab in the disposable database to remove the lab table.
This is a one-way wait. It can clear when the holder ends its transaction. A deadlock is a cycle in which transactions cannot all make progress; PostgreSQL detects it and aborts a participant. The lab’s lock timeout can fire without any deadlock.
SET application_name = 'lock_lab_waiter';
BEGIN;
SET LOCAL lock_timeout = '60s';
UPDATE lock_wait_lab SET quantity = quantity + 2 WHERE id = 1;
-- The UPDATE waits. Run ROLLBACK separately after observing it.Resolve the incident at the transaction boundary
Capture the waiter, its immediate blockers, the affected application, and the transaction age at the head of the chain. Refresh that evidence before signaling a PID. If the owner can close the transaction, have them commit only if the work is complete and should persist; otherwise have them roll it back. Issuing ROLLBACK in the observer connection cannot end a different session’s transaction.
If the approved response is to cancel a query, pg_cancel_backend targets the current statement. It cannot end an idle transaction simply because that transaction holds locks. pg_terminate_backend ends the session, aborts its uncommitted work, and disconnects its client. Use it only when authorized and when you understand the effect on application retries or unfinished work. Recheck the chain and the application’s error rate after taking action.
Match a durable fix to the pattern you observed. If a transaction waits on an HTTP request before committing, reconsider the transaction boundary while preserving correctness. If a migration routinely queues behind long readers, give the migration a bounded wait and plan how to retry it. If concurrent writers lock the same rows in different orders, use a consistent order to reduce deadlock risk.
Source: PostgreSQL server signaling: query cancellation and session termination ↗
Set a bounded wait and know when to look elsewhere
lock_timeout applies separately to each lock acquisition attempt. statement_timeout bounds the statement more broadly and can fire first. Scope timeouts to the affected operation rather than setting one blanket limit for every workload. Handle the resulting error and end the failed transaction before reusing a pooled connection. If your application retries, make sure that repeating the operation is safe and that the retries have a limit.
An empty report means you did not see matching waits in this database at that moment. Compare a few samples with request timestamps and pool metrics. A request can queue before it ever gets a database connection, and an I/O wait or an internal LWLock needs a different investigation. Avoid polling pg_blocking_pids in a tight loop because it briefly needs exclusive access to shared lock-manager state.
A useful incident record names the blocked operation, identifies the owner of the transaction or queue entry, and shows whether the wait disappeared after the response. Save the transaction pattern and the smallest change that will prevent a repeat. If lock evidence does not line up with the slow requests, check the connection pool, I/O, or the query plan next.
Source: PostgreSQL client defaults: lock and statement timeouts ↗
Your next steps
- Trace waiter-to-blocker edges; a blocker may itself be waiting.
- Measure the current lock request separately from statement and transaction age.
- Confirm ownership and refresh the wait chain before canceling or ending a session.
Sources & official resources
Linked resources checked on 2026-11-08. Technical behavior and provider guidance can change; check the documentation for the version you use.
- PostgreSQL system information functions: pg_blocking_pids ↗
- PostgreSQL monitoring: pg_stat_activity and wait events ↗
- PostgreSQL pg_locks: lock requests and waitstart ↗
- PostgreSQL explicit locking: row locks, table locks, and deadlocks ↗
- PostgreSQL server signaling: query cancellation and session termination ↗
- PostgreSQL client defaults: lock and statement timeouts ↗
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →