Schema migrations (expand and contract)

Why you need it

During a deploy, old and new copies of the code run at the same time, against the same database. If the new code renames a column, the old copies still ask for the old name, find nothing, and break.

Think of it like this

Changing your phone number. You keep the old one working for a while, and tell people the new one. Only once nobody calls the old number do you give it up.

Where you’ll find it

  • Stripe: Moved huge tables with no downtime in four steps, described in online migrations at scale.
  • pgroll: pgroll runs expand and contract for Postgres, so old and new code can each see the table shape they expect.
  • Ruby on Rails: The strong_migrations gem stops unsafe changes, like a rename, and prints the safe steps instead.

What to know first

Old and new together. While a deploy runs, some copies run the old code and some the new. See Rolling deploys.

Schema. The shape of a table: its columns and their names.

Migration. A script that changes the schema, like adding or removing a column.

How it works

  1. A rename breaks the old copy. The new code says town, so the column city is renamed. The old copy still asks for city and gets an error. This is the first picture in the animation.
  2. Expand: add, do not change. Add town beside city and copy the values across. Now both copies find the column they ask for. This is the expand step in the animation.
  3. Replace the old copies. Deploy the new code while both columns exist. When the last old copy is gone, nobody asks for city any more.
  4. Contract: remove last. Only now drop the old column. Nothing breaks, because nothing uses it.
  5. Keep both in step. While both columns exist, new rows must fill both, or the old copy reads stale values. The new code often writes to both. On a big table, copy the values in small batches.

An example

Monday: add town and copy 2 million cities across, 10,000 rows at a time, in about 20 minutes.

Tuesday: deploy the new code, which reads town and writes both. Old and new copies run together for 5 minutes and both work.

Next week: no code reads city, so it is dropped. Visitors never saw an error.

Further reading

  • ParallelChange, Danilo Sato, on martinfowler.com. The expand, migrate, contract steps in one short page. Start with this one.
  • Online migrations at scale, Stripe engineering blog. A real migration of hundreds of millions of rows, step by step.
  • Evolutionary Database Design, Pramod Sadalage and Martin Fowler. How to change a database in small, safe steps as the code changes.