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:
- An analyst started a 10-minute
SELECT, which holds anACCESS SHARElock on the table. - The deploy runs
ALTER TABLE orders ADD COLUMN note text. It's a very fast operation, but it needsACCESS EXCLUSIVEand waits for step 1. - Every new
SELECT * FROM ordersnow stands in the queue behind the ALTER, because the lock queue is FIFO. - 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 NULLdoes a full scan. FirstCHECK (col IS NOT NULL) NOT VALID, thenVALIDATE CONSTRAINT, thenSET 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.
Sign up to mark studied questions and save your progress.