SQLNirvana by Pyro

Blog › mysql · postgresql · locks

Who is blocking whom? Finding lock waits in MySQL and PostgreSQL

When queries pile up waiting for each other, here's how to find the session holding the lock, see what it's doing, and decide whether to end it.

A typical lock pile-up: one session starts a transaction, updates a row, then goes quiet, often because the application is waiting on something else or forgot to commit. Every other session that wants that row now waits behind it, connections fill up, and the site slows to a crawl. The fix is usually to find the one blocker.

MySQL (InnoDB)

The sys schema joins the lock tables for you:

SELECT waiting_pid, waiting_query, wait_age_secs,
       blocking_pid, blocking_query, blocking_trx_age, locked_table, locked_type
FROM sys.innodb_lock_waits
ORDER BY wait_age_secs DESC;

If blocking_query is NULL, the blocking session isn't running anything right now: it's sitting in an open transaction. Look it up in the process list:

SELECT id, user, host, db, command, time, state, info
FROM information_schema.processlist WHERE id = 1234;

The raw data lives in performance_schema.data_locks and performance_schema.data_lock_waits (MySQL 8.0 and later).

PostgreSQL

pg_blocking_pids() returns the sessions blocking a given process:

SELECT waiting.pid AS waiting_pid, now() - waiting.query_start AS waiting_for, waiting.query AS waiting_query,
       blocking.pid AS blocking_pid, blocking.state AS blocking_state,
       now() - blocking.xact_start AS blocking_xact_age, blocking.query AS blocking_query
FROM pg_stat_activity waiting
JOIN LATERAL unnest(pg_blocking_pids(waiting.pid)) AS b(pid) ON true
JOIN pg_stat_activity blocking ON blocking.pid = b.pid
ORDER BY waiting_for DESC;

A blocker with state = 'idle in transaction' is the classic culprit: it holds its locks while doing nothing.

Ending the blocker

First find out what it is: which application, which user, which host. Ending a session rolls back its open transaction, which is usually safe for a stuck web request but not for a half-finished batch job.

Stop it happening again

SQLNirvana's Diagnostics tab shows blocked sessions and their blockers live, keeps 24 hours of lock history, and raises a "Needs attention" item when a session has been blocked for more than 30 seconds.

Let SQLNirvana watch it for you

Health, tuning, security and upgrade checks every minute. Free for one server.

Start free