Video in progress
How do you rename a column or drop a column without stopping the application?
With the expand-contract method: first I add the new column and the application writes to both, I move the data over, then I switch reads to the new column and drop the old column only in the last release. Every stage is a separate deploy.
📖 Answer
In a rolling deploy, the old and new versions run at the same time. If a migration does RENAME COLUMN full_name TO name, the old pods fail immediately with column "full_name" does not exist.
The stages:
Release 1 (expand): ADD COLUMN name text;
the app writes to full_name AND name, reads from full_name
Backfill: UPDATE ... SET name = full_name WHERE name IS NULL (in batches)
Release 2: the app reads from name, still writes to both
Release 3: writes only to name
Release 4 (contract): DROP COLUMN full_name;
Dropping a column is similar: first the code stops using the column, and the next release does the DROP. If the field stays in a Hibernate entity, it goes into the SELECT and fails once the column is gone.
Don't do the backfill with one big UPDATE: it locks millions of rows in one transaction, bloats the WAL, and leaves the replica behind:
UPDATE app_user SET name = full_name
WHERE id IN (SELECT id FROM app_user WHERE name IS NULL LIMIT 5000);
-- repeat until it returns nothing, with a small pause in between
It's a lot of work, but the only way around it is a downtime window.
Sign up to mark studied questions and save your progress.