skip to content

During a PostgreSQL checkout outage, dozens of sessions wait with wait_event_type 'Lock'; how do you use pg_blocking_pids() to find and clear the root blocker?

level: seniorimportance: should knowfreq 60%

answer

  1. waiters point at their blockers
  2. hard block and soft block
  3. blocks others, not blocked itself
  4. idle in transaction at the root
  5. a zero means prepared transaction

basics

~10 s

Call pg_blocking_pids(pid) for each waiting session, then find the PIDs that block others but are not blocked themselves. In a checkout pile-up that root is often an idle-in-transaction session, ended with pg_terminate_backend().

solid answer

~40 s

`pg_blocking_pids(pid)` returns the PIDs blocking a session's heavyweight-lock request: *hard* blockers holding a conflicting lock and *soft* blockers queued ahead with a conflicting request. Waiters form a tree, so I list sessions where `cardinality(pg_blocking_pids(pid)) > 0`, collect the PIDs they name, and keep those with no blockers of their own: the roots. In a checkout outage the root is typically `idle in transaction` with an old `xact_start`, an app that updated a stock row and then stalled outside the database. A cancel is ignored by an idle backend, so I record its `usename`, `application_name`, `client_addr` and last `query`, then call `pg_terminate_backend(pid)`; the rollback releases its locks and the queue drains. A `0` in the array is a prepared transaction, cleared only with `ROLLBACK PREPARED` or `COMMIT PREPARED`.

code

sql · 14 lines
sql
WITH waiting AS (
  SELECT pid, pg_blocking_pids(pid) AS blockers
  FROM pg_stat_activity
  WHERE wait_event_type = 'Lock'
)
SELECT a.pid, a.state, a.usename, a.application_name, a.client_addr,
       now() - a.xact_start AS xact_age,
       (SELECT count(*) FROM waiting w
         WHERE a.pid = ANY (w.blockers)) AS directly_blocks,
       left(a.query, 60) AS last_query
FROM pg_stat_activity a
WHERE a.pid IN (SELECT unnest(blockers) FROM waiting)
  AND cardinality(pg_blocking_pids(a.pid)) = 0
ORDER BY directly_blocks DESC;

go deeper

for a junior

Recall that pg_blocking_pids(pid) names who blocks a session, and that a lock pile-up has one or a few root sessions behind all the waiters.

for a middle

Explain hard versus soft blocking, why the root is a blocker that is not itself blocked, and why an idle-in-transaction root needs termination rather than cancel.

for a senior

Walk through the incident: rank roots, capture evidence before terminating, handle pid 0 from prepared transactions, then fix the application path and add a timeout and alerting.

for a principal

Discuss making such outages unlikely by design: short transactions around external calls, per-role timeouts, and alerting on transaction age rather than on waiter counts.

