A database can have spare CPU and healthy disk latency while an API becomes unusable. One transaction holds a lock, another waits for it, and a queue forms behind them. Adding application replicas may only add more waiters. The useful question is not which query is slow, but which transaction owns the resource that everyone else needs.

1. Separate lock waits from slow execution

Start with the active sessions and their wait events. PostgreSQL exposes the current wait category and event through pg_stat_activity. A Lock wait is different from an I/O wait or a client that is holding a transaction open while doing work elsewhere. Look at transaction age as well as query age: a statement that completed long ago may still hold locks until its transaction ends.

SELECT pid, application_name, state,
       wait_event_type, wait_event,
       now() - xact_start AS transaction_age,
       now() - query_start AS query_age
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid()
ORDER BY xact_start NULLS LAST;

Run diagnostics from a separate administrative connection with appropriate monitoring privileges. Avoid exporting raw query text into shared dashboards because it may contain sensitive values. Refresh the snapshot rather than keeping the diagnostic transaction open indefinitely.

2. Follow the blocking chain

Use pg_blocking_pids rather than trying to infer the complete blocking relationship from a join on pg_locks. It includes sessions ahead of a waiter in the lock queue as well as conflicting holders. The following query gives direct edges in the blocking graph.

SELECT w.pid AS waiting_pid,
       b.pid AS blocking_pid,
       b.state AS blocker_state,
       now() - b.xact_start AS blocker_age,
       b.application_name
FROM pg_stat_activity AS w
CROSS JOIN LATERAL
  unnest(pg_blocking_pids(w.pid)) AS p(pid)
LEFT JOIN pg_stat_activity AS b
  ON b.pid = p.pid
WHERE w.datname = current_database();

Follow edges until you find the root blocker. A prepared transaction can appear as PID zero; a missing activity row is not evidence that no blocker exists. Parallel workers and changing sessions can also complicate the snapshot. Use pg_locks to inspect the lock object and mode after identifying the relevant sessions. Do not run expensive diagnostic queries at high frequency during peak load.

Beware the migration queue. A long-running read can block a schema change requesting an exclusive table lock. New queries can then queue behind the schema change even though they would have been compatible with the original read. Canceling the waiting migration may restore traffic without terminating the original reader.

3. Set a budget for lock acquisition

A migration should fail quickly if it cannot acquire a disruptive lock. Set lock_timeout below statement_timeout so you can distinguish lock acquisition failures from longer execution. For a transactional DDL change, keep the settings local to the transaction.

BEGIN;
SET LOCAL lock_timeout = '750ms';
SET LOCAL statement_timeout = '5s';
ALTER TABLE orders ADD COLUMN source text;
COMMIT;

These are illustrative budgets, not universal defaults. On failure, roll back before returning the connection to the pool. The lock timeout applies separately to each acquisition attempt, while statement_timeout bounds a statement. Some operations, including CREATE INDEX CONCURRENTLY, cannot run inside a transaction block; use a dedicated connection and reset session settings afterward. Inspect failed concurrent indexes before retrying.

4. Shorten the transaction, not just the SQL

A common application mistake is to update a row and then call an external API before committing. The transaction holds locks across network latency, retries and outages. Move unrelated I/O outside the transaction and use an outbox or another durable workflow when a business effect must follow the commit.

const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query(
    "SET LOCAL lock_timeout = '500ms'"
  );
  await client.query(
    'UPDATE orders SET status = $1 WHERE id = $2',
    ['confirmed', orderId]
  );
  // Persist any required outbox event here.
  await client.query('COMMIT');
} catch (error) {
  await client.query('ROLLBACK').catch(() => {});
  throw error;
} finally {
  // Discard the client if rollback or protocol recovery failed.
  client.release();
}

The example illustrates transaction scope; in production, track rollback failure and pass an error to the pool release method to discard an unhealthy client. Keep transaction boundaries explicit and acquire locks in a consistent order when modifying multiple rows. That reduces deadlock risk but does not eliminate all contention.

5. Choose an incident response deliberately

Retry an entire aborted transaction only when its business effects are safe to repeat. Deadlock failures and lock timeouts require separate metrics and bounded retry policy. A retry storm against the same hot row can make the incident worse.

6. Reproduce the incident before production does

In a disposable database, open two sessions. In the first, begin a transaction and update one order without committing. In the second, set a short lock_timeout and update the same order. Observe the blocking edge from a third connection. Repeat with a long reader, a waiting ALTER TABLE, and a third reader to reproduce the migration queue. Roll back every test transaction when finished.

Monitor lock wait duration, oldest transaction age, idle-in-transaction sessions, deadlocks, and pool acquisition latency. Correlate these with deployment timestamps and endpoint latency. Keep PID and order identifiers in logs or traces rather than metric labels.

Production rule Treat transaction duration as a shared resource. A fast query inside a long transaction can be more disruptive than a slow query that holds no contested lock.

Official references

Related engineering notes