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 limit applies separately to each lock acquisition attempt, not to the statement as a whole.
- It covers explicit locks (
LOCK TABLE,SELECT ... FOR UPDATEwithoutNOWAIT) and implicit ones, such as the lock thatALTER TABLEneeds. - The default is 0, which means no limit. If you never set it, statements wait as long as it takes.
- If
statement_timeoutis the same or lower, settinglock_timeoutis pointless, because the statement timeout always fires first. That is a different error, covered in our article on canceling statement due to statement timeout. - The documentation advises against setting it in
postgresql.conf, because it would affect all sessions.
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:
- 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). - A long report or analytics query. Even a plain
SELECTholdsACCESS SHARE, which conflicts with theACCESS EXCLUSIVElock that mostALTER TABLEforms need. - Autovacuum, a backup or another migration. Look at
application_nameandusenamebefore 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:
- A long
SELECTholdsACCESS SHAREonorders. ALTER TABLE orders ...requestsACCESS EXCLUSIVEand waits.- Every new query on
orders, even a simpleSELECT, now queues behind the waiting ALTER. - 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
- Turn on lock wait logging, and know your version. log_lock_waits logs a message such as
process 12345 still waiting for AccessExclusiveLock on relation ...when a wait is longer thandeadlock_timeout, which defaults to 1 second (lock management). Its default isoffup to PostgreSQL 18 andonfrom PostgreSQL 19. PostgreSQL 18 also added log_lock_failures, which currently logs onlySELECT ... NOWAITfailures. - Remove long-lived blockers at the source.
idle_in_transaction_session_timeoutends sessions that sit idle inside a transaction, and PostgreSQL 17 addedtransaction_timeout, which limits how long any transaction may run (client settings). Set them per role or per application. A global value that kills legitimate batch jobs creates its own incidents. - Poolers and SET do not mix well. In our experience, a plain
SET lock_timeoutsent through a pooler in transaction mode applies to whatever server connection runs that transaction, and may not be there for the next statement. UseSET LOCALinside the transaction, or set a default for the role:
-- default for the migration role, also works through a pooler
ALTER ROLE migrator SET lock_timeout = '3s';
- Treat 55P03 as retryable in application code. For short OLTP transactions that use row locks, a small
lock_timeoutand an automatic retry are usually better than waiting a long time. In our experience it also makes lock problems visible in metrics instead of hiding them as slow requests. - Count the error per table. A rising number of lock timeouts on one table after a release usually means a new long transaction or a new code path that locks rows in a different order. Alert on it the same way you alert on deadlocks.
Key takeaways
- "Canceling statement due to lock timeout" (55P03) means a lock wait exceeded
lock_timeout. The default 0 means no limit. - Find the blocker with
pg_blocking_pids()andpg_stat_activitybefore you retry or cancel anything. - A waiting ACCESS EXCLUSIVE request blocks every later query on the table. That queue causes the outage, not the DDL.
- Run DDL with
SET LOCAL lock_timeoutof a few seconds and retry with backoff. log_lock_waitsis off by default up to PostgreSQL 18 and on from 19. Use idle-in-transaction and transaction timeouts per role.