## The symptom At a fashion retailer, checkout requests start timing out at the peak of a sale. `pg_stat_activity` shows dozens of client backends in state `active` with `wait_event_type = 'Lock'` and wait events such as `transactionid`, `tuple` or `relation`. A heavyweight-lock pile-up like this has a shape: one or a few sessions at the root and a growing tree of waiters behind them. Ending waiters achieves little; the job is to find the root. ## What pg_blocking_pids() returns `pg_blocking_pids(pid)` returns an `integer[]` of the process IDs blocking that backend from acquiring a lock, or an empty array if it is not blocked. Its rules: - **Hard blockers** hold a lock that conflicts with the request. - **Soft blockers** do not hold a conflicting lock, but are **ahead in the wait queue** with a conflicting request. An `ALTER TABLE` waiting behind an old transaction therefore blocks later readers of that table, and those readers list the `ALTER TABLE`'s pid, not the old transaction's (the lock-queue mechanics belong to the schema-changes topic). - With **parallel query**, the result lists the client-visible leader pid even when a worker holds or awaits the lock, so the same pid can appear twice. - A **0** means a **prepared transaction** holds a conflicting lock: there is no backend to signal. - It covers heavyweight locks only. Sessions waiting on `LWLock`, `IO` or `IPC` events get an empty array. - It is not free: each call briefly needs **exclusive access to the lock manager's shared state**, so call it for waiting sessions during an incident, not for every session every second. ## Finding the root 1. List the waiters: client backends with `wait_event_type = 'Lock'`, each with its `pg_blocking_pids(pid)`. 2. Collect every pid that appears in those arrays. 3. Keep the ones whose own `pg_blocking_pids()` is empty: they block others and are not blocked themselves. Those are the roots. 4. Rank the roots by how many sessions they block, and read their `state`, `xact_start`, `state_change`, `usename`, `application_name`, `client_addr` and last `query`. In the checkout outage the root is typically a backend in `idle in transaction` whose `xact_start` is minutes old: the application opened a transaction, decremented stock for a SKU on sale, then stalled on something outside the database, such as a payment call, without committing. Every other order for that SKU queues behind its row lock. Its `query` column shows only its **last** statement, which may not be the one that took the lock. ## Clearing it | What sits at the root | What to do | |---|---| | An `idle in transaction` backend | `pg_terminate_backend(pid)`; an idle backend ignores a cancel | | An `active` backend running a long statement | `pg_cancel_backend(pid)` first, terminate if it does not stop | | pid `0`, a prepared transaction | Find it in `pg_prepared_xacts` (`gid`, `prepared`, `owner`), then `COMMIT PREPARED` or `ROLLBACK PREPARED` once you know which outcome its coordinator intended | | A soft blocker, such as DDL waiting in the queue | Cancelling it lets later sessions through, but the real root behind it is still there | When the root's transaction rolls back, its locks are released and the waiters proceed. Record what you saw (pid, application, client address, last query, transaction age) **before** terminating, because the row disappears with the session. ## After the outage - **Fix the application path** that left the transaction open: commit before calling external services, and make every error path roll back. - **Add a guard**: `idle_in_transaction_session_timeout` ends such sessions automatically; its tuning belongs to the connection-tuning topic. - **Make the next one visible**: turning on `log_lock_waits` writes a log line when a lock wait outlasts `deadlock_timeout` (the logging topic covers it), and lock modes are read from `pg_locks` (the locking topic). - **Alert on transaction age**: a check on `now() - xact_start` for client backends in `idle in transaction` catches the next stalled session before a queue builds.

  • Why can PostgreSQL's pg_blocking_pids() name a session that holds no conflicting lock on the table?
    Because it also reports soft blockers: sessions ahead in the wait queue whose own request conflicts. An `ALTER TABLE` waiting for its lock behind an idle transaction is listed as the blocker of every later reader. Cancelling the `ALTER TABLE` frees the readers, but the idle transaction behind it remains the root.
  • What does a 0 in the array returned by pg_blocking_pids() mean, and how do you clear it?
    A prepared transaction, left by `PREPARE TRANSACTION`, holds a conflicting lock. It has no backend, so neither signalling function helps. Find it in `pg_prepared_xacts` by `gid` and `prepared` time, establish what its coordinator intended, then run `COMMIT PREPARED` or `ROLLBACK PREPARED` with that `gid`.
  • Why not poll pg_blocking_pids() for every session every second from a dashboard?
    Each call briefly needs exclusive access to the lock manager's shared state, so frequent calls across all sessions add contention on a busy server. Call it only for sessions already waiting with `wait_event_type = 'Lock'`, at a modest interval, and use the server log's lock-wait messages for the history.

  • Kill whichever session has the most waiters behind it; that is always the root.
  • pg_blocking_pids only returns sessions that hold a conflicting lock.
  • pg_cancel_backend on the idle in transaction blocker will release its locks.
  • The blocker's query column shows the statement that took the blocking lock.
  • Restarting PostgreSQL is the quickest safe way out of a lock pile-up.