An expand-and-contract migration introduces a new representation while old code still runs, copies or dual-writes data as needed, changes readers after verification, then removes the old representation later. The phases matter because a rolling deployment and rollback can leave two application versions alive at once. A schema change that renames a column in place can break the old version immediately.
Database change safety: expand, migrate, contract
Operational decision
A parcel service replaces a free-text delivery state with a constrained state code. First add the new nullable column and teach new writers to populate it while retaining the old field. Backfill in bounded batches with checkpoints, then compare counts and sample records. Change readers only after the data is complete, and defer dropping the old column until the rollback window closes. The SQL fragment shows only the expansion step; the application dual-write, backfill job, and contract migration are separate reviewed changes. On a large table, even adding a column can have database-specific lock or rewrite effects. Rehearse against production-like volume, watch replication lag, and plan what happens if the backfill stops halfway.
ALTER TABLE parcel_events
ADD COLUMN delivery_state_code VARCHAR(32);
CREATE INDEX parcel_events_state_code_idx
ON parcel_events (delivery_state_code);Cost and verification
Backfills consume I/O and can contend with user queries. An index build may block writes depending on the database and command; use the database's online/concurrent mechanism where applicable. Dual-writing adds application complexity and can create divergent values, so measure mismatches until the old path is retired. Rolling back code is safe only while the old field remains valid and populated. Do not assume a migration is reversible merely because its SQL file has a down section.
Common Mistakes
- Do not drop an old column in the same release that introduces its replacement.
- Do not run an unbounded backfill at peak traffic.
- Do not claim rollback works without testing mixed application versions.
Connected lessons
- DevOps Tutorial
- Kubernetes Deployment: rolling update capacity
- Progressive delivery: canary checks and rollback
- Backups and disaster recovery: prove the restore path
