Queries in PostgreSQL are hanging. How do you find and resolve locks?

IntermediateTroubleshootingPostgreSQL
Answer

Short answer

Some session holds a lock that others are waiting for — often a long-running or idle-in-transaction session, or a schema change (ALTER TABLE) waiting behind a long query and blocking everyone after it. Find the blocking process with pg_stat_activity + pg_blocking_pids(), then end it if appropriate.

Find who blocks whom

SELECT a.pid, a.usename, a.state, now() - a.query_start AS running_for,
       pg_blocking_pids(a.pid) AS blocked_by, left(a.query, 80) AS query
FROM pg_stat_activity a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;

SELECT pid, state, now() - xact_start AS tx_age, left(query, 80)
FROM pg_stat_activity WHERE pid IN (<blocker pids>);

Resolve

SELECT pg_cancel_backend(<pid>);      -- cancel its current query (gentle)
SELECT pg_terminate_backend(<pid>);   -- end the session (if cancel isn't enough)

Prevent

  • idle_in_transaction_session_timeout = '60s'
  • lock_timeout = '5s' for migrations so an ALTER TABLE gives up instead of queueing everyone behind it.
  • statement_timeout per application role.
  • Run DDL in quiet periods; use CREATE INDEX CONCURRENTLY.

What to say in the interview

"I use pg_blocking_pids with pg_stat_activity to find the blocker — often an idle-in-transaction session or a migration's ALTER queued behind a long query — then cancel or terminate it. Prevention is lock_timeout for migrations, idle-in-transaction and statement timeouts, and CONCURRENTLY for index builds."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL