Database Migrations Without Downtime: Expand-Contract Pattern

Zero-downtime database migrations are one of those skills that separate teams that can ship daily from teams that schedule maintenance windows at 2 AM. I have led migrations on PostgreSQL clusters serving 40k+ writes per second where any lock longer than a few hundred milliseconds would cascade into application timeouts and user-visible errors. The pattern that has consistently let us evolve schema under load without taking the service down is expand-contract — also called parallel change. It requires more discipline than a single ALTER TABLE, but it eliminates the most common source of deployment-related outages: the mismatch between old code, new code, and the database schema during a rolling deploy. This article walks through the pattern as I actually implement it in production, including the SQL, the application changes, and the verification steps that prevent silent data loss.

Why In-Place Schema Changes Break Rolling Deployments

In my experience, the failure rarely comes from the SQL itself. It comes from the deployment window where two versions of your application are running simultaneously against one database. If you run a migration that renames a column from name to full_name and then deploy the code that expects full_name, there is a period where the old pods still running expect name and will throw 500s. Reverse the order — deploy code first — and the new code fails because full_name does not exist yet. This is the backward incompatibility window, and it is the root cause of most migration outages.

Standard migration tools encourage this problem by treating a schema change as an atomic event. You write a single migration file, it runs, and you assume the world is consistent. In a system with connection pooling, rolling restarts, and cached prepared statements, that assumption is false. I've found that even seemingly safe operations like adding a NOT NULL column without a default will hold an ACCESS EXCLUSIVE lock on PostgreSQL while the table is rewritten, blocking all reads and writes for the duration. On a 50M row table, that can be minutes.

Expand-contract solves this by never breaking compatibility. Every step must leave the database usable by both the old and new application versions. We achieve this by splitting every breaking change into three or more safe, small releases instead of one big risky one.

What Counts as a Breaking Change

Any operation that assumes old and new code see the same schema at the same time is breaking. That includes renaming a column or table, changing a column type, splitting a column into two, merging two columns, adding a non-nullable constraint without a default, dropping a column that old code still reads, and adding a new required foreign key. If you are doing any of these, you need an expand-contract flow. Only purely additive, nullable changes like ADD COLUMN ... NULL or CREATE INDEX CONCURRENTLY are safe to run in a single step, and even then you need to be careful with locks.

The Three Logical Phases

The pattern is always: Expand — add the new structure alongside the old without removing anything; Migrate — move and transform data so both structures are correct; Contract — remove the old structure after no code depends on it. Each phase is a separate deploy and a separate migration that can be rolled forward or back safely. Understanding this mental model is more important than the exact SQL.

Expanding the Schema Without Breaking Compatibility

The expand phase is intentionally boring. You are not cleaning anything up; you are only adding. The goal is to make the database a superset that supports both schemas. In a recent project we needed to replace a free-text status VARCHAR(50) with a stricter status_id SMALLINT REFERENCES statuses(id). Instead of altering the column, we expanded.

-- 2024.10.11_expand_add_status_id.sql
-- Safe: ADD COLUMN NULL does not rewrite table, no default
ALTER TABLE orders ADD COLUMN status_id SMALLINT;

-- Safe: add FK as NOT VALID initially to avoid long scan
ALTER TABLE orders ADD CONSTRAINT fk_orders_status_id
  FOREIGN KEY (status_id) REFERENCES statuses(id) NOT VALID;

-- Safe: create index without blocking writes
CREATE INDEX CONCURRENTLY idx_orders_status_id ON orders(status_id);

-- Keep old column; new code will handle both
COMMENT ON COLUMN orders.status IS 'deprecated, use status_id - remove after 2024.11.01';

Notice what we did not do: we did not set NOT NULL, did not validate the foreign key yet, and did not drop the old column. The constraint is NOT VALID which, as described in the Python Documentation patterns for deferred constraint handling and PostgreSQL docs, allows the ALTER TABLE to complete in milliseconds even on large tables. Validation happens later with VALIDATE CONSTRAINT which takes a weaker lock.

