PostgreSQL lock waits

PostgreSQL Lock Waits: Find Blockers and Fix Deadlocks

To diagnose PostgreSQL lock waits, find waiting sessions in pg_stat_activity, identify their blockers with pg_blocking_pids(), then inspect lock details in pg_locks. The safest fix depends on the blocking transaction, which might belong to an idle connection rather than a running query.

For SaaS teams, one abandoned transaction can delay requests across multiple tenants. Start by tracing the blocking relationship before canceling queries or changing database settings.

Key takeaways

  • Follow blocker relationships before acting; the slow request may only be a victim.
  • Use transaction age, session state, and application identity to understand each blocker.
  • Keep transactions short, bound lock acquisition, and retry deadlock victims as complete transactions.

Why SaaS queries wait on locks

PostgreSQL uses locks to coordinate concurrent operations. Two transactions updating the same row can conflict, while schema changes may require locks that conflict with ordinary reads.

Under PostgreSQL’s multiversion concurrency control, a normal SELECT generally doesn’t wait for another transaction’s row updates. However, it can wait behind a conflicting table lock.

A waiting migration adds another complication. A long transaction can prevent DDL from acquiring its lock. Later queries can then queue behind that DDL, even though the migration hasn’t started changing anything.

A deadlock is different: transactions form a cycle in which each waits for another. PostgreSQL detects that cycle and aborts one participant. An ordinary lock wait can continue until the blocker finishes or a timeout interrupts it.

Find blocked queries and their blocking sessions

Run diagnostics against the affected database using a restricted monitoring identity. The PostgreSQL lock-monitoring examples provide additional patterns for live investigations.

Map each waiter to its blockers

This query returns one row per waiting-session and blocker pair:

SELECT
    w.pid AS waiting_pid,
    w.application_name AS waiting_app,
    w.wait_event,
    clock_timestamp() - w.query_start AS query_age,
    w.query AS waiting_query,
    p.blocker_pid,
    b.application_name AS blocking_app,
    b.state AS blocking_state,
    clock_timestamp() - b.xact_start AS blocking_xact_age,
    b.query AS blocker_last_query
FROM pg_stat_activity AS w
CROSS JOIN LATERAL
    unnest(pg_blocking_pids(w.pid)) AS p(blocker_pid)
LEFT JOIN pg_stat_activity AS b
    ON b.pid = p.blocker_pid
WHERE w.datname = current_database()
  AND w.wait_event_type = 'Lock'
ORDER BY w.query_start;

pg_blocking_pids() includes both conflicting lock holders and sessions ahead in a lock queue. Therefore, a blocker might itself be waiting. Follow its PID until you reach the root blocker.

Trace the transaction behind the query

Read blocking_state alongside blocking_xact_age. An idle in transaction session has stopped executing but still has an open transaction.

For that session, blocker_last_query shows its most recent statement, not necessarily the statement that originally acquired the lock. Correlate application_name and PID with application logs.

Also distinguish query age from wait duration. query_age includes execution before the wait began.

Cross-user visibility requires suitable privileges, such as pg_read_all_stats. Restrict access because query text can expose tenant data. A blocker PID of 0 indicates a prepared transaction, which requires separate investigation rather than backend cancellation.

Inspect the requested locks with pg_locks

After identifying the involved PIDs, inspect their locks. Bind $1 to an integer array containing those observed PIDs:

SELECT
    pid,
    locktype,
    mode,
    granted,
    waitstart,
    relation::regclass AS relation,
    transactionid
FROM pg_locks
WHERE pid = ANY($1::int[])
ORDER BY granted, pid, locktype;

Run this in the affected database so relation identifiers resolve correctly.

granted = false identifies an unfulfilled lock request. waitstart records when that wait began, although it can briefly remain null. This column requires PostgreSQL 14 or later; omit it on older releases.

A row conflict often appears as a wait on a transaction ID. PostgreSQL doesn’t normally expose every held row lock as a separate pg_locks row.

The official pg_locks documentation recommends pg_blocking_pids() for identifying blockers. A hand-written self-join can miss queue ordering and mishandle parallel workers. Use the function for relationships and the view for lock details.

Capture deadlocks after they disappear

A live inspection often misses a deadlock because PostgreSQL has already aborted a participant. Capture SQLSTATE 40P01 in application error reporting, along with request ID, transaction operation, and backend PID when available.

The server’s deadlock report identifies participating processes and lock dependencies. Correlate those details with application logs to reconstruct statement order.

For ordinary waits, enable log_lock_waits through an authorized administrator. It logs waits that exceed deadlock_timeout.

deadlock_timeout controls when PostgreSQL checks for deadlocks. It doesn’t limit how long an ordinary lock wait can last.

Track the database counter as supporting evidence:

SELECT datname, deadlocks, stats_reset
FROM pg_stat_database
WHERE datname = current_database();

PostgreSQL’s activity and statistics documentation describes this counter. Measure changes over time and account for stats_reset; the total doesn’t identify affected queries.

After a deadlock, roll back and retry the whole transaction with bounded backoff and jitter. Repeating only the failed statement can break application assumptions.

Choose remediation without causing another incident

Capture the blocker relationship and transaction details before intervening. Live sessions can disappear between diagnosis and action, so re-read the selected PID’s identity immediately before signaling it.

Cancel running work selectively

When a dispensable running query is the root blocker, SELECT pg_cancel_backend($1); requests cancellation of its current statement. Bind $1 to the selected backend PID.

Canceling a blocked request may reduce application pressure, but it won’t remove the root cause. Prefer stopping an unnecessary maintenance operation when it owns the blocking transaction.

Coordinate with the owning application so it handles the error and rolls back before returning the connection to its pool. Monitoring permissions alone don’t grant permission to cancel another user’s backend.

End abandoned transactions deliberately

For an idle transaction, request an application-side ROLLBACK on its existing connection. Canceling an idle backend doesn’t close its transaction.

If the owner can’t recover an abandoned session, SELECT pg_terminate_backend($1); disconnects that backend and rolls back its uncommitted work. Use it only after identifying the workload and accepting the disruption.

Termination can break a customer request or migration. Afterward, rerun the blocker query and watch request failures before taking further action. A vanished PID alone doesn’t establish that the application recovered.

Set separate limits for waiting and execution

Timeouts protect different boundaries. lock_timeout limits each individual lock-acquisition wait. statement_timeout limits total statement duration, including time spent waiting.

Keep the lock limit below the statement limit when you want lock-specific failures. Otherwise, the statement timeout fires first.

This column-addition example uses a short-DDL budget:

BEGIN;
SET LOCAL lock_timeout = '1s';
SET LOCAL statement_timeout = '5s';


ALTER TABLE accounts ADD COLUMN plan_code text;


COMMIT;

These values illustrate a policy, not universal recommendations. SET LOCAL confines both settings to the transaction. If the alteration fails, issue ROLLBACK before retrying.

A short lock timeout prevents a waiting migration from remaining in the queue indefinitely. Inspect long transactions before deployment, then retry failed DDL with bounded backoff rather than an endless loop.

For abandoned connections, idle_in_transaction_session_timeout terminates sessions that remain idle inside a transaction too long. It doesn’t limit actively running statements.

With transaction pooling, use transaction-local settings where appropriate. Session settings may affect a different request or may not follow the client to its next backend.

Prevent recurring contention in SaaS workloads

Shorten transactions and standardize lock order

Keep external HTTP requests, file uploads, and user interaction outside database transactions. Open the transaction when database work is ready, then commit promptly.

When operations touch multiple rows or tables, acquire locks in a consistent order across API handlers and background workers. For account transfers, that can mean locking account IDs in ascending order.

Break large backfills into bounded batches using an indexed cursor. Commit each batch so locks don’t remain held for the entire job. Preserve tenant filters and row-level security context throughout; operational maintenance doesn’t justify weakening isolation.

Control shared bottlenecks and pooled connections

Avoid unnecessary concurrent updates to shared counters or tenant-wide summary rows. Although requests may affect different business records, a shared update can serialize their transactions.

Set distinct application_name values for API services, workers, and migrations so diagnostics identify the owning workload.

If requests stall before appearing in pg_stat_activity, inspect PgBouncer’s administrative views: SHOW POOLS, SHOW CLIENTS, and SHOW SERVERS. Waiting for a pooled connection is different from waiting for a PostgreSQL lock. Adding connections won’t remove a lock dependency.

Combine wait observations with request latency, CPU, and I/O. PostgreSQL’s database monitoring guidance explains why database views and system measurements belong together.

Frequently asked questions

Does an active session mean its query is executing?

No. A session can report state = 'active' while waiting. Use wait_event_type = 'Lock' to identify lock waits, then inspect wait_event and blocker relationships.

Will an index fix a lock wait?

An index can shorten work and reduce transaction duration, but it doesn’t release an existing conflicting lock. Diagnose the blocking transaction first.

Should every timeout trigger an automatic retry?

No. Retry only operations whose transaction and side-effect handling make repetition safe. Bound retries so an overloaded service doesn’t receive an escalating wave of repeated requests.

Fix the blocking transaction first

PostgreSQL lock waits become easier to resolve when you connect the waiting query to its blocker and owning application. Session state, transaction age, and lock details explain which intervention makes sense.

Start with the root blocker, then choose cancellation, rollback, or termination deliberately. Short transactions, consistent lock ordering, and scoped timeouts reduce the chance of the same incident returning.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *