Sub topic 3
Finding Blocked and Blocking Sessions
This chapter assumes you know basic SQL, transactions (BEGIN, COMMIT, ROLLBACK), and how to run two psql sessions at once. The earlier chapters covered row locks and deadlocks. Here you diagnose waits and limit how long they last.
Finding blocked and blocking sessions
Join pg_stat_activity with pg_blocking_pids() to list each waiting session and the sessions it waits on:
SELECT a.pid,
pg_blocking_pids(a.pid) AS blocked_by,
a.state,
a.wait_event_type,
a.wait_event,
left(a.query, 80) AS query
FROM pg_stat_activity AS a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;Timeouts for lock waits
Set timeouts so a session gives up instead of waiting forever:
SET lock_timeout = '2s';
SET statement_timeout = '30s';
SET idle_in_transaction_session_timeout = '60s';lock_timeoutcancels a statement that waits too long for a lock.statement_timeoutcancels any statement that runs too long.idle_in_transaction_session_timeoutends a session that stays open inside a transaction without doing work.
NOWAIT and SKIP LOCKED
FOR UPDATE NOWAIT raises an error at once if the row is locked. FOR UPDATE SKIP LOCKED skips locked rows, which suits a job queue where several workers each claim a different job:
BEGIN;
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
COMMIT;Running schema changes without blocking traffic
ALTER TABLE takes an ACCESS EXCLUSIVE lock. While it waits, every later query on that table queues behind it. A short lock timeout makes the change fail fast instead:
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;If the statement times out, retry it later.
Advisory locks
An advisory lock is a lock on a number your application chooses. It locks no table rows. This transaction-level lock releases at commit or rollback:
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_lock;
-- if got_lock is true, run the exclusive work
COMMIT;Exercise
Why set lock_timeout before running ALTER TABLE on a busy table?
Show answer
Without it, the ALTER waits indefinitely for its lock, and every later query on that table waits behind the ALTER.