Find Blocking Queries in Postgres with pg_locks (Rails)
The pg_locks + pg_stat_activity query to find what's blocking a Rails query right now, how to read it, and how to cancel the offending backend safely.
Contents
- Why a query waits instead of failing
- The shortcut: pg_blocking_pids
- The full picture: pg_locks joined to pg_stat_activity
- Reading the output
- Tracing the blocker back to Rails code
- Breaking the standoff safely
- Bounding lock waits with timeouts
- How this connects to connection-pool exhaustion
- Common mistakes
- Key takeaways
- FAQ
- How do I find what is blocking a query in Postgres?
- What is the difference between pg_cancel_backend and pg_terminate_backend?
- What does granted = false mean in pg_locks?
- Why is my Rails query hanging with no error?
- Conclusion
A request is hung. The user is staring at a spinner, your APM shows a query that has been running for ninety seconds, and there is no error in the log, because nothing has failed. The query isn’t slow; it’s waiting, blocked on a lock another transaction is holding and won’t release. Unlike a deadlock, which Postgres detects and breaks within about a second, a plain lock wait has no referee. It blocks until the holder commits or rolls back, the holder is killed, or a timeout fires. Your job, mid-incident, is to find the holder.
This is the diagnostic playbook: the one-line shortcut, the pg_locks query that shows what is blocking what, how to read it, how to trace the blocker back to Rails code, and how to break a standoff safely. If the log says deadlock detected instead, that is a different problem: paste the report into the Postgres deadlock analyzer.
Why a query waits instead of failing
Postgres tracks heavyweight locks in a system view called pg_locks. When a transaction requests a lock that conflicts with one already held, Postgres does not error (unless you asked it to, with NOWAIT or lock_timeout). It adds a row to pg_locks with granted = false and puts the backend to sleep until the lock is free. That row can sit there indefinitely, which is why a lock wait presents as a hang, not a crash.
A deadlock is a cycle, two transactions each waiting on the other, which Postgres detects and resolves by killing one. A simple block is one-directional: A holds, B waits, and A is perfectly happy to keep holding. Nothing is wrong from Postgres’s point of view, so nothing gets killed. Fixing repeated cycles is the subject of fixing ActiveRecord::Deadlocked; this article is about the live question of who is holding the lock my request needs right now.
The shortcut: pg_blocking_pids
Postgres 9.6 and later ship a function that answers the question directly. Given a backend’s process id, pg_blocking_pids(pid) returns the array of process ids blocking it:
SELECT
pid,
pg_blocking_pids(pid) AS blocked_by,
state,
now() - query_start AS waiting_for,
query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
ORDER BY waiting_for DESC;
Any row returned is a backend that is currently waiting. blocked_by names the culprits, waiting_for is the age of the hung statement, and query is the statement itself, longest wait first. For most incidents this is all you need. Start here.
The function applies Postgres’s real conflict rules: it counts sessions holding a conflicting lock and sessions queued ahead of yours for one, and shows a prepared transaction as pid 0. One caution from the docs: frequent calls “could have some impact on database performance”, because each call needs exclusive access to the lock manager’s shared state for a short time. Run it by hand during an incident, not in a check that fires every few seconds.
The full picture: pg_locks joined to pg_stat_activity
When you need the blocking query text, not just its pid, to understand why the lock is held and whether it is safe to kill, join pg_locks to itself through pg_stat_activity:
SELECT
blocked.pid AS blocked_pid,
now() - blocked.waitstart AS blocked_for,
blocked_act.query AS blocked_query,
blocking.pid AS blocking_pid,
blocking_act.state AS blocking_state,
blocking_act.query AS blocking_query
FROM pg_locks blocked
JOIN pg_stat_activity blocked_act ON blocked.pid = blocked_act.pid
JOIN pg_locks blocking
ON blocking.locktype = blocked.locktype
AND blocking.database IS NOT DISTINCT FROM blocked.database
AND blocking.relation IS NOT DISTINCT FROM blocked.relation
AND blocking.page IS NOT DISTINCT FROM blocked.page
AND blocking.tuple IS NOT DISTINCT FROM blocked.tuple
AND blocking.virtualxid IS NOT DISTINCT FROM blocked.virtualxid
AND blocking.transactionid IS NOT DISTINCT FROM blocked.transactionid
AND blocking.classid IS NOT DISTINCT FROM blocked.classid
AND blocking.objid IS NOT DISTINCT FROM blocked.objid
AND blocking.objsubid IS NOT DISTINCT FROM blocked.objsubid
AND blocking.pid <> blocked.pid
AND blocking.granted
JOIN pg_stat_activity blocking_act ON blocking.pid = blocking_act.pid
WHERE NOT blocked.granted
ORDER BY blocked_for DESC NULLS LAST;
WHERE NOT blocked.granted selects only locks that are waiting. The self-join with blocking.granted finds a held lock on the same object, meaning all ten identifying columns match. The IS NOT DISTINCT FROM comparisons are deliberate: most of those columns are NULL for any given lock type, and plain = treats NULL = NULL as unknown, which would drop the very rows you want. Leave out virtualxid or the advisory-lock columns (classid, objid, objsubid) and those lock types over-match: every advisory lock in the database would appear to block every other one.
A blocked row UPDATE usually appears as a ShareLock request on the holder’s transactionid: a backend that must wait for another transaction to finish requests a share lock on that transaction’s ID. waitstart (Postgres 14+) is when the wait began; on older versions use now() - blocked_act.query_start. NULLS LAST matters because waitstart can be null for a moment after a wait starts.
The caveat: this join lists every granted lock on the same object, whether or not its mode conflicts with the request. A CREATE INDEX waiting for SHARE on a table is blocked by a writer’s ROW EXCLUSIVE, but the join also lists sessions holding ACCESS SHARE from a plain SELECT, which doesn’t conflict. It can’t see wait-queue order or parallel workers either. The Postgres docs call this kind of self-join “very difficult to get right in detail” and recommend pg_blocking_pids(). The Postgres lock mode lookup shows which modes actually conflict.
To get the query text with the authoritative blocker list, let pg_blocking_pids choose and use pg_stat_activity for context:
WITH waiting AS (
SELECT pid, query, query_start, pg_blocking_pids(pid) AS blocked_by
FROM pg_stat_activity
WHERE wait_event_type = 'Lock'
)
SELECT w.pid AS blocked_pid,
now() - w.query_start AS blocked_for,
b.pid AS blocking_pid,
b.application_name AS blocking_app,
b.state AS blocking_state,
now() - b.xact_start AS blocking_xact_age,
b.query AS blocking_query
FROM waiting w
JOIN pg_stat_activity b ON b.pid = ANY (w.blocked_by)
ORDER BY blocked_for DESC;
It calls pg_blocking_pids only for backends actually waiting on a lock, and blocking_xact_age shows how long the blocker’s transaction has been open.
Reading the output
blocked_pid | blocked_for | blocked_query | blocking_pid | blocking_state | blocking_query
-------------+-------------+------------------------------------+--------------+---------------------+------------------------------
18344 | 00:01:32 | UPDATE orders SET ... WHERE id = 7 | 18321 | idle in transaction | UPDATE orders SET ... id = 7
Read it as a sentence: backend 18344 has been waiting 92 seconds to update order 7, blocked by backend 18321, which holds the lock and is now idle in transaction. That last detail is the tell. The blocker ran a statement, took a lock, and then stopped doing anything without committing: almost always an application bug, a transaction left open across slow work or a code path that never reached its commit. Its blocking_query is only the last statement it sent; the one that took the lock may be earlier in the same transaction.
backend 18321 (holder) backend 18344 (waiter)
────────────────────── ──────────────────────
BEGIN BEGIN
UPDATE orders id=7 ← takes lock
...idle in transaction... UPDATE orders id=7 ← WAITS
(no COMMIT) (blocked, 92s and counting)
│ ▲
└──────────── holds the lock ───────┘
Tracing the blocker back to Rails code
You can run either query from a production Rails console when psql isn’t handy:
sql = File.read("blocking.sql") # either query above
ActiveRecord::Base.connection.select_all(sql).to_a
# => [{"blocked_pid"=>18344, "blocking_pid"=>18321, ...}]
A pid alone doesn’t say which part of your app holds the lock. Name each process type in config/database.yml, so application_name (the blocking_app column above) reads web or sidekiq instead of a blank:
production:
<<: *default
application_name: <%= ENV.fetch("APP_ROLE", "web") %>
Then turn on query log tags (Rails 7.0+):
config.active_record.query_log_tags_enabled = true
Active Record adds an SQL comment to each query naming the application, controller and action, or the job, so blocking_query points at the code path. The trade-offs: the Rails guide notes it disables prepared statements, and pg_stat_activity.query is truncated at track_activity_query_size (1024 bytes by default), which can cut off a comment appended to a long statement; config.active_record.query_log_tags_prepend_comment = true puts it first.
Breaking the standoff safely
Finding the blocker is usually enough: you fix the code path that left the transaction open. But when a held lock is causing an outage and you need it gone now, Postgres gives you two tools, and the order matters:
-- First choice: cancel the running query, keep the connection.
SELECT pg_cancel_backend(18321);
-- Last resort: end the whole session, rolling back its transaction.
SELECT pg_terminate_backend(18321);
pg_cancel_backend cancels the current statement; the connection survives and the application gets an error it can handle. Try it first. But it does nothing to a backend that is idle in transaction, because there is no running statement to cancel. For that case pg_terminate_backend is the tool: it ends the session, which rolls back the open transaction and releases every lock it held. The application sees a dropped connection, so reserve it for when cancel cannot help. Both return true once the signal is sent; on Postgres 14+, pass a timeout in milliseconds as the second argument to pg_terminate_backend to wait for the backend to exit.
Who may run them: superusers, members of the role that owns the target backend, and roles with the privileges of pg_signal_backend. Only a superuser can signal a superuser’s backend. On managed Postgres, where you rarely get a true superuser, check what your admin role is granted before the incident rather than during it.
Bounding lock waits with timeouts
A safer systemic fix than killing backends by hand is to bound the problem at the source. Three settings do it, each disabled (0) by default:
lock_timeoutaborts a statement that waits longer than this for any single lock, the setting aimed directly at this problem. Rails raisesActiveRecord::LockWaitTimeout.statement_timeoutaborts any statement that runs longer than this, waiting or not. Rails raisesActiveRecord::QueryCanceled. Keeplock_timeoutlower; the docs note it is pointless otherwise.idle_in_transaction_session_timeoutterminates the session, not just a statement, once it has sat idle in an open transaction too long. The transaction rolls back and its locks are released.
The docs advise against setting the first two in postgresql.conf, since they would affect every session. Set them per connection with variables, which the Rails Postgres adapter applies with SET SESSION. These values are examples only; size yours from your slowest legitimate query:
production:
<<: *default
variables:
lock_timeout: "5s"
statement_timeout: "30s"
idle_in_transaction_session_timeout: "60s"
They apply to every connection that environment opens, migrations and long jobs included, so give those their own limits (a separate config, or SET LOCAL inside the transaction that needs longer). The Postgres timeout config builder produces one set of these values each for web, jobs and migrations and checks them for conflicts.
How this connects to connection-pool exhaustion
A blocked query is not just one stuck request; it is a held resource. The waiting backend occupies a connection from your Rails pool for the entire 92 seconds it waits. A handful of long lock waits can drain the pool and produce ActiveRecord::ConnectionTimeoutError for unrelated requests, covered in Rails connection pool exhaustion. The pg_locks query shows you the cause; the pool error shows you the blast radius.
Common mistakes
- Reaching for
pg_terminate_backendfirst. Cancel before you terminate. - Using
=instead ofIS NOT DISTINCT FROMin the blocking join. Lock columns are oftenNULL, and=silently drops the matching rows. - Treating the self-join as authoritative. It can list holders whose mode doesn’t conflict;
pg_blocking_pidsapplies the real rules. - Ignoring
idle in transaction. That blocker is an application bug, a transaction left open, not a slow query. - No timeouts. Without them, one forgotten transaction can block traffic until someone notices.
- Confusing a block with a deadlock. No
40P01in the log means blocked, not deadlocked.
Key takeaways
- A hung Rails query with no error is usually waiting on a lock: a
pg_locksrow withgranted = false. pg_blocking_pids(pid)is the fast, authoritative path; call it by hand, not in a tight loop.- The
pg_locksself-join shows the blocking query text but can over-report holders. application_nameand query log tags turn a pid into a process and a controller or job.- Cancel before terminate, and confirm in advance that your role may do either.
- Set
lock_timeout,statement_timeoutandidle_in_transaction_session_timeoutto make hangs bounded failures.
FAQ
How do I find what is blocking a query in Postgres?
Call pg_blocking_pids(pid) for the waiting backend: it returns the process ids blocking it, using Postgres’s real lock-conflict rules. Join those pids to pg_stat_activity for the blocker’s query text. A self-join of pg_locks filtered on NOT granted is an approximation that can list holders whose lock mode does not conflict.
What is the difference between pg_cancel_backend and pg_terminate_backend?
pg_cancel_backend(pid) cancels the running query but leaves the connection open, the safe first choice. pg_terminate_backend(pid) ends the session, rolling back its transaction and releasing its locks. Use terminate only when cancel cannot help, such as an idle in transaction backend. Both require superuser, membership in the target’s role, or pg_signal_backend privileges.
What does granted = false mean in pg_locks?
A row with granted = false is a lock a backend requested but has not yet received, because another process holds or is queued for a conflicting lock on the same object. Filtering on NOT granted shows everything blocked right now.
Why is my Rails query hanging with no error?
It is usually waiting on a lock held by another transaction, not running slowly. Postgres does not break a simple wait, so the query blocks until the holder commits or rolls back, someone cancels it, or a timeout such as lock_timeout fires. Use pg_blocking_pids to find the holder.
Conclusion
The worst production database incidents are often the quiet ones: no error, no deadlock, just a request that never returns and a lock held by a transaction that fell asleep. pg_blocking_pids tells you who holds the lock, the joins tell you what each side is running, and the fix is usually a forgotten commit or a transaction wrapped around a slow call. Keep the blocking query in a snippet, set the three timeouts, and the next silent hang becomes a short diagnosis instead of a guess-and-restart.