DEV Community

Cover image for Database Migrations Without Downtime: The Expand and Contract Pattern
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Database Migrations Without Downtime: The Expand and Contract Pattern

Deploying new code without downtime is a solved problem for many teams: start new instances, shift traffic, stop the old ones. The database is harder. There is usually one schema shared by every running instance, old and new, and changing it can lock tables or break the code that is still running. A migration that takes two seconds on your laptop can block every write in production for minutes.

This article explains why migrations cause downtime and the pattern that avoids it: expand and contract.

Why migrations break things

There are two separate problems.

1. Old and new code run at the same time. During a rolling deploy, some servers run version 1 and some run version 2. Even with a single server, the migration runs either before or after the new code starts, so for some period the schema and the code do not match. If you rename name to full_name in one step, every version-1 instance that still queries name fails immediately.

2. Some schema changes take heavy locks. In PostgreSQL, most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which blocks reads and writes on that table. If the change is instant, the lock is held for a moment and nobody notices. If the change rewrites the table or scans it (changing a column type, adding a NOT NULL check on existing rows, building an index the normal way), the lock is held for as long as the work takes.

There is also a subtle trap: the lock queue. Your ALTER TABLE waits behind a long-running query that holds a weaker lock. While it waits, every new query on that table queues behind the ALTER. The table looks frozen even though the migration has not started its real work yet.

The rule: every step must work with old and new code

A zero-downtime migration is a series of small steps. After each step, both the code currently running and the code about to be deployed must work with the schema. That leads to the expand and contract pattern (also called parallel change):

  1. Expand: add the new structure next to the old one. Nothing is removed.
  2. Migrate: deploy code that writes to both, backfill old data, then switch reads to the new structure.
  3. Contract: once nothing uses the old structure, remove it.

Each phase is its own deploy. It takes longer than one migration file, and that is the price of no downtime.

Example: renaming a column

Say you want to rename users.name to users.full_name.

Step 1, expand. Add the new column, nullable, with no default that needs a rewrite:

ALTER TABLE users ADD COLUMN full_name text;
Enter fullscreen mode Exit fullscreen mode

Old code ignores it. Nothing breaks.

Step 2, dual write. Deploy code that writes both name and full_name on every insert and update, but still reads name. Some teams use a database trigger for this instead of application code.

Step 3, backfill. Copy existing values in small batches, so no single statement locks many rows for long or creates a huge transaction:

UPDATE users SET full_name = name
WHERE id BETWEEN 1 AND 10000 AND full_name IS NULL;
Enter fullscreen mode Exit fullscreen mode

Repeat for the next range until every row is done.

Step 4, switch reads. Deploy code that reads full_name. Keep writing both for now, so you can roll back to the previous version safely.

Step 5, stop writing the old column. Deploy code that uses only full_name.

Step 6, contract. When no running code references name, drop it:

ALTER TABLE users DROP COLUMN name;
Enter fullscreen mode Exit fullscreen mode

In PostgreSQL, dropping a column is a quick catalog change; it does not rewrite the table.

Six steps for a rename feels like a lot. But at no point does a running version of the app see a schema it cannot handle, and every step can be rolled back.

Safe versions of common changes

The exact lock behavior depends on the database and its version, so check your database's documentation. For PostgreSQL, the usual safe forms are:

Adding a column. A nullable column with no default is a quick change. Since PostgreSQL 11, adding a column with a constant default is also quick, because the default is stored in the catalog instead of written to every row. A volatile default such as random() still rewrites the table.

Adding an index. A plain CREATE INDEX blocks writes on the table until it finishes. Use:

CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
Enter fullscreen mode Exit fullscreen mode

It takes longer and cannot run inside a transaction block, and if it fails it leaves an invalid index you need to drop and retry. Many migration tools need a flag to run a step outside a transaction for this.

Adding NOT NULL to an existing column. Setting NOT NULL directly scans the whole table under a heavy lock. A safer path: add a check constraint as NOT VALID (quick, applies only to new rows), then validate it separately, which scans with a lighter lock that does not block reads and writes:

ALTER TABLE users ADD CONSTRAINT full_name_not_null CHECK (full_name IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT full_name_not_null;
Enter fullscreen mode Exit fullscreen mode

Adding a foreign key. Same idea: ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID, then VALIDATE CONSTRAINT in a later step.

Changing a column type. Most type changes rewrite the table. Treat them like a rename: add a new column with the new type, dual write, backfill, switch, drop.

Dropping a column or table. First deploy code that no longer uses it. Some ORMs cache the column list, so make sure the running code does not select it, then drop it in a later deploy.

MySQL has its own rules. InnoDB supports online DDL for many operations, and tools such as gh-ost and pt-online-schema-change copy the table in the background and swap it in when ready.

Protect yourself from lock queues

Set a lock timeout on the migration session so it gives up instead of blocking everyone:

SET lock_timeout = '5s';
Enter fullscreen mode Exit fullscreen mode

If it fails, retry later, when the long-running query is gone. A statement timeout is also useful for steps that should be quick.

Common mistakes

  • Running the migration and the code change in one deploy when they are not compatible in both directions.
  • One giant backfill UPDATE. It holds row locks for a long time, generates a lot of WAL, and can slow replicas. Batch it.
  • Trusting the migration tool to be safe. ORM-generated migrations are correct but not always online. Read the SQL they produce. Linters such as squawk for PostgreSQL or strong_migrations for Rails flag risky operations.
  • Dropping too early. If you roll back the code after dropping the column, the old code fails. Contract only when you are sure.
  • Testing only on small data. A migration that takes 50 ms on a test database may take much longer on a large production table. Test on realistic sizes when you can.

Watch the animated version: https://youtu.be/lVoNo9Vp8Ww

In short

  • Downtime comes from two things: old code meeting a new schema, and schema changes that hold heavy locks.
  • Use expand and contract: add new structure, dual write and backfill, switch reads, then remove the old structure, each in its own deploy.
  • Prefer the online forms: nullable columns, CREATE INDEX CONCURRENTLY, NOT VALID then VALIDATE for constraints.
  • Backfill in batches, set lock_timeout, and read the SQL your migration tool generates.
  • Every step should be safe to roll back.

Originally published at abdeldjalilchougui.biz.

Top comments (0)