At this point we deploy application code that knows about both columns. The application is still reading status but is now capable of writing to both. This dual-capable code is the key to zero downtime. For context on how connection poolers interact with these deploys, see Database Connection Pooling: PgBouncer, HikariCP and Why It Matters — if your pool holds prepared statements referencing the old column list, a naive SELECT * will break even if the schema is compatible.

Rules for a Safe Expand

I enforce three rules during expand: every new column must be nullable or have a default that does not require a table rewrite, every new constraint must be added as NOT VALID or DEFERRABLE, and no existing column or index is dropped or renamed. If you need a new index, always use CONCURRENTLY on PostgreSQL. It takes longer but does not block writes. I've found that running CREATE INDEX CONCURRENTLY outside a transaction block is worth the extra complexity in your migration runner.

Keeping Data Consistent With Dual-Writes and Backfills

Once both structures exist, you need to keep them in sync while old and new writes are happening. There are two mechanisms: dual-writes in the application layer for new traffic, and a backfill for historical rows. You need both. Relying only on a backfill means new writes after the backfill starts will be missed. Relying only on dual-writes means old rows remain null.

We typically implement dual-writes in the service layer, not with database triggers, because triggers hide logic and make debugging harder at scale. The code looks like this:

# app/models/order.py - expand phase, writes to both
def save_order(order: Order) -> None:
    # Map new enum to old string for backward compat
    status_map = {1: "pending", 2: "shipped", 3: "cancelled"}
    legacy_status = status_map.get(order.status_id)

    # Write both columns in same transaction
    db.execute(
        """
        INSERT INTO orders (id, status, status_id, updated_at)
        VALUES (%s, %s, %s, NOW())
        ON CONFLICT (id) DO UPDATE
        SET status = EXCLUDED.status,
            status_id = EXCLUDED.status_id,
            updated_at = NOW()
        """,
        (order.id, legacy_status, order.status_id),
    )

For reads, the expand-phase code prefers the new column but falls back to the old one. This allows a rolling deploy where some instances have not yet been updated to write status_id:

-- Read path that works with both versions
SELECT
  id,
  COALESCE(status_id, 
    CASE status 
      WHEN 'pending' THEN 1 
      WHEN 'shipped' THEN 2 
      ELSE 3 END) AS status_id
FROM orders WHERE id = $1;

The backfill is then run as a separate, throttled job after dual-writes are live. Never run a single UPDATE orders SET status_id = ... on a large table — it will bloat the table, generate massive WAL, and hold locks. In my experience, batching with a sleep interval is mandatory.

Throttled Backfill Pattern

I use a script that updates 1k-5k rows per batch, ordered by primary key, with a pause and explicit VACUUM considerations. Track progress in a separate table so it is resumable. Example runner logic:

-- backfill_status_id.py (simplified)
last_id = 0
while True:
    result = db.execute("""
        UPDATE orders
        SET status_id = CASE status
            WHEN 'pending' THEN 1 WHEN 'shipped' THEN 2 ELSE 3 END
        WHERE id > %s AND status_id IS NULL
        ORDER BY id LIMIT 1000
        RETURNING id
    """, (last_id,))
    if result.rowcount == 0:
        break
    last_id = result.rows[-1].id
    time.sleep(0.1)  # throttle to avoid replica lag
    # optional: check pg_stat_replication lag, pause if > 2s

After the backfill completes, validate the data: SELECT COUNT(*) FROM orders WHERE status_id IS NULL AND status IS NOT NULL should be zero. Only then do you run ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_status_id to enforce the foreign key. If you need to understand how the new index affects query plans before contracting, reviewing SQL Query Optimization: EXPLAIN Plans, Indexes and Join Strategies with EXPLAIN (ANALYZE, BUFFERS) is a useful checkpoint here.

Contracting the Schema After All Readers Have Migrated

Contract is the phase teams rush and regret. You may only remove the old structure after you are certain no running code, no delayed job, no analytics replica, and no old container still references it. I require a minimum of one full deploy cycle plus a buffer — usually 1-2 weeks — between finishing the backfill and dropping the old column. We also add observability first.

Before dropping, I add logging to detect any remaining reads of the deprecated column, and I revoke write access in a soft contract step:

-- 2024.10.25_contract_soft.sql
-- First, make old column read-only via trigger or app check
-- Then, after verification, actual drop in next release

-- Ensure new column is now NOT NULL after backfill validated
ALTER TABLE orders ALTER COLUMN status_id SET NOT NULL;

-- Drop the fallback logic; old column still exists but unused
DROP INDEX IF EXISTS idx_orders_status; -- if no longer needed

The final hard contract migration is tiny but irreversible:

-- 2024.11.01_contract_hard.sql
ALTER TABLE orders DROP COLUMN status CASCADE;
-- If you used a trigger for dual-write, drop it here

I have seen teams attempt to combine soft and hard contract into one deploy to save time. Don't. If a single canary pod with old code is still running during your rolling deploy, dropping the column will cause immediate errors that are not easily rolled back without restoring the column and re-backfilling. Separate releases give you a clean rollback path: you can revert the application without needing a database restore.

Verification Checklist Before Dropping

My pre-contract checklist includes: 1) grep the entire codebase and confirm zero references to status, 2) query pg_stat_statements for any query containing the old column in the last 7 days, 3) check CDC / Debezium / ETL jobs that may replicate the column, and 4) confirm dashboards and BI tools do not select it. For PostgreSQL-specific introspection, techniques from PostgreSQL Advanced Features: CTEs, Window Functions and JSONB like using pg_depend and information_schema can help audit dependencies before the drop.

Navigating Renames, Type Conversions and Constraint Changes

Certain operations are often labeled impossible without downtime, but they are just multi-step expand-contract flows. A rename is the classic example. You never use RENAME COLUMN in a zero-downtime system. Instead, you add the new column, dual-write, backfill, and then drop the old one. To the application it looks like a rename, but to the database it was an add and a drop separated by weeks.

Type changes are similar. Changing a VARCHAR to JSONB or an INTEGER to BIGINT requires a new column with the target type. For integer widening on a high-write table, I add a BIGINT column, dual-write with casting, backfill, then swap reads. PostgreSQL 11+ has made some ALTER COLUMN TYPE rewrites less painful, but on a table with heavy traffic I still avoid in-place type changes because they take an ACCESS EXCLUSIVE lock for the duration of the rewrite.

Adding a NOT NULL or UNIQUE constraint also follows expand-contract. Add the column nullable, backfill with a sensible default, then add the constraint as NOT VALID followed by VALIDATE CONSTRAINT. For unique constraints, create a UNIQUE INDEX CONCURRENTLY first, then add the constraint using that index: ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX .... This avoids the long exclusive lock that a direct ADD CONSTRAINT UNIQUE would take. The IETF RFC Standards on HTTP semantics (IETF RFC Standards) remind us that idempotency matters — your backfill and dual-write logic should be safe to retry if a deploy fails mid-way.

Handling Foreign Keys Without Outages

Foreign keys are a frequent source of long locks because validation scans the entire table. Always add them NOT VALID, backfill the child table to ensure all values have matching parents, then VALIDATE CONSTRAINT which only needs a SHARE UPDATE EXCLUSIVE lock and does not block writes. If you need to drop a foreign key that is heavily used, remember that the index that was automatically created for it is not dropped automatically — remove it explicitly if it is no longer needed for queries.

Coordinating Expand-Contract Across Code, Deploys and Monitoring

The technical SQL is the easy part. The coordination is where projects slip. Expand-contract requires tight coupling between migration ordering and code deploys. I structure this as four distinct releases in our CI/CD pipeline, each with its own migration and code change, and each verified by automated checks.

Migration Pattern Downtime Required Rollback Complexity Best For
Expand-Contract (Parallel Change) None Low — revert code, old column still exists Frequent deploys, large tables, breaking changes
In-Place ALTER (Single Deploy) Seconds to minutes (exclusive lock) High — may need restore or reverse migration Small tables, internal tools, maintenance windows allowed
Blue-Green with Snapshot Seconds (cutover) Medium — DNS / router flip back Entire schema rewrites, multi-service coordination
Trigger-Based Online Change (pt-osc, gh-ost) None Medium — tool-specific cleanup MySQL large tables, no app dual-write wanted

We gate each phase with feature flags and observability. During expand, we emit metrics for dual_write_mismatch_total — if the old and new columns diverge, we alert. During backfill, we monitor replication lag on followers; if lag exceeds 3 seconds, the backfill job pauses automatically. During contract, we monitor error rates for undefined_column exceptions — any spike means an old code path is still live. I've found that adding a temporary database view that exposes both columns and comparing row counts hourly catches drift before it becomes customer impact.

Rollbacks must be tested before you need them. If you need to roll back after expand but before contract, you just revert the application to stop writing the new column — no database change needed. If you need to roll back after contract (after dropping the column), you must recreate the column and re-backfill from the new column, which is why we keep a logical backup of the dropped column for at least 30 days. Document this recovery path in the same pull request as the contract migration, not after the fact.

Finally, treat your migration files as code that is reviewed as strictly as application code. I require every migration to include: the expected lock level, estimated duration on a table of N rows, whether it runs in a transaction or not, and the rollback plan. Tools like pg_query and strong_migrations can lint for dangerous operations automatically in CI. This discipline turns database changes from risky events into routine, boring releases — which is exactly what you want.

Frequently Asked Questions

How many deploys does a single expand-contract change actually require?

At minimum three: 1) Expand — add the new column/index/constraint and ship code that dual-writes and reads with fallback; 2) Migrate — run the backfill and validate constraints after dual-writes are confirmed in production; 3) Contract — ship code that stops using the old column, then drop it. In practice I ship four deploys by splitting contract into a soft contract (stop writing the old column but keep it) and a hard contract (drop the column) with at least a week in between for verification. Each deploy must be independently safe to roll back.

Can I use database triggers instead of application dual-writes?

You can, but I rarely recommend it for primary application tables. Triggers keep data in sync even if a service forgets to dual-write, but they hide business logic in the database, add write overhead on every transaction, and make debugging harder when a write fails. I've used triggers only for cases where multiple independent services write to the same table and updating all of them at once is not feasible, or for low-volume reference tables. For most web applications, explicit dual-writes in the service layer are clearer and easier to observe and remove during contract.

What if my ORM generates SELECT * and breaks when I add a column?

SELECT * is incompatible with expand-contract and with stable production systems in general. An added column changes the column order and can break code that relies on positional mapping or that fetches unnecessary large columns like JSONB. Require explicit column lists in all application queries. If you cannot change the ORM behavior quickly, expand by adding the column as nullable and ensure the ORM's model is updated to know about it before the migration runs, so its SELECT * remains valid. Long term, enforce a lint rule that bans SELECT * in application code.

How do I handle zero-downtime migrations on tables larger than 100M rows?

The same expand-contract logic applies, but batching and throttling become critical. Backfill in small batches of 1k-5k rows with sleeps, monitor replica lag and bloat, and run VACUUM or pg_repack considerations afterward. Always use CONCURRENTLY for indexes and NOT VALID for constraints. For extremely large tables, consider tools like pgroll or gh-ost that automate the shadow-table approach, but understand that they trade application dual-write complexity for trigger or WAL-based complexity. Regardless of tooling, never run a single large UPDATE or ALTER that rewrites the whole table in one transaction.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards