← Back to PostgreSQL, page 3

postgresql-0054 · Medium mid

A migration's ALTER TABLE hangs and blocks all queries. Explain why and protect it with lock_timeout.

ALTER TABLE usually needs an ACCESS EXCLUSIVE lock, so it waits behind any open transaction that has touched the table, even an idle one. While it waits in the lock queue, every new query on that table queues behind it, which looks like an outage. Set lock_timeout for migrations so the ALTER gives up quickly and can be retried.

Full answer

Schema and sample rows:

sql
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');
sql
BEGIN; SELECT name FROM products WHERE id = 1;

PostgreSQL returns:

text
 name
------
 pen
(1 row)

In a second session:

sql
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;

Result on PostgreSQL 17:

text
ERROR:  canceling statement due to lock timeout
sql
COMMIT;

Result:

text
COMMIT

In a second session:

sql
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;

Output:

text
 column_name
-------------
 id
 name
 price
(3 rows)

Session A's open transaction holds an ACCESS SHARE lock from its SELECT. The ALTER in session B waits for it, and after 200 ms fails with 'canceling statement due to lock timeout' instead of hanging; without the timeout, every later query on products would have queued behind the ALTER. Once A commits, the same ALTER succeeds instantly, because adding a nullable column only updates the catalog. Migration tooling should set lock_timeout and retry with backoff, and idle_in_transaction_session_timeout helps end forgotten transactions.

sql
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');

BEGIN; SELECT name FROM products WHERE id = 1;

-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;

COMMIT;

-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • ALTER TABLE takes an exclusive lock
  • It waits behind open transactions
  • Queued DDL blocks later queries
  • lock_timeout makes migrations fail fast
  • Retry with backoff

Common mistakes

  • Running migrations without lock_timeout
  • Leaving transactions idle in application code

Follow-ups

  • Which ALTER TABLE forms take weaker locks?
  • How would you find the blocking session?

Tips

  • Explain the lock queue