Zero-Downtime Schema Migrations

Change database schemas safely inside CI/CD with versioned migrations and the expand-and-contract pattern.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Deployment Strategies and Feature Flags, Database Backups and Restores

Application code can roll back in seconds; a dropped column cannot. Schema changes are where deploys most often cause outages, so they need their own discipline.

Versioned migrations

Store every schema change as an ordered, immutable migration file in the repository and apply it with a tool: Flyway, Liquibase, Atlas, or framework tools such as Prisma Migrate, Alembic, Rails or Django migrations. The tool records which migrations ran in a table, so every environment converges to the same schema.

Running them in pipelines

  • Apply migrations as a separate step (a CI job, a Kubernetes Job, or an Argo CD pre-sync hook) before new app code rolls out.
  • Only one runner at a time: tools take a lock, but make sure your deploy does not start several.
  • Test migrations against a copy of production-sized data in staging to spot slow operations.

Expand and contract

During a rolling deploy, old and new app versions run together, so every schema must work with both:

  1. Expand: add the new column or table, nullable or with a default. Deploy code that writes to both old and new.
  2. Migrate: backfill existing rows in small batches.
  3. Switch reads to the new structure.
  4. Contract: once no running code uses the old column, drop it in a later release.

Dangerous operations

Adding an index without CONCURRENTLY (Postgres) can block writes; rewriting a large table can hold locks for minutes; renaming a column breaks old code instantly. Set a lock_timeout so a migration fails fast instead of queueing every query behind it. Tools such as gh-ost or pt-online-schema-change handle big MySQL changes online.

Good enough to move on: you can run migrations as a gated pipeline step, rename a column with zero downtime using expand and contract, and name three operations that lock tables.

Key concepts

  • Versioned migration files
  • Flyway, Liquibase and Atlas
  • Migrations as a pipeline step
  • Expand and contract
  • Batched backfills
  • Locking operations and lock_timeout
  • Online schema change tools

Mini project

In a demo app, rename a heavily used column with zero downtime across three releases using expand and contract, running each migration as a Kubernetes Job before the rollout, while a load test confirms no errors.

Check yourself

Why is renaming a column in a single migration unsafe during a rolling deployment, even if the new code uses the new name?

Free resources