How-To Guide

How to Diagnose PostgreSQL Lock Contention

Find the query that is blocking others, understand which lock mode is held and why, and resolve contention without restarting the database.

On this page

  1. Introduction
  2. How PostgreSQL Locks Work
  3. Finding Blocked and Blocking Sessions
  4. Interpreting Lock Modes and Wait Events
  5. Breaking Contention Safely
  6. Designing Around Contention
  7. Prevention and Monitoring
  8. Conclusion

Introduction

When a query that normally takes milliseconds suddenly hangs, the cause is often not the query itself but a lock held by another session. PostgreSQL uses row-level and table-level locks to keep concurrent work consistent, and it will happily let one session wait for minutes while another holds a conflicting lock. The symptom is a growing queue of blocked sessions, a spike in latency, and eventually connection-pool exhaustion. Diagnosing contention means answering three questions: who is blocked, who is blocking them, and in what mode. This article shows the queries that answer those questions and the design changes that keep contention rare.

How PostgreSQL Locks Work

PostgreSQL takes locks at several levels of granularity. Row-level locks are implicit: an UPDATE or DELETE locks the rows it touches, and a SELECT … FOR UPDATE locks rows for later modification. Table-level locks come from DDL, from explicit LOCK statements, and from statement-level locks that every operation takes for the duration of the statement. Lock modes form a conflict matrix: ACCESS EXCLUSIVE conflicts with everything, while ACCESS SHARE conflicts only with ACCESS EXCLUSIVE. A reader and a writer on different rows do not conflict because they hold row locks on distinct rows, but two writers on the same row do.

Two sessions can also deadlock: each holds a row the other needs. PostgreSQL detects a deadlock cycle after deadlock_timeout and aborts one of the transactions with a deadlock error. That error is a signal to retry, not a bug, though frequent deadlocks point to a design that acquires locks in inconsistent order.

Finding Blocked and Blocking Sessions

The most useful view is pg_stat_activity joined to pg_locks. pg_stat_activity tells you which sessions are running, waiting or idle in transaction; pg_locks tells you which locks are held and which are awaited. Join them on the process id, and pair a waiting lock’s pid with the pid that granted it through the pg_blocking_pids function, which resolves the blocking chain for you.

-- Who is blocked, by whom, for how long
SELECT blocked.pid             AS blocked_pid,
       blocked.query           AS blocked_query,
       blocked.wait_event_type,
       pg_blocking_pids(blocked.pid) AS blocking_pids,
       blocker.pid             AS blocker_pid,
       blocker.state           AS blocker_state,
       now() - blocker.xact_start AS blocker_xact_age,
       blocker.query           AS blocker_query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocker
  ON blocker.pid = ANY (pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0
ORDER BY blocker.xact_start;

Interpreting Lock Modes and Wait Events

Once you know the blocking pid, look at the lock mode it holds and what the blocked session is waiting for. An ACCESS EXCLUSIVE lock from an ALTER TABLE that is itself waiting for a long query is a common cascade: the DDL holds the top lock, everything behind it queues, and new readers queue too. The wait_event_type of Lock confirms the wait is on a lock rather than on I/O or a client.

-- Locks held or awaited by a specific pid, with the relation name
SELECT l.pid, l.locktype, l.mode, l.granted,
       c.relname AS relation
FROM pg_locks l
LEFT JOIN pg_class c ON c.oid = l.relation
WHERE l.pid = $1
ORDER BY l.granted, l.mode;

-- All ungranted locks: the queue of waiters
SELECT pid, mode, relation::regclass AS relation, granted
FROM pg_locks
WHERE NOT granted;

Breaking Contention Safely

The instinct to terminate the blocker is sometimes correct and sometimes harmful. If the blocker is an idle-in-transaction session that will never commit, terminating it is safe and frees the queue. If the blocker is an important write in progress, killing it rolls back real work and may leave inconsistent application state. Check the blocker’s state and transaction age first: an idle-in-transaction session older than your idle_in_transaction_session_timeout is a bug, not legitimate work.

Use pg_cancel_backend to cancel a query while leaving the session alive, and pg_terminate_backend only when cancellation does not help or the session is abandoned. Set statement_timeout and lock_timeout so a query cannot wait forever; lock_timeout aborts a statement that waits too long for a lock, which turns an unbounded hang into a fast, retryable error.

Designing Around Contention

Most lock contention is a design smell. Long transactions hold row locks for their whole duration, so keeping transactions short and doing slow work outside them removes most conflicts. Always acquire locks in a consistent order, for example always update the lower account id first in a transfer, so two sessions cannot deadlock. Avoid SELECT … FOR UPDATE over broad ranges when a narrower predicate would do, and remember that adding an index so a query locks only the needed rows reduces how many rows it must touch.

DDL deserves special care. An ALTER TABLE that needs ACCESS EXCLUSIVE will block behind every query currently holding ACCESS SHARE, and new queries will block behind the DDL, creating a queue that looks like a freeze. Set lock_timeout before running DDL so it fails fast rather than building a queue, and run it in a maintenance window or split it into steps. Many changes can be done online with the appropriate statement variant.

Prevention and Monitoring

Make contention observable before it becomes an incident. Alert on the count of sessions waiting on locks and on the maximum transaction age, because both grow before users notice. Track deadlock counts from pg_stat_database: a nonzero steady rate means some code path acquires locks in a conflicting order. Set idle_in_transaction_session_timeout and lock_timeout globally to bound the damage a single careless session can do.

When a lock incident does occur, write a short record of the blocker’s query, the lock mode, and the duration, and turn it into a test or a design change. The same query and the same lock mode will recur unless you fix the pattern, so the incident is only useful if it changes something.

Conclusion

Lock contention is diagnosable in minutes with pg_stat_activity joined to pg_locks and pg_blocking_pids. Find the blocked session, identify the blocker and the lock mode it holds, decide whether the blocker is legitimate work or an abandoned transaction, and either cancel, terminate or wait. Then fix the cause: shorter transactions, consistent lock ordering, narrower locking predicates, and online DDL with a lock timeout. Watch the queue length and transaction age so the next contention event is caught before it exhausts the connection pool.

Sources: PostgreSQL: Explicit Locking, PostgreSQL: Monitoring locks, PostgreSQL: pg_stat_activity.

FAQ

Is it safe to terminate the blocking session?
Only after checking its state and transaction age. An idle-in-transaction session that will never commit is safe to terminate. A session performing an important write is not: killing it rolls back work and may leave application state inconsistent, so cancel the query first or let it finish.
How do I stop a query from waiting on a lock forever?
Set lock_timeout so a statement that cannot acquire a lock is aborted quickly, and statement_timeout as a broader bound. This converts an unbounded hang into a fast, retryable error and prevents a single blocked session from building a queue behind it.

Related Examples