Database Migrations in Production
Execute zero-downtime database schema changes safely in production PostgreSQL and MySQL systems.
Overview
Overview
Database migrations are among the highest-risk operations in production. A naive ALTER TABLE on a large table can take a lock for minutes or hours, block reads and writes, and cause a full outage. Knowing how the database executes DDL, and which operations are safe at what scale, is what lets you migrate without downtime.
The safe method, called expand-contract, splits one risky change into six small ones. You add the column as nullable with no default, deploy code that writes the new column, backfill in batches, enforce NOT NULL through a CHECK ... NOT VALID constraint plus VALIDATE, deploy code that reads the new column, and finally drop the old column. Before walking those steps, it helps to see exactly what goes wrong without them.
Key concepts
- AccessExclusiveLock
- Expand-Contract Pattern
- CREATE INDEX CONCURRENTLY
- NOT VALID Constraint
- Backfill
Interview questions
- Walk through the safe zero-downtime migration sequence for adding a NOT NULL column with a default to a 500-million-row PostgreSQL table.
- What happens when CREATE INDEX CONCURRENTLY fails partway through, and how do you recover?
- How do you safely backfill a large column in PostgreSQL without causing replication lag or I/O saturation?
Sign up free to read the full topic
More Troubleshooting topics
Start free on Cariara · Coding problems · System design studio