← Lessons

quiz vs the machine

Gold1480

Databases

Schema Evolution And Migrations

Change a live schema safely with versioned, ordered, reversible migrations.

6 min read · core · beat Gold to climb

Schema Evolution And Migrations

A schema is never finished. Migrations are the versioned, ordered scripts that evolve it over time, so that every environment reaches the same structure by running the same steps in the same order.

Good migration practice rests on a few rules:

  • Each migration is small and atomic, doing one change.
  • Migrations are ordered and recorded, so a tracking table knows which have run.
  • Migrations are forward only in production but ideally have a defined down step for local use.

The hard part is changing a schema that is live and serving traffic. A naive rename or a not null column added in one step can break running application versions or lock a large table. The safe pattern is the expand and contract migration, sometimes called parallel change.

It runs in phases:

  • Expand add the new column or table without removing the old, and backfill data.
  • Migrate deploy code that writes to both old and new shapes and reads the new.
  • Contract once nothing reads the old shape, drop it in a later migration.

Because each phase is backward compatible, old and new application versions coexist during a rolling deploy. This avoids downtime and lets you roll back a deploy without a broken schema. Treat migrations as code, review them, and test them on production sized data.

Key idea

Evolve a live schema with small ordered migrations using expand and contract phases so old and new code coexist without downtime.

Check yourself

Answer to earn rating on the learn ladder.

1. What problem does the expand and contract pattern solve?

2. Why must migrations be ordered and recorded?

3. In expand and contract, when do you drop the old column?