Schema Migrations

Evolve your database schema safely with versioned migrations, including on large live tables.

Intermediate · about 5 hours · difficulty 3/5

Learn first: ORMs and Query Builders

A migration is a versioned script that changes the schema (and sometimes data) from one state to the next. Migrations live in your repo, run in order, and let every environment (your laptop, CI, staging, production) reach the same schema reproducibly.

Tools

Most ORMs include a migration tool (Prisma Migrate, Django migrations, Alembic for SQLAlchemy, EF Core migrations, Rails migrations). Standalone options include Flyway, Liquibase, golang-migrate and dbmate.

Zero-downtime changes

During a deploy, old and new versions of your code run at the same time, so each migration must be compatible with both. The expand and contract pattern handles risky changes:

  1. Expand: add the new column or table (nullable, no heavy default).
  2. Deploy code that writes to both old and new, then backfill existing rows in batches.
  3. Switch reads to the new structure.
  4. Contract: remove the old column in a later release.

Dangerous operations on big tables

  • Adding a NOT NULL column with a volatile default, changing a column type, or creating an index without CONCURRENTLY can lock a table for minutes.
  • Set a lock_timeout so a migration fails fast instead of blocking all traffic.

Pitfalls

  • Editing a migration that has already run in production. Write a new one instead.
  • Renaming a column in one step while old code still reads it.

You are ready to move on when you can rename a column in a live system using expand and contract with no errors during the deploy.

Key concepts

  • Versioned migration files
  • Up and down migrations
  • Expand and contract pattern
  • Batched data backfills
  • CREATE INDEX CONCURRENTLY
  • lock_timeout
  • Flyway, Liquibase, Alembic

Mini project

In a sample app, rename users.name to users.full_name across three migrations and two deploys using expand and contract, with a load script running the whole time to prove zero errors.

Check yourself

Why must a migration be compatible with both the old and new version of your application code?

Free resources