Overview and Lock Mechanics
Among all production database performance issues, lock contention is the most insidious. When a system suffers from lock queueing, queries are not inherently slow, host CPU utilization remains remarkably low, and storage I/O is quiet. Yet from the perspective of users and backend services, the application is completely frozen. Queries are simply stalled in line, waiting for an earlier transaction to release its lock.
In this operational runbook, you will learn how to identify lock contention in under 60 seconds, isolate the exact blocking PID versus blocked PID chain in 5 minutes, safely terminate blocking sessions without corrupting data, and configure timeouts to permanently prevent cascading lock freezes.
Scenario
14:07 PM: The Low-CPU System Freeze. The backend engineering team escalates an urgent P1 incident:
The DBA queries pg_stat_activity and uncovers the ground truth: 40 client connections are listed as active, but all 40 have their wait state set to wait_event = 'Lock'.
None of the 40 queries are actually executing compute instructions; they are waiting for a single transaction to commit or rollback. That single root transaction has been open for 2 hours: it executed an UPDATE statement, held an exclusive row lock, and remained in an idle in transaction state because an interactive developer terminal went to lunch. One forgotten transaction paralyzed the entire transactional platform.
This runbook details the exact triage protocol for this scenario.
Lock Anatomy: Why Locks Exist
Locks are not bugs; they are the fundamental mechanism relational databases use to guarantee the "I" (Isolation) in ACID transactions. If two concurrent sessions attempt to update the same account balance simultaneously, one session must wait for the other to complete. Without locks, data corruption is guaranteed.
The operational problem is never the existence of a lock; it is the excessive duration a lock is held.
▸Key PostgreSQL Lock Levels:
- 1Row-Level Locks (`RowExclusiveLock`, `ExclusiveLock`): Acquired automatically by
UPDATE,DELETE, andSELECT FOR UPDATE. Blocks concurrent modifications to the same physical row, but permits concurrent readers. - 2Table-Level Locks (`AccessExclusiveLock`): Acquired by DDL statements such as
ALTER TABLE,DROP TABLE,TRUNCATE, andVACUUM FULL. Blocks all concurrent reads and writes to the target relation. - 3Advisory Locks: Application-managed locks acquired explicitly via SQL functions (
pg_advisory_lock). Useful for distributed scheduling, but dangerous if unreleased.
▸The 3 Structural Root Causes:
- 1Long-Running Open Transactions: A transaction that runs an update and then performs external network HTTP calls, sleeps, or waits for user confirmation holds all acquired locks open.
- 2Inconsistent Lock Ordering (Deadlocks): Transaction A locks Table 1 then requests Table 2, while Transaction B locks Table 2 then requests Table 1.
- 3Mass-Update Scope: An
UPDATEstatement that mutates 500,000 rows locks 500,000 rows simultaneously, creating massive concurrency bottlenecks.
Step 1: Rapid 60-Second System Triage
Is the database actually experiencing a lock bottleneck? Run this immediate aggregated inspection:
SELECT
state,
wait_event_type,
wait_event,
count(*) AS session_count
FROM pg_stat_activity
WHERE state <> 'idle'
GROUP BY 1, 2, 3
ORDER BY session_count DESC;▸Interpreting the Triage Matrix:
- •
wait_event_type = 'Lock'count is 0: No lock contention exists. Pivot investigation to CPU, memory, or network layers. - •
wait_event_type = 'Lock'count is 1–5 (transient): Normal OLTP behavior. Short row lock contentions resolve in milliseconds. - •
wait_event_type = 'Lock'count is > 10 and rising: A lock crisis is forming. Move immediately to Step 2. - •
wait_event_type = 'Lock'count is > 30: Active production outage. Connection pool exhaustion is imminent.
Next, inspect the volume and duration of `idle in transaction` sessions:
SELECT
state,
count(*) AS total_sessions,
max(now() - state_change) AS longest_idle_duration
FROM pg_stat_activity
GROUP BY state
ORDER BY total_sessions DESC;idle in transaction count is high and longest_idle_duration > 5 minutes, a client has executed queries within an open transaction block and abandoned the socket without calling COMMIT or ROLLBACK.Step 2: Identify the Blocking vs Blocked Chain
This is the primary diagnostic query of this runbook. It maps the relationship between the blocked query waiting for resources and the blocking query holding the lock:
SELECT
blocked.pid AS blocked_pid,
blocking.pid AS blocking_pid,
blocked.wait_event AS wait_reason,
round(EXTRACT(EPOCH FROM (now() - blocked.query_start))::numeric, 1) AS blocked_duration_sec,
round(EXTRACT(EPOCH FROM (now() - blocking.query_start))::numeric, 1) AS blocking_runtime_sec,
blocking.state AS blocking_state,
blocking.application_name AS blocking_client,
blocking.usename AS blocking_user,
left(blocked.query, 120) AS blocked_statement,
left(blocking.query, 120) AS blocking_statement
FROM pg_stat_activity blocked
JOIN pg_locks blocked_lock
ON blocked.pid = blocked_lock.pid
AND NOT blocked_lock.granted
JOIN pg_locks blocking_lock
ON blocking_lock.locktype = blocked_lock.locktype
AND blocking_lock.granted
AND blocking_lock.relation = blocked_lock.relation
JOIN pg_stat_activity blocking
ON blocking.pid = blocking_lock.pid
WHERE blocked.pid <> blocking.pid
ORDER BY blocked_duration_sec DESC;▸Reading the Output:
- •`blocking_pid`: The process ID causing the blockage. This is your target.
- •`blocking_state`: If this shows
idle in transaction, the query shown inblocking_statementwas the *last* statement executed, but the transaction remains uncommitted. - •`blocked_duration_sec`: How long incoming traffic has been queueing behind this blocker.
Step 3: Deep-Dive the Blocker
Before terminating a process, inspect what the blocking transaction is doing:
SELECT
pid,
usename,
client_addr,
application_name,
state,
now() - xact_start AS transaction_age,
now() - query_start AS query_age,
query
FROM pg_stat_activity
WHERE pid = <BLOCKING_PID>;Assessment Checklist:
- 1Is it an automated batch migration, a background vacuum, or an interactive developer session?
- 2How long has the transaction been active? If under 60 seconds, it may finish naturally. If open for 45 minutes with no CPU activity, it is a frozen or abandoned session.
Step 4: The Safe Termination Protocol
When terminating a blocking session in production, follow this phased escalation protocol:
▸Phase 1: Graceful Cancellation (pg_cancel_backend)
Sends a SIGINT signal to the backend process. It cancels the currently executing query but preserves the client connection:
SELECT pg_cancel_backend(<BLOCKING_PID>);- •Success: The active query rolls back, locks are released, and the connection remains alive.
- •Limitation: If the session is
idle in transaction, there is no active query to cancel!pg_cancel_backendwill have no effect on an idle transaction.
▸Phase 2: Forceful Termination (pg_terminate_backend)
Sends a SIGTERM signal to the backend process. It severs the client socket connection entirely and rolls back the transaction in PostgreSQL shared memory:
SELECT pg_terminate_backend(<BLOCKING_PID>);- •Locks held by the transaction are instantly released.
- •Blocked queries in the queue resume execution immediately.
- •The client receives an error: *"FATAL: terminating connection due to administrator command"*.
kill -9 from the operating system shell on a PostgreSQL backend process. Doing so crashes PostgreSQL shared memory, forcing the postmaster to shut down all active backends and enter crash recovery mode (WAL replay). Always use SQL-level pg_terminate_backend().Step 5: Post-Incident Verification
Immediately verify that the lock queue has drained:
SELECT count(*) FROM pg_locks WHERE NOT granted;A return value of 0 confirms all lock queues have cleared and transactions are processing normally.
Permanent Prevention: Guardrails and Timeouts
Eliminate manual intervention by configuring automated defensive timeouts in postgresql.conf:
▸1. idle_in_transaction_session_timeout
Automatically terminates any session that leaves a transaction open and idle for longer than the threshold:
ALTER SYSTEM SET idle_in_transaction_session_timeout = '60s';
SELECT pg_reload_conf();This single setting permanently prevents developers or broken application pools from locking tables while unattended.
▸2. lock_timeout
Aborts an incoming query if it cannot acquire its required lock within the configured timeframe, preventing cascading queue pile-ups:
ALTER SYSTEM SET lock_timeout = '10s';
SELECT pg_reload_conf();▸3. Preventing Deadlocks via Deterministic Ordering
A deadlock occurs when two transactions attempt to lock the same resources in opposite order:
- •Transaction 1: Locks Account A, requests Account B.
- •Transaction 2: Locks Account B, requests Account A.
The Fix: Enforce deterministic locking order in application code by sorting entity IDs before locking:
-- Always lock accounts in ascending ID order:
SELECT * FROM accounts WHERE id IN (101, 202) ORDER BY id FOR UPDATE;Because both transactions request ID 101 first and ID 202 second, deadlocks become mathematically impossible.
Operational Checklist
- Count of sessions waiting on
wait_event = 'Lock'verified - Count and longest duration of
idle in transactionsessions audited - Blocking PIDs and blocked PID dependency tree identified
- Lock mode and target relation verified
- Runtime, query text, and application origin of blocking PID confirmed
- Session observed if runtime < 2 minutes without premature termination
- Application engineering team notified if session duration is excessive
- Graceful cancellation via
pg_cancel_backendattempted first - Hard termination via
pg_terminate_backendapplied if session fails to yield - Lock clearance and throughput recovery verified
- Deadlock ordering analyzed if deadlocks occurred
lock_timeoutandstatement_timeoutparameters audited- Long-running transaction alerts configured in monitoring system
- Root cause resolved in application transaction scope
Related Guides in Series
- •Pillar: Performance & Query Optimization
- •Cluster: Finding Top 20 Expensive Queries with pg_stat_statements
- •Cluster: The N+1 Query Problem and Connection Pool Saturation
- •Cluster: Reading and Deconstructing EXPLAIN ANALYZE
- •Cluster: Vacuum, Analyze, and Autovacuum Tuning
- •Cluster: Memory Tuning: shared_buffers, work_mem, effective_cache_size