A battle-tested playbook for executing complex schema mutations across multi-terabyte tables without acquiring exclusive access locks or pausing API ingestion.
The Dreaded AccessExclusiveLock
In PostgreSQL, running an `ALTER TABLE` with a default value or adding certain constraints requires an `AccessExclusiveLock`. On a 5TB `orders` table receiving 5,000 inserts per second, this lock will block all reads and writes, bringing the entire application to a halt.
The Expand/Contract Pattern
We utilize a strict 4-phase Expand and Contract deployment strategy.
1. **Expand**: Add the new column without a default value (which is instantaneous in modern PG).
2. **Dual-Write**: Deploy application code that writes to both the old and new columns.
3. **Backfill**: Run a background worker that batches updates to the new column for historical rows.
4. **Contract**: Switch reads to the new column, then drop the old column.
-- 1. Add column instantly
ALTER TABLE orders ADD COLUMN status_v2 VARCHAR(50);
-- 2. Create index without blocking writes
CREATE INDEX CONCURRENTLY idx_status ON orders(status_v2);
-- 3. Cleanup bloat live
pg_repack --table=orders --no-kill-backend;
For heavy bloat cleanup, we use `pg_repack`, which rebuilds the table online using triggers, swapping it instantaneously at the end. Lock contention window: 0.00ms. True zero-downtime engineering.