Skip to content

Sessions waiting on a lock

Who is waiting, on whom, and for how long. An empty result is the healthy one.

PostgreSQL · SQL
SELECT w.pid AS waiting_pid,       w.usename AS waiting_user,       EXTRACT(EPOCH FROM (now() - w.query_start))::int AS waiting_seconds,       LEFT(w.query, 120) AS waiting_query,       b.pid AS blocking_pid,       b.usename AS blocking_user,       b.state AS blocking_state,       LEFT(b.query, 120) AS blocking_queryFROM pg_stat_activity wJOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS bp(pid) ON trueJOIN pg_stat_activity b ON b.pid = bp.pidWHERE w.wait_event_type = 'Lock'ORDER BY w.query_start

This query is part of the "PostgreSQL health" pack: connect the database in DataRunner and install the whole pack at once, with queries and dashboard.

What this query shows

When one session holds a lock that another needs, the second waits. Most waits last milliseconds. When one lasts minutes, everything queued behind it stacks up, and the application looks frozen while the database CPU sits idle.

The query reads pg_stat_activity for sessions with wait_event_type = 'Lock' and uses pg_blocking_pids to find the sessions that hold them back. Each row is one waiting and blocking pair. Run it during an incident, or on a schedule to catch short blocks you would never see live.

How to read each column

  • waiting_pid, waiting_user, waiting_query: the session that is stuck and the first 120 characters of its statement.
  • waiting_seconds: time since the waiting statement started, from query_start.
  • blocking_pid, blocking_user: the session holding the lock.
  • blocking_state: the state of the blocker. idle in transaction is the classic culprit, a session that took a lock, stopped, and never committed.
  • blocking_query: the blocker's current or last statement. For an idle blocker it is the last statement it ran, which may not be the one that took the lock.

Healthy and worrying numbers

An empty result is the healthy one. A single row for a few seconds during a migration is normal. Worry when waiting_seconds grows across runs, when the same blocking_pid appears in many rows, or when the blocker is idle in transaction.

One blocker with many waiters usually means one bad session. A chain, where the blocker itself waits on someone else, means you have to follow blocking_pid up until you reach a session that is not waiting.

What to do about it

Look at the blocker first. If it is running a legitimate long statement, wait or schedule that work off peak. If it is idle in transaction, the application forgot to commit. End it to release the lock.

SELECT pg_terminate_backend(12345);  -- the blocking_pid

To protect the application, give statements a limit on how long they wait for a lock, and ask the server to log slow waits.

ALTER ROLE app_user SET lock_timeout = '5s';ALTER SYSTEM SET log_lock_waits = on;SELECT pg_reload_conf();

log_lock_waits writes a line to the server log when a session waits longer than deadlock_timeout (1 second by default). For schema changes, set lock_timeout in the migration session so it gives up instead of queueing everyone behind it.

Limits of this query

  • It catches waits on heavyweight locks only, those shown as wait_event_type = 'Lock'. Short internal waits (LWLock, IO) do not appear.
  • It is a snapshot. A lock that cleared a second ago leaves no trace, which is why scheduling it helps.
  • Queries of other users are hidden unless your role is a superuser or in pg_read_all_stats.
  • Deadlocks are resolved by the server itself, which aborts one session after deadlock_timeout. They show up in the log, not here.

Run it on a schedule in DataRunner

Connect the database to DataRunner, paste this query or start from the template, approve the SQL, then pick a schedule and a channel. Every 5 to 15 minutes catches blocks that last long enough to matter. Each run executes the query on your database and delivers the result as CSV, Excel, PDF or inline HTML by e-mail, Slack, Telegram, Discord, WhatsApp (beta), a signed webhook or Google Sheets.

This query returns no rows when everything is fine. A run with no rows can be skipped, so a message only arrives when there is something to look at.

If the database sits in a private network, the bridge agent opens the connection from the inside out, so you do not need to open an inbound port.

Frequently asked questions

How do I find blocking queries in PostgreSQL?
Use pg_blocking_pids(pid) on each session that is waiting for a lock and join the result back to pg_stat_activity, as this template does. The output pairs every waiting session with the one blocking it, with both statements. This works from PostgreSQL 9.6.
How do I release a lock in PostgreSQL?
Locks are released when the transaction that holds them ends. To force that, call pg_terminate_backend with the blocking pid, which rolls the transaction back. Try pg_cancel_backend first when the blocker is running a statement you only want to stop.
What is the difference between a lock wait and a deadlock?
In a lock wait one session waits for another that will eventually finish. In a deadlock two or more sessions wait for each other and never will. PostgreSQL detects deadlocks after deadlock_timeout and aborts one of the sessions with an error.
What does wait_event_type Lock mean?
It means the session is waiting for a heavyweight lock, such as a row lock or a table lock held by another transaction. The wait_event column then names the lock type, for example relation or transactionid.