Video in progress
You need to rename a column or change its type in a table running in production. How do you do it with no downtime and with the ability to roll back?
The expand/contract method: first a new column is added, the code writes to both columns, old data is copied in batches, reads switch to the new column, and only at the end is the old column dropped. Each stage is a separate deploy, and at each one the old version of the code can still work.
📖 Answer
ALTER TABLE users RENAME COLUMN phone TO phone_number is a single line, but during a rolling deploy the old pods still reference phone and crash. If you roll back, the old code runs against the new schema. And on a big table, changing a type rewrites the whole table and holds a long lock.
The stages (each a separate release):
- Expand. Add the new column, nullable, with no default (in PostgreSQL 11+ adding it with a default is fast too, but the plain way is safer):
ALTER TABLE users ADD COLUMN phone_number VARCHAR(20); - Dual write. The code writes to both
phoneandphone_number, and reads still come from the old one. - Backfill. Old rows are copied in batches:
Each batch is a separate short transaction — replica lag and locks stay under control.UPDATE users SET phone_number = phone WHERE id BETWEEN :from AND :to AND phone_number IS NULL; - Verification. Check with a query that the two columns match.
- Switching reads. The code reads from the new column and still writes to both — rollback is still safe.
- Contract. Writing to the old column stops, and after a release or two the column is dropped.
Additional subtle points:
- Adding
NOT NULLscans a big table; in PostgreSQL first addCHECK (phone_number IS NOT NULL) NOT VALID, thenVALIDATE CONSTRAINT— the validation doesn't block writes. - For an index,
CREATE INDEX CONCURRENTLY; in Flyway/Liquibase this migration must run outside a transaction. - The DDL lock queue: if a long-running query exists, the
ALTERwaits for it, and all ordinary queries line up behind theALTER. UseSET lock_timeout = '3s'and retry. - Don't use
ddl-auto=updatein Hibernate on prod — it changes the schema without control.
It's slower, but you can go back at every step. On a small table it's overkill; on a big table running 24/7, it's the only safe way.
Sign up to mark studied questions and save your progress.