Zero-Downtime Schema Migrations With Expand-Contract

The riskiest change most engineering teams make is the one they treat as routine: a single migration script that alters a table the whole application depends on, run at midnight, with rollback that amounts to a prayer.

Big-bang schema changes cause outages because they assume the application and the database can change in the same instant. They cannot. There is always a window — sometimes seconds, sometimes the length of a deployment — where old code is talking to a new schema, or new code is talking to an old one. If the change is not backward-compatible across that window, something breaks: a writer hits a column that no longer exists, a reader gets a NULL it was never written to handle. For a regulated firm, that is not just downtime. It is an unplanned, poorly-evidenced change to a system of record, which is exactly the category of event a supervisor asks about afterwards.

Expand-contract is the pattern that closes the window. Instead of one irreversible cutover, you decompose the change into a sequence of individually safe, individually reversible steps, each of which keeps both the old and the new shape of the data valid at the same time. It is slower to plan and it produces more commits. It is also the difference between a migration you can run on a Tuesday afternoon and one you have to schedule an outage for.

Free · 4 minutes

Is your engineering team shipping safely, or quietly accumulating risk?

Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.

The four phases, and why the order is fixed

The pattern has four movements, and the ordering is not a matter of taste. Each phase exists to guarantee that the next one has nothing depending on the thing it is about to remove.

  1. Expand. Add the new structure alongside the old one, as an additive, non-breaking change. A new nullable column, a new table, a new index built concurrently. Nothing reads it yet. Old code is entirely unaffected because, from its point of view, nothing changed.
  2. Dual-write. Deploy application code that writes to both the old and the new structure on every mutation. From this point, new rows are correct in both shapes. Reads still come from the old structure.
  3. Backfill. Copy the historical data into the new structure in bounded batches, so that old rows catch up with the new ones. When this completes, both shapes hold the full dataset.
  4. Contract. Switch reads to the new structure, confirm nothing still depends on the old one, then remove it — drop the column, drop the table, drop the trigger.

The property that makes this safe is that at every step the system is deployable and rollbackable in isolation. If the backfill misbehaves, you have not yet switched reads, so nothing user-facing is wrong. If the new read path is faulty, the old column still holds valid data and you revert one deployment. You never hold the whole change in a state where reverting means data loss.

A worked example: changing how a value is stored

Say an orders table stores amount as a numeric in currency units, and you have decided — correctly — that money should be an integer count of minor units to avoid rounding drift. You cannot simply retype the column: every reader and writer would break the moment you did. Expand-contract turns it into a controlled sequence.

-- PHASE 1 (Expand): additive, non-breaking.
-- In PostgreSQL 11+ adding a nullable column is metadata-only: no table rewrite, no long lock.
ALTER TABLE orders ADD COLUMN amount_cents bigint;

-- Build any index the new read path needs without locking writes.
CREATE INDEX CONCURRENTLY idx_orders_amount_cents ON orders (amount_cents);

-- PHASE 2 (Dual-write) happens in application code, not SQL:
-- every INSERT/UPDATE now sets BOTH amount and amount_cents.
-- Old code paths keep working because amount is untouched.

The backfill is where teams most often cause the outage they were trying to avoid. A single UPDATE orders SET amount_cents = round(amount * 100) takes a lock on every row and can stall the table for the length of the statement. Batch it, key on the primary key, and commit between batches so locks stay short and replication keeps up.

# PHASE 3 (Backfill): bounded batches, keyset pagination, short locks.
import time

BATCH = 5000
last_id = 0

while True:
    rows = db.execute(
        """
        WITH batch AS (
            SELECT id FROM orders
            WHERE id > %(last)s AND amount_cents IS NULL
            ORDER BY id
            LIMIT %(batch)s
        )
        UPDATE orders o
        SET amount_cents = round(o.amount * 100)
        FROM batch
        WHERE o.id = batch.id
        RETURNING o.id
        """,
        {"last": last_id, "batch": BATCH},
    ).fetchall()

    if not rows:
        break

    last_id = max(r[0] for r in rows)
    db.commit()      # commit each batch; never hold one long transaction
    time.sleep(0.1)  # let other writers and the replica breathe
-- PHASE 4 (Contract): only after reads have moved to amount_cents
-- and you have confirmed nothing writes amount any more.

-- Enforce the invariant. SET NOT NULL scans the table under an
-- exclusive lock; on a large table, add a NOT VALID CHECK first,
-- VALIDATE it (which does not block writes), then SET NOT NULL.
ALTER TABLE orders ALTER COLUMN amount_cents SET NOT NULL;

-- Remove the old structure once nothing depends on it.
ALTER TABLE orders DROP COLUMN amount;

The soak time is the point, not the delay

The instinct is to run all four phases in one release to get it over with. Resist it. The value of the pattern comes from letting each phase soak in production before the next depends on it. Dual-write should run long enough that you are confident every write path — including the batch job nobody remembered, the admin tool, the third-party integration — is populating the new structure. Backfill should complete and be verified before you switch a single read. The gap between phases is where you catch the writer you forgot about, and it costs you nothing but calendar time.

This is also why the pattern generalises well beyond adding a column. A table split, a foreign-key introduction, a move to a normalised reference table — all of them decompose the same way. The same discipline underpins backward-compatible API evolution, where you add the new field before you deprecate the old one and never remove anything a client still reads; if you already design the contract before the code, the schema version of the argument will feel familiar.

Where this fits change governance

For a regulated firm, expand-contract is not just an availability technique. It is a governance one. Each phase is a small, reviewable, independently deployable change with a defined rollback — which is precisely what a change-management framework asks you to demonstrate. A big-bang migration produces one high-risk change record with a rollback plan nobody has tested. Expand-contract produces a sequence of low-risk records, each with a real, exercised revert path, and an audit trail that shows the data was never left in an inconsistent state.

The same logic scales up to the infrastructure level. The reason I reached for logical replication rather than an in-place major upgrade was the same one that drives expand-contract at the column level: keep the old thing serving until the new thing is proven, then cut over, then remove. It is the pattern that lets a platform migration proceed as a governed series of steps instead of a single weekend everyone dreads.

A schema is a live contract with every process that touches it. You do not renegotiate a live contract by tearing it up at midnight and hoping the counterparties agree by morning.

Looking at an acquisition, supplier, or major project?

The greatest risks are rarely visible in the executive summary. The Sixteen Pillars framework surfaces the technology risks that diligence usually misses.