Video in progress
You need to rename a column in a big production table. How do you do it without stopping the service?
With expand/contract (parallel change): first I add the new column and the application writes to both, the data is copied in chunks, reads move to the new column, and only after every instance runs the new version is the old column dropped. Each step is a separate deploy and can be rolled back.
📖 Answer
Why a plain rename doesn't work: during a rolling deploy the old and new versions run side by side. The moment the migration renames the column, the old instances start failing, and rolling back becomes impossible too.
Using customer_name → full_name as an example:
- Expand, the migration:
alter table orders add column full_name varchar(200); -- nullable, no default, so it's fast
-
Deploy A: the application writes to both columns, and on read uses
coalesce(full_name, customer_name). -
Backfill, in chunks:
update orders set full_name = customer_name
where id between :from and :to and full_name is null;
One big UPDATE locks the table for a long time and generates a lot of WAL. Do it in batches of 5-10 thousand rows, with a pause in between.
-
Deploy B: reads only from
full_name, but still writes to both, so a rollback is safe. -
Constraints: for
NOT NULLin PostgreSQL, firstcheck (full_name is not null) not valid, thenvalidate constraint, with no long lock. -
Deploy C: writing to the old column stops.
-
Contract: after watching for a while,
drop column customer_name.
Two more things. Put a lock_timeout on every migration, otherwise an ALTER waiting in the queue stops the whole table, which is a classic case on prod. And find out in advance whether other services or ETL/BI also read this column.
Sign up to mark studied questions and save your progress.