Video in progress

You need to add a NOT NULL column to a table with 500 million rows and fill in the old rows. How do you plan it without downtime?

I first add the column as nullable or with a constant default (PG11+ doesn't rewrite the table), then backfill in small batches, and set NOT NULL through CHECK ... NOT VALID and VALIDATE with only a short lock. I run every stage with lock_timeout and replica lag monitoring.

📖 Answer

The risks: a long ACCESS EXCLUSIVE lock, one huge transaction (WAL explosion, replica lag, vacuum stalling), and holding a lock during a full table scan.

Step 1: the column (instant, but watch out for the lock queue):

SET lock_timeout = '2s';
ALTER TABLE payment ADD COLUMN currency text;            -- or DEFAULT 'UZS'

Since PG11 a constant default is written only to the catalog. But a volatile default like DEFAULT now() or gen_random_uuid() rewrites the table, so don't do that.

Step 2: the application starts writing the value on new rows (a deploy).

Step 3: the backfill. By id ranges, each batch in its own transaction:

UPDATE payment SET currency = 'UZS'
WHERE id >= :from AND id < :from + 10000 AND currency IS NULL;

Between batches I check the lag in pg_stat_replication and slow down if needed. A periodic pause gives autovacuum a chance to keep up. The whole process must be stoppable and restartable.

Step 4: the constraint:

ALTER TABLE payment ADD CONSTRAINT payment_currency_nn
    CHECK (currency IS NOT NULL) NOT VALID;               -- short lock
ALTER TABLE payment VALIDATE CONSTRAINT payment_currency_nn; -- scans, but doesn't block writes
ALTER TABLE payment ALTER COLUMN currency SET NOT NULL;   -- PG12+: uses the valid CHECK, no scan
ALTER TABLE payment DROP CONSTRAINT payment_currency_nn;

Everything goes in separate Flyway migrations, while the backfill is often not a migration but a separate job, because you need to watch it and be able to stop it for hours. I run it on a copy of prod first and measure the time.