Nov 23, 20266 min read

Expand and Contract Database Migrations

How to change a column, table or constraint in a live Postgres database without downtime: add the new shape, write to both, backfill in batches, switch reads, then remove the old one, with each step as its own deploy.

Illustration for Expand and Contract Database Migrations

Renaming a column takes one line of SQL and breaks production for the minutes while a rolling deploy runs old and new code side by side. The old version asks for name, the new version asks for full_name, and one of them is always wrong.

Expand and contract, also called parallel change, avoids that by making each step safe for both versions. It costs three or four deploys instead of one, and it never needs a maintenance window.

What are the steps?

StepSchema changeCode changeSafe to roll back?
1. ExpandAdd full_name, nullableNoneYes
2. Dual writeNoneWrite both columnsYes
3. BackfillUpdate old rows in batchesNoneYes
4. Switch readsAdd the constraintRead full_nameYes
5. ContractDrop nameStop writing nameNot without a backup

Martin Fowler's parallel change describes the same three phases, and the Prisma data guide on expand and contract walks through a column rename in SQL. The rule underneath is that the schema must always work with the previous version of the code and the next one.

How do you expand safely?

Adding a nullable column with no default is a metadata change in Postgres, so it is fast on any table size. The part that bites is the lock: ALTER TABLE needs an exclusive lock, and if a long query holds the table, the ALTER waits and every query behind it waits too. Set a short lock timeout so the migration fails fast instead of queueing the table:

-- 2_expand_full_name.up.sql SET lock_timeout = '3s'; ALTER TABLE users ADD COLUMN full_name TEXT;

If it fails on the lock, run it again at a quieter time. Creating indexes on large tables needs CREATE INDEX CONCURRENTLY, which cannot run inside a transaction block, so check how your migration tool runs each file.

How do you backfill?

Update old rows in batches of a few thousand with a pause between them, so the job does not hold locks or flood replication. Each batch picks rows that still need work, which makes the job safe to stop and rerun:

UPDATE users SET full_name = name WHERE id IN ( SELECT id FROM users WHERE full_name IS NULL ORDER BY id LIMIT 2000 );

Repeat until it updates zero rows. Do this from application code or a script, not from a migration file, because a migration that runs for an hour blocks the deploy.

How do you tighten the constraint?

Add NOT NULL last, and avoid the full-table scan under an exclusive lock. A NOT VALID check constraint skips the scan, VALIDATE CONSTRAINT checks existing rows with a weaker lock, and since Postgres 12 a validated check lets SET NOT NULL skip its own scan:

-- 4_full_name_not_null.up.sql ALTER TABLE users ADD CONSTRAINT full_name_present CHECK (full_name IS NOT NULL) NOT VALID; ALTER TABLE users VALIDATE CONSTRAINT full_name_present; ALTER TABLE users ALTER COLUMN full_name SET NOT NULL; ALTER TABLE users DROP CONSTRAINT full_name_present;

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and each step maps to a numbered migration file next to the service plus a code change. The schema change docs state the rule this pattern relies on: migrations are applied before the application restarts with the new code, so the old code must work with the new schema, which is what every expand step guarantees. Databases are declared in code with SQLDatabase, as the database docs show.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create accounts --example=ts/hello-world$ cd accounts && mkdir -p users/migrations$ ls users/migrations1_create_users.up.sql 2_expand_full_name.up.sql

The code for steps 2 to 4 changes in the same service file over three deploys:

// users/users.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; const db = new SQLDatabase("users", { migrations: "./migrations" }); interface User { id: number; name: string; } // Deploy 2: dual write. Reads still use the old column. export const create = api( { expose: true, method: "POST", path: "/users" }, async (req: { name: string }): Promise<User> => { const row = await db.queryRow<User>` INSERT INTO users (name, full_name) VALUES (${req.name}, ${req.name}) RETURNING id, name`; return row!; }, ); // Deploy 3: the backfill, run by calling this endpoint until it reports zero. export const backfill = api( { expose: false, method: "POST", path: "/users/backfill" }, async (): Promise<{ updated: number }> => { let updated = 0; for await (const _row of db.query<{ id: number }>` UPDATE users SET full_name = name WHERE id IN (SELECT id FROM users WHERE full_name IS NULL ORDER BY id LIMIT 2000) RETURNING id`) { updated++; } return { updated }; }, ); // Deploy 4: reads switch to full_name, and the constraint migration ships with it. export const get = api( { expose: true, method: "GET", path: "/users/:id" }, async ({ id }: { id: number }): Promise<{ id: number; name: string }> => { const row = await db.queryRow<{ id: number; full_name: string }>` SELECT id, full_name FROM users WHERE id = ${id}`; return { id: row!.id, name: row!.full_name }; }, );

encore run starts a local Postgres and applies every migration in order, so you can test each step against a copy of the schema as it will look in production. A coding agent asked to rename a column writes the migration and the matching code change together and can follow this sequence deliberately, since each step is a small diff that runs locally. After step 5 ships, add 5_drop_name.up.sql; Encore applies migrations on each deploy to your AWS or GCP account, with the database running on RDS or Cloud SQL.

Best fit: Teams that deploy continuously and cannot take downtime for schema changes.

Things to decide early

  • Timing. Leave at least one full deploy between steps so no old instance is still running when you contract.
  • Backups. Dropping a column is the only step that cannot be rolled back, so take a snapshot first.
  • Triggers or dual writes. A database trigger that copies the value covers writers you do not control, such as scripts and other services, at the price of hidden logic.
  • ORMs. Generated clients cache column lists, so regenerate and redeploy them between steps.

Frequently asked questions

What is the expand and contract migration pattern?

It splits a breaking schema change into compatible steps. You expand the schema by adding the new column or table, move writes and then reads to it over separate deploys, and contract by removing the old structure once nothing uses it. At every step the running code works against the current schema.

Why not rename a column in one migration?

A rename is instant in Postgres, but the old application version still running during a rolling deploy queries the old name and fails. Expand and contract keeps both names working until every instance runs the new code.

How do you add a NOT NULL constraint without locking a large table?

Add a CHECK constraint with NOT VALID, which does not scan the table, then validate it, which only takes a light lock. On Postgres 12 and later you can then set NOT NULL cheaply and drop the check.

How do you do expand and contract migrations with Encore?

With Encore, each step is a numbered migration file plus a code change. Encore applies migrations before the new code is restarted, so the old code must work with the new schema, which is exactly what each expand step guarantees.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders