Database migrations are safest when they are treated as part of an application release, not as an emergency command run beside it. The goal is a sequence that old and new application versions can both tolerate while traffic is moving.

Expand before you change

Start by adding the new column, table, or index without removing the old path. Deploy code that can write both representations, backfill in small batches, and measure the work. Only after readers use the new representation should a later release remove the compatibility code. This expand-and-contract pattern avoids coupling a destructive operation to a single deploy.

Treat backfills as production workloads

A backfill competes with user traffic for locks, I/O, and cache space. Make it resumable, bound its batch size, and expose progress and failure metrics. PostgreSQL’s concurrent index creation is one example of choosing an operation that reduces blocking, but it still needs capacity planning and a rollback plan.

Prove the rollback story

Test the old application against the migrated schema and the new application against the pre-migration schema where that is possible. Write down which changes cannot be reversed and keep a restore procedure separate from an application rollback. A migration is ready when the on-call engineer knows what to pause, what to observe, and what data cannot be recovered automatically.

A concrete rollout: split a full name

Suppose a users table has one full_name field and the product now needs given_name and family_name. Add both nullable columns first. Update writes to populate old and new columns, and keep reads on full_name while a bounded job backfills existing rows. Count rows still missing the new fields, inspect names that cannot be split reliably, and let people correct those cases. Switch reads only after the backfill and a period of dual-write monitoring. Drop full_name in a later release, after the old application version can no longer be deployed.

Checks before pressing deploy

Estimate the table size and lock behavior in a staging database of realistic size. Check whether the migration framework wraps operations in one transaction; a long backfill inside that transaction can hold locks and exhaust storage. Define a stop condition for increased query latency and watch replication lag. Keep the backfill checkpointed by primary key so a restart does not begin again at row one.

Sources

Reference: PostgreSQL ALTER TABLE documentation and CREATE INDEX documentation. Lock and rewrite behavior depends on the exact operation and PostgreSQL version; check the documentation for your deployment.

More on Software Engineering →