Incident Response

PostgreSQL ERROR: canceling statement due to lock timeout

A statement waited longer than lock_timeout for a lock and gave up. Usually that is the setting doing its job. Here is how to find the blocker, why the waiting query can be more dangerous than the one holding the lock, and how to run DDL on busy tables.

· 11 min read · AG Data Team

ERROR: canceling statement due to lock timeout means a statement waited for a lock longer than lock_timeout allowed, and PostgreSQL cancelled it. The error is SQLSTATE 55P03, lock_not_available, raised by the interrupt processing code. No data changed. Most of the time this is the setting working as intended: it is far better for a migration to fail after three seconds than to sit in a lock queue and stall the whole application.

SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN source text;

ERROR:  canceling statement due to lock timeout

What lock_timeout actually limits

The documentation defines lock_timeout as the maximum time a statement may wait while trying to acquire a lock on a table, index, row or other object. A few details matter:

The related NOWAIT errors are could not obtain lock on relation "..." and could not obtain lock on row in relation "...". They come from LOCK ... NOWAIT or SELECT ... FOR UPDATE NOWAIT, which fail immediately instead of waiting at all.

Step 1: find the blocker

Retrying without knowing who holds the lock rarely helps. pg_blocking_pids() returns the sessions that block a given process, and pg_stat_activity shows wait_event_type = 'Lock' for a session waiting for a heavyweight lock:

-- who is waiting, and who is blocking them
SELECT pid,
       pg_blocking_pids(pid)          AS blocked_by,
       wait_event_type,
       state,
       now() - xact_start             AS xact_age,
       left(query, 80)                AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

-- what the blockers are doing
SELECT pid, usename, application_name, state,
       now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE pid IN (SELECT unnest(pg_blocking_pids(pid))
              FROM pg_stat_activity);

In our experience the blocker is usually one of these:

  1. A session that is idle in transaction. It ran a query, opened a transaction and never committed. Its locks stay until it ends, because locks are released only at transaction end (explicit locking).
  2. A long report or analytics query. Even a plain SELECT holds ACCESS SHARE, which conflicts with the ACCESS EXCLUSIVE lock that most ALTER TABLE forms need.
  3. Autovacuum, a backup or another migration. Look at application_name and usename before you decide what to cancel.

Once you know the blocker, choose: wait for it to finish, ask its owner to commit, or end it with pg_cancel_backend(pid) or pg_terminate_backend(pid). Cancelling the backend of a payment job to let a column be added is rarely the right trade.

Why the waiting statement is the dangerous one

The pg_blocking_pids() documentation describes two kinds of blocking. A hard block is a held lock that conflicts with the request. A soft block is a session that is only waiting for a conflicting lock but is ahead in the queue. This is what turns a harmless migration into an outage:

  1. A long SELECT holds ACCESS SHARE on orders.
  2. ALTER TABLE orders ... requests ACCESS EXCLUSIVE and waits.
  3. Every new query on orders, even a simple SELECT, now queues behind the waiting ALTER.
  4. Connections pile up, the pool runs dry and the application goes down, although the ALTER itself would take milliseconds.

Set lock_timeout before every DDL on a busy table. With a short lock_timeout, the ALTER gives up after a few seconds, the queue clears and the application continues. Then you retry. Without it, the queue lasts as long as the slowest query in front of it.

Step 2: run DDL with a short timeout and retries

Use SET LOCAL inside a transaction so the setting does not leak into other work on the same connection:

BEGIN;
SET LOCAL lock_timeout = '3s';         -- give up quickly instead of queueing
SET LOCAL statement_timeout = '15min'; -- upper bound for the work itself
ALTER TABLE orders ADD COLUMN source text;
COMMIT;

Then retry with growing pauses, either in your migration tool or in a simple loop:

for i in 1 2 3 4 5 6 7 8 9 10; do
  psql -X -v ON_ERROR_STOP=1 -f add_column.sql && break
  echo "attempt $i failed, retrying"; sleep $((i * 5))
done

Our guide to zero-downtime PostgreSQL migrations describes the full pattern: split DDL into small steps, keep each lock short and retry the steps that time out.

What changes on large databases and fleets

-- default for the migration role, also works through a pooler
ALTER ROLE migrator SET lock_timeout = '3s';

Key takeaways

PostgreSQL Errors Locks Migrations
Work with us

Migrations stuck behind locks?

We run PostgreSQL schema changes on busy production tables with short lock windows, retries and monitoring, and track down the sessions that block them.

Get in touch More from the blog