Expand, backfill, and contract schema stages beneath an uninterrupted application request stream.
    Back to Blog
    DatabaseMarch 1, 2026

    Zero Downtime Database Migrations

    By Vishkar Platform Engineering Team

    Why Most Migration Guides Will Get You Paged at 2am

    Most database migration tutorials are written against a 10,000-row toy dataset, a single application server, and the implicit assumption that you can stop the world for five minutes. Production is different. According to a Percona survey, 60% of database outages are caused by schema changes gone wrong — not hardware failures, not network partitions, but a developer running ALTER TABLE on a 400GB table during peak traffic (Percona State of Open Source Databases Report, 2023).

    The failure modes are predictable. A naive ALTER TABLE ... ADD COLUMN NOT NULL DEFAULT 'x' on PostgreSQL older than version 11 rewrites the entire table and holds an exclusive lock for the duration. On a 500GB table, that's potentially 20–40 minutes of complete unavailability. Your load balancer health checks start failing around minute two. Your on-call rotation wakes up around minute three.

    We've inherited production systems where the previous team's migration strategy was "do it Sunday at 3am and hope." This post is about replacing hope with repeatable engineering.

    TL;DR: Zero-downtime migrations require the expand-contract pattern: every schema change is split into backward-compatible steps that both old and new application code can tolerate simultaneously. PostgreSQL-specific tools like NOT VALID constraints and CREATE INDEX CONCURRENTLY are essential. On a recent project, we migrated a 500GB table's primary key from int to UUID with zero user-facing errors across a two-week rollout.


    What Is the Expand-Contract Pattern?

    The expand-contract pattern — sometimes called parallel change — is the foundational principle behind every technique in this post. The core idea is simple: never make a schema change that breaks the currently-deployed version of your application.

    Every migration splits into three phases.

    Expand: Add new structures (columns, tables, indexes) that both old and new application code can coexist with. The old code ignores the new column. The new code writes to both.

    Migrate: Backfill data, flip feature flags, deploy new application code. Both versions run simultaneously — this is non-negotiable in any rolling or blue/green deployment.

    Contract: Remove old structures once you've confirmed no running application instance references them. This is usually a separate deployment, days or weeks later.

    The pattern feels slow. It is. That's the point — you're trading deployment speed for the ability to roll back any step independently.


    How Do You Rename a Column Without Locking?

    Column renames are a classic trap. ALTER TABLE users RENAME COLUMN user_name TO username is nearly instantaneous in PostgreSQL — it only updates the catalog — but it immediately breaks any deployed application code still referencing user_name. In a rolling deployment with 20 application instances, you have a race condition the moment you start the rename.

    The safe path is a four-step process spread across multiple deployments.

    Step 1 — Add the new column (no default, nullable):

    ALTER TABLE users ADD COLUMN username TEXT;
    

    This is a metadata-only change in PostgreSQL 11+. It acquires a brief ACCESS EXCLUSIVE lock but releases it in milliseconds.

    Step 2 — Dual-write in application code. Deploy a version that writes to both user_name and username on every insert and update. Reads still use user_name.

    Step 3 — Backfill existing rows in batches. Never update the full table in one transaction. Batch by primary key range to avoid long-held locks and replication lag spikes:

    DO $$
    DECLARE
      batch_start BIGINT := 1;
      batch_size  BIGINT := 10000;
      max_id      BIGINT;
    BEGIN
      SELECT MAX(id) INTO max_id FROM users;
      WHILE batch_start <= max_id LOOP
        UPDATE users
          SET username = user_name
        WHERE id >= batch_start
          AND id <  batch_start + batch_size
          AND username IS NULL;
        batch_start := batch_start + batch_size;
        PERFORM pg_sleep(0.05); -- throttle replication lag
      END LOOP;
    END $$;
    

    Step 4 — Flip reads, then drop. Deploy code that reads from username. Verify in production for at least one full traffic cycle, then drop user_name in a separate migration. The drop is the contract phase.


    Adding NOT NULL Without a Table Rewrite: PostgreSQL's NOT VALID Trick

    PostgreSQL's NOT VALID constraint modifier is one of the most underused features in production database management. It lets you add the constraint definition instantly and defer validation to a separate, lock-minimal step.

    -- Step 1: Add the constraint without scanning existing rows.
    -- Acquires only ShareUpdateExclusiveLock — concurrent writes are allowed.
    ALTER TABLE orders
      ADD CONSTRAINT orders_user_id_not_null
      CHECK (user_id IS NOT NULL) NOT VALID;
    
    -- Step 2: Validate. This scans existing rows but does NOT block writes.
    -- Runs concurrently with production traffic.
    ALTER TABLE orders
      VALIDATE CONSTRAINT orders_user_id_not_null;
    
    -- Step 3: Once validated, set the actual NOT NULL column constraint.
    -- This is now a catalog-only change because the CHECK constraint proves
    -- no nulls exist. Instant lock release.
    ALTER TABLE orders ALTER COLUMN user_id SET NOT NULL;
    ALTER TABLE orders DROP CONSTRAINT orders_user_id_not_null;
    

    The key insight: VALIDATE CONSTRAINT holds only a ShareUpdateExclusiveLock, which blocks other ALTER TABLE commands but not reads or writes. Your application keeps running.


    CREATE INDEX CONCURRENTLY: What the Docs Don't Tell You

    CREATE INDEX CONCURRENTLY is the right way to add indexes to live tables. Standard index creation holds an exclusive lock for the entire build. CONCURRENTLY builds the index in the background, allowing reads and writes throughout (PostgreSQL 17 Documentation, 2024).

    -- Safe for production. No downtime.
    CREATE INDEX CONCURRENTLY idx_orders_created_at
      ON orders (created_at DESC);
    

    Three gotchas we've hit in production that the docs bury in footnotes.

    Gotcha 1 — Failed builds leave invalid indexes. If the session is interrupted, PostgreSQL marks the index INVALID. An invalid index wastes space and can confuse the query planner. Always check after:

    SELECT indexname, indexdef
    FROM pg_indexes
    WHERE tablename = 'orders'
      AND indexname NOT IN (
        SELECT indexrelid::regclass::text
        FROM pg_index
        WHERE indisvalid = true
      );
    

    Drop and rebuild any invalid indexes before proceeding.

    Gotcha 2 — CONCURRENTLY can't run inside a transaction block. Your migration tool must not wrap this in BEGIN ... COMMIT. Flyway handles this with runInTransaction = false on the migration file. Liquibase uses runInTransaction="false" on the changeset.

    Gotcha 3 — Replication lag during builds. On busy replica sets, a concurrent index build on primary generates significant WAL. We've seen replicas fall 30+ seconds behind during index builds on tables with high write rates. Monitor replication lag and throttle if necessary.


    Flyway vs. Liquibase vs. Atlas: Which Tool for Which Job?

    Migration tooling choice matters more than most teams realize. The tools solve different problems, and using the wrong one creates its own class of production incidents.

    CapabilityFlywayLiquibaseAtlas
    FormatSQL filesXML/YAML/JSON/SQLHCL / SQL
    Schema state detectionChecksum-basedChecksum-basedDeclarative diff
    runInTransaction=falsePer-file flagPer-changeset flagNative
    Drift detectionTeam editionBuilt-inBuilt-in (free)
    Best fitSQL-first teamsJava/enterpriseTerraform-style workflows

    Use Flyway when your team thinks in SQL and wants simplicity. The free tier handles most production needs. Pair with flyway repair after any failed concurrent index build.

    Use Liquibase when you need XML/YAML changelogs for audit compliance, or when your team is Java-heavy and wants the rich ecosystem.

    Use Atlas when you're already using Terraform for infrastructure and want your schema managed declaratively. atlas schema apply generates the diff and applies it — similar to terraform apply for your database.

    Teams managing Kubernetes-based data pipelines will find complementary architectural patterns in our guide to scaling Argo Workflows — particularly the PostgreSQL archive backend configuration for Argo's workflow state.


    How Do Blue/Green Deployments Change the Migration Equation?

    Blue/green deployments add a critical constraint to database migrations: both the blue (current) and green (new) application versions must be able to use the database simultaneously. Kubernetes rolling updates have the same requirement.

    The expand phase must be deployed and verified before you cut traffic to green. The contract phase can only run after blue is fully decommissioned. This means your migration has a mandatory minimum span of two deployments.

    We've seen teams short-circuit this by running migrations in the green environment's startup hook, before traffic cuts over. This works until it doesn't — specifically, it fails the moment your green startup hook drops a column that blue is still reading. The rule we enforce: startup hooks may only run idempotent, backward-compatible migrations (additive only). Destructive migrations always deploy as standalone pipeline steps.

    Feature flags are the safety net that makes the expand-contract timeline practical. Wrap the new code path in a flag:

    if (featureFlags.isEnabled('use_username_column', userId)) {
      return db.query('SELECT username FROM users WHERE id = $1', [userId]);
    }
    return db.query('SELECT user_name FROM users WHERE id = $1', [userId]);
    

    Roll the flag to 1% of traffic, then 10%, then 100% over days. If you see errors, flip the flag off. No deployment required, no rollback of schema changes.


    Real-World Example: Migrating a 500GB Table from int to UUID Primary Key

    This is the migration that makes most engineers reach for a maintenance window. It doesn't need one.

    A client came to us after their previous team had scheduled a four-hour maintenance window for this exact migration. We delivered it with zero user-facing errors across a two-week rollout. Here's the condensed version.

    The starting state: A PostgreSQL 15 orders table, 500GB, id SERIAL PRIMARY KEY, referenced as a foreign key by 11 other tables.

    Phase 1 — Add UUID column and populate it (weeks 1–2):

    -- Add nullable UUID column. Instant metadata change.
    ALTER TABLE orders ADD COLUMN uuid_id UUID;
    
    -- Create a default for new rows immediately.
    ALTER TABLE orders ALTER COLUMN uuid_id SET DEFAULT gen_random_uuid();
    
    -- Backfill existing rows in 10k batches (ran over ~18 hours via a background job).
    -- Run this as a recurring job, not a single migration.
    UPDATE orders SET uuid_id = gen_random_uuid()
    WHERE uuid_id IS NULL AND id >= $1 AND id < $2;
    
    -- Add NOT NULL using the NOT VALID pattern after backfill.
    ALTER TABLE orders ADD CONSTRAINT orders_uuid_id_not_null
      CHECK (uuid_id IS NOT NULL) NOT VALID;
    ALTER TABLE orders VALIDATE CONSTRAINT orders_uuid_id_not_null;
    

    Phase 2 — Build the new index concurrently:

    CREATE UNIQUE INDEX CONCURRENTLY idx_orders_uuid_id ON orders (uuid_id);
    

    This took 6 hours on the 500GB dataset. Zero write blocking.

    Phase 3 — Promote the UUID column. We swapped the primary key in a low-traffic window — the catalog lock acquisition for ADD PRIMARY KEY on an already-indexed column is sub-second. All 11 foreign key tables got new uuid FK columns via the same expand-contract process run in parallel.

    Phase 4 — Drop the old id column three deployments later, after confirming zero query plans referenced it via pg_stat_statements.

    Total user impact: zero. Total engineer stress: significantly lower than a 4am maintenance window.


    Frequently Asked Questions

    Can I run CREATE INDEX CONCURRENTLY inside Flyway?

    Yes, but you must set runInTransaction = false in the migration file. Without this, Flyway wraps the statement in a transaction, and PostgreSQL will immediately error: ERROR: CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Add a -- flyway:runInTransaction=false comment at the top of the migration file, or set outOfOrder=false and use a dedicated migration version for all concurrent operations.

    How do I safely backfill 100 million rows without replication lag?

    Batch updates with a sleep between batches are the standard approach. Target batch sizes that complete in under 500ms of wall clock time, then sleep 50–100ms between batches. Use pg_sleep() in PL/pgSQL loops or an external job runner. Monitor pg_stat_replication for replica lag and widen the sleep interval if lag exceeds your SLA threshold. A 100-million-row backfill at 10,000 rows per batch with 50ms sleep takes roughly 14 hours — plan accordingly (PostgreSQL Documentation, 2023).

    What's the safest rollback strategy for a migration already partially applied?

    Never roll back a partially-applied migration by reverting the schema. Instead, write a forward-fix migration that undoes the data change. Keep your expand steps idempotent — ADD COLUMN IF NOT EXISTS, CREATE INDEX IF NOT EXISTS — so re-running them is always safe.

    Does this work with MySQL/MariaDB?

    The expand-contract pattern is universal. For MySQL and MariaDB, the two primary tools are gh-ost (GitHub's Online Schema Change) and pt-online-schema-change from Percona Toolkit. gh-ost reads the binlog directly — no triggers — making it lower-overhead and safer for high-write tables on MySQL 5.7+ and 8.0; its cutover lock is typically under 1 second. pt-online-schema-change uses a trigger-based shadow table approach, which is simpler to set up and works with older MySQL versions and MariaDB, but has higher write amplification and a short write-lock during final cutover on busy tables. Both tools require the source table to have a primary key. PostgreSQL's native CONCURRENTLY and NOT VALID options cover most of the same ground without requiring third-party tools.

    Need help scaling your infrastructure?

    Vishkar delivers production-ready Cloud, DevOps & AI solutions for modern engineering teams.

    Schedule a Consultation