DAT-22Required
Expand first and contract later
Make every schema change work with both the old and the new code, so deploys and rollbacks never break.
How to do it
To rename a column, add the new one and write to both, from the app or a trigger. Copy old rows across in batches, then move reads to the new column. Keep writing both columns until no release that reads the old column can still be a rollback target. Only then stop writing it, and drop it in a later release. Add columns as nullable or with a constant default, and add NOT NULL once every row is filled. Never drop or rename in the same release that stops using a column. That is what lets an automatic rollback run without a schema error.
Examples
SQL example
-- Release 1: expand
ALTER TABLE customers ADD COLUMN full_name text;
UPDATE customers SET full_name = name WHERE full_name IS NULL AND id BETWEEN $1 AND $2;
-- Release 2: code reads full_name and still writes both columns, so release 1 stays a safe rollback
-- Release 3: code writes full_name only, once release 1 can no longer be deployed
-- Release 4: contract
ALTER TABLE customers DROP COLUMN name;
How to check
Deploy the migration, then run the previous release's tests against the new schema. They pass. Then let the new release create and edit a record, roll back to the previous release, and read that record. It shows the new release's values.
Sources
Related rules
- ENG-8 Deploy in one step and roll back by itself in Engineering
- TST-12 Test against the same database engine in Testing
- SCL-27 Change large tables in small batches in Scaling
- DEN-21 Give notice before removing a column people use in Data engineering
- EVT-5 Treat each source schema as a contract in Integration and events
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/migrations/expand-and-contract">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.