Video in progress

A small ALTER TABLE migration stopped the whole site for a few minutes. What happened, and how do you prevent it?

ALTER TABLE asks for an ACCESS EXCLUSIVE lock and waits for a long query to finish. While it waits, all the ordinary SELECTs queue up behind it, and that's how the site freezes. The protection: run the migration with lock_timeout and retry.

📖 Answer

The scenario goes exactly like this:

  1. An analyst started a 10-minute SELECT, which holds an ACCESS SHARE lock on the table.
  2. The deploy runs ALTER TABLE orders ADD COLUMN note text. It's a very fast operation, but it needs ACCESS EXCLUSIVE and waits for step 1.
  3. Every new SELECT * FROM orders now stands in the queue behind the ALTER, because the lock queue is FIFO.
  4. The pool's connections run out and the health check fails.

The protection is to limit how long the lock wait can last:

-- V27__add_order_note.sql
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN note text;

If it can't get the lock within 3 seconds, the migration stops with an error while the site keeps working. Then you run it again. Some teams automate this with a retry.

Which DDL is expensive (rewrites the table or does a full scan):

  • changing a column type (int → bigint) rewrites it;
  • ADD COLUMN ... DEFAULT now(), a volatile default, rewrites it. In PG 11+ a constant default doesn't rewrite;
  • SET NOT NULL does a full scan. First CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, then SET NOT NULL (PG 12+ doesn't repeat that check);
  • a new FK: the same, in two phases with NOT VALID + VALIDATE.

I review migrations that touch big tables separately and apply them when traffic is low.