Zero-Downtime Alembic Migrations with Expand and Contract in PostgreSQL

Infrastructure & DevOps

Plan zero-downtime Alembic migrations in PostgreSQL with expand and contract, resumable backfills, staged constraint checks and tests for older app versions.

TL;DR

  • Design zero-downtime Alembic migrations around the versions of your application that will run together. In PostgreSQL, make an additive schema change first, preserve reads and writes for both versions during the rollout, then remove the old shape in a later release. A successful migration command only proves that the database accepted the statements.
  • Keep backfills out of the deployment transaction. Run them in small, resumable transactions, measure their impact and let the database continue to enforce new writes. For nullable-to-required changes, use a NOT VALID check, validate it and then make the column NOT NULL while the proof is still available.
  • Run migrations from a single deployment job with a lock budget. Rehearse upgrades and mixed-version behaviour on a database that already has representative data. Schedule destructive steps after the rollback window closes. For concurrent index builds, verify catalog state after failures because an interrupted revision can leave behind an invalid index.

Why fast SQL can still take an application offline

A customer table uses full_name and now needs display_name. An engineer has a migration ready, but the API runs a rolling deployment. Several old replicas still insert the original column, and a nightly export still selects it. The team cannot stop writes for the rollout. It also has a fleet of read replicas, so an application rollout can get ahead of replica replay even after the primary’s migration process finishes.

A direct rename affects every SQL client immediately when it commits. It also needs a table lock. Many ALTER TABLE operations take an ACCESS EXCLUSIVE lock unless PostgreSQL documents a weaker one. A rename may change only metadata, but waiting to acquire that lock can let read and write queues grow, particularly when a seconds-long export transaction already has the table open. A second failure follows if old containers then try to use a missing column. PostgreSQL 17 lock behaviour for ALTER TABLE

Put the migration and release schedule on the same timeline. Inventory workers, ingestion jobs, feature-flagged APIs, reports and rollback images. Each one can continue to use yesterday’s table shape. Inventory processes outside your service too, such as data exports that query the primary and consumers that require a replica to have applied changes. Confirm the desired name is a compatible representation before treating it as a rename. If it has different semantics, define how the old representation can be maintained through the compatibility window.

The example below assumes PostgreSQL 17, Alembic with SQLAlchemy 2.0 and psycopg 3, a table public.customer with a positive stable bigint primary key id, and an existing full_name text NOT NULL column. It handles compatible names. A change that splits a name into multiple parts needs an explicit transformation and a plan for information lost in either direction.

Plan expand and contract as compatibility windows

Zero downtime is a property of the deployment sequence and the workload it runs under. The goal is that every active binary sees a usable schema and that the database stays inside its normal latency budget. Keep the application rollback path available by committing compatibility layers before changing traffic.

WindowDatabaseApplicationGo/no-go check
ExpandBoth names exist. A trigger mirrors writes.Only the old name is required.Current app completes its normal write paths on the expanded schema.
Backfill and switchCopy old rows in batches and validate the new column.Read both as needed. Roll out the new column once it is ready.Null and mismatch counts are zero, and dependent replicas have caught up.
ContractDrop compatibility objects and the original column.Only the new name is used across all processes.Old binaries are past their rollback window, and dependencies are checked.

Choose where compatibility lives. An application can write both columns when every writer is known, upgraded, and under one release process. For an old binary that cannot change, a short-lived BEFORE trigger can keep both values in sync. It runs for direct SQL and other writers that go through the normal table write path. Bypassing triggers or writing through a path that has different replication semantics needs separate handling. Label temporary compatibility code, name its owner and put a removal deadline on it.

The non-obvious failure is a legacy worker that overwrites a value after the backfill has already copied it. A backfill proves what was true when it ran. Compatibility needs to exist before the first batch and remain until the last old writer is retired. Another common error is to keep an old application reading a shadow column while a new writer silently drops the information the old application needs. The simple rename here has an exact mapping both ways.

When splitting a table, add the destination schema and key mapping first. Own the relationship in one place through the transition. Backfill with a stable source key, and compare both representations. A foreign key can then be introduced NOT VALID and validated separately if its table and version support the operation. A destructive schema change often cannot be restored meaningfully by running an autogenerated downgrade.

Implement the migration with Alembic and PostgreSQL

Add a column and mirror writes before traffic changes

Place the expansion in a revision based on your current head. The example uses the default schema public for the Alembic column operation. Standard online Alembic environments wrap PostgreSQL migrations in transactions. Keep the change short and let a lock timeout abort if it cannot enter the schedule during normal production workload. Claim one runner before invoking Alembic.

from alembic import op
import sqlalchemy as sa

revision = "20261120_expand_name"
down_revision = "20261119_baseline"

def upgrade():
    op.execute("SET LOCAL lock_timeout = '500ms'")
    op.add_column("customer", sa.Column("display_name", sa.Text(), nullable=True))
    op.execute("""
      CREATE FUNCTION public.sync_customer_display_name() RETURNS trigger
      LANGUAGE plpgsql SET search_path = pg_catalog AS $$
      BEGIN
        IF TG_OP = 'INSERT' THEN
          NEW.display_name := COALESCE(NEW.display_name, NEW.full_name);
          NEW.full_name := COALESCE(NEW.full_name, NEW.display_name);
        ELSIF NEW.full_name IS DISTINCT FROM OLD.full_name
          AND NEW.display_name IS NOT DISTINCT FROM OLD.display_name THEN
          NEW.display_name := NEW.full_name;
        ELSIF NEW.display_name IS DISTINCT FROM OLD.display_name
          AND NEW.full_name IS NOT DISTINCT FROM OLD.full_name THEN
          NEW.full_name := NEW.display_name;
        ELSIF NEW.display_name IS NULL THEN
          NEW.display_name := NEW.full_name;
        END IF;

        IF NEW.display_name IS DISTINCT FROM NEW.full_name THEN
          RAISE EXCEPTION 'customer name columns disagree'
            USING ERRCODE = '23514';
        END IF;
        RETURN NEW;
      END;
      $$;
    """)
    op.execute("""
      CREATE TRIGGER customer_sync_display_name
      BEFORE INSERT OR UPDATE ON public.customer
      FOR EACH ROW EXECUTE FUNCTION public.sync_customer_display_name()
    """)

def downgrade():
    op.execute("SET LOCAL lock_timeout = '500ms'")
    op.execute("DROP TRIGGER customer_sync_display_name ON public.customer")
    op.execute("DROP FUNCTION public.sync_customer_display_name()")
    op.drop_column("customer", "display_name")

On insert the trigger fills whichever name the caller omitted. On update it mirrors the changed value. A client providing two different names gets a constraint-like error. Old rows fill in on unrelated updates too. Test old inserts, new inserts, old updates after a backfill, new updates while old readers still run, both columns provided with different values, and changes that roll back.

The expansion downgrade is useful only if everything still expects the old shape or after the application has rolled back to it. Once new application versions expect the new column, the normal recovery is to roll back the application while preserving both columns. Keep that choice possible by deploying expansion revisions and application code as separate operations.

Run the backfill as an independent job

Before reading from the new column, seed historical rows. Let the worker bind :after_id through SQLAlchemy, starting at zero for this fixture. Run the loop outside Alembic, for example as a scheduled or manually initiated batch. Use one cursor and commit each statement’s transaction. The Alembic cookbook calls out separate data migrations as an option for substantial transformations. Alembic’s techniques for data migrations

BEGIN;
SET LOCAL lock_timeout = '500ms';
SET LOCAL statement_timeout = '8s';

-- The worker binds :after_id and commits before saving the new cursor.
WITH batch AS (
  SELECT id FROM customer
  WHERE id > :after_id AND display_name IS NULL
  ORDER BY id LIMIT 1000
  FOR UPDATE
)
UPDATE customer AS c
SET display_name = c.full_name
FROM batch
WHERE c.id = batch.id AND c.display_name IS NULL
RETURNING c.id;
COMMIT;

Persist the highest returned ID only after the database commits. If the process stops between commit and checkpoint, the next run can repeat the last batch safely because completed rows no longer meet the null condition. A lock timeout keeps the cursor on the same value for a retry. An empty result can end the forward scan, but complete a final correctness check independently. Confirm both null counts and mismatch counts using display_name IS DISTINCT FROM full_name.

Add a sleep or adaptive limit based on application latency, replica replay and write-ahead log volume. A one-off full-table UPDATE can create many dead tuples and hold locks for too long. If you later parallelise the worker, allocate separate non-overlapping key ranges or use explicit reconciliation. Advancing one global cursor after a SKIP LOCKED scan can strand rows whose locks were skipped.

Validate the invariant, add optional indexes and remove the old name

Once the compatibility trigger protects writes and the backfill is complete, add and validate a check proving there are no null values. New writes are checked as soon as the check is installed. PostgreSQL can validate it with a weaker lock than the usual ALTER TABLE default. With a valid check available, setting NOT NULL can avoid an additional table scan, although the command still needs its lock. PostgreSQL 17 documentation on validation and SET NOT NULL

-- Run each transaction as a separate revision/deployment step as appropriate.
BEGIN;
SET LOCAL lock_timeout = '500ms';
ALTER TABLE customer ADD CONSTRAINT customer_display_name_present
  CHECK (display_name IS NOT NULL) NOT VALID;
COMMIT;

BEGIN;
SET LOCAL lock_timeout = '500ms';
SET LOCAL statement_timeout = '15min';
ALTER TABLE customer VALIDATE CONSTRAINT customer_display_name_present;
COMMIT;

BEGIN;
SET LOCAL lock_timeout = '500ms';
-- Keep the validated check available while PostgreSQL sets NOT NULL.
ALTER TABLE customer ALTER COLUMN display_name SET NOT NULL;
ALTER TABLE customer DROP CONSTRAINT customer_display_name_present;
COMMIT;

Only index the column when a real query needs it. CREATE INDEX CONCURRENTLY keeps normal writes possible during a build and must run outside a transaction block. Configure transaction_per_migration=True in the Alembic environment and put this operation in an isolated revision, since autocommit_block() unconditionally commits any preceding transaction. Do not rely on an index name existing as proof the build finished. Alembic’s autocommit transaction behaviour, PostgreSQL concurrent index builds and invalid indexes

from alembic import op

revision = "20261120_customer_display_name_idx"
down_revision = "20261120_display_name_required"

def upgrade():
    with op.get_context().autocommit_block():
        op.create_index(
            "ix_customer_display_name", "customer", ["display_name"],
            schema="public", postgresql_concurrently=True,
        )

def downgrade():
    with op.get_context().autocommit_block():
        op.drop_index(
            "ix_customer_display_name", table_name="customer",
            schema="public", postgresql_concurrently=True,
        )

Deploy the release that uses only display_name while the two columns still exist. Search application SQL, reports, views, ETL jobs, ORM load lists and rollback images for full_name. When all consumers are clear and the rollback window closes, deploy the contract revision with a short lock budget. Check database dependencies and avoid CASCADE unless the objects removed have been reviewed explicitly.

BEGIN;
SET LOCAL lock_timeout = '500ms';
DROP TRIGGER customer_sync_display_name ON public.customer;
DROP FUNCTION public.sync_customer_display_name();
ALTER TABLE public.customer DROP COLUMN full_name;
COMMIT;

Verify release compatibility in CI

This workflow boots a disposable PostgreSQL database. It assumes requirements.lock contains the application’s pinned Alembic, SQLAlchemy and psycopg dependencies and that env.py reads DATABASE_URL. It checks revision application and differences Alembic’s autogeneration can detect. Add tests that restore your previous revision, seed awkward data, migrate, and exercise both application versions within each compatibility window. Alembic check and its autogeneration limits

name: Check PostgreSQL migrations
on:
  pull_request:
jobs:
  migration-check:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: migration_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd="pg_isready -U test -d migration_test"
          --health-interval=5s --health-timeout=3s --health-retries=12
    env:
      DATABASE_URL: postgresql+psycopg://test:test@localhost:5432/migration_test
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: python -m pip install -r requirements.lock
      - run: alembic upgrade head
      - run: alembic check

On a separate disposable database, check that reversible revisions can downgrade and upgrade once more. For a destructive revision, exercise restore or the forward recovery procedure. In production, use an authenticated migration runner and serialize deployments per database. A workflow concurrency key can coordinate runs of one pipeline. An independent job or human runner still needs to honour the same database-level coordination rule.

Failures to rehearse before the change reaches production

A queued schema lock backs up requests

An idle transaction or lengthy query holds a relation lock and the migration waits. Later requests can accumulate behind it. Look at blocker pairs and query age in pg_locks and pg_stat_activity. Let the migration fail on a bounded lock timeout, investigate the blocker and retry at a safer time. Killing sessions ad hoc can discard unrelated work.

A replica exposes the old schema after primary migration

The new version reads a replica that has not replayed the schema change yet. Application queries can fail with 42703 for an undefined column. Check replay progress and the actual replica schema before routing new reads. During rollout, direct affected reads to the primary if the workload can tolerate it.

A concurrent index is present but invalid

Lock, capacity and timeout failures can leave an invalid index in the catalog without moving Alembic’s revision marker. Inspect pg_index.indisvalid and verify the exact definition. Review and remove the invalid index using appropriate concurrent DDL before retrying. An indiscriminate IF NOT EXISTS can silently keep the unusable object.

The new commit is incompatible with a rollback binary

Once the old column has been dropped, a rollback image that selects it will fail. Keep the compatibility window open until your recoverable releases agree on the schema. Document who can approve contract and how to restore a deleted representation from a known backup or forward transformation if required.

When to choose a different migration strategy

  • Short planned write downtime can be a better fit for a small internal tool with a maintenance agreement and a tested restore. A simpler change executed during a bounded pause can reduce weeks of temporary compatibility code.
  • A shadow table or logical replication can help with a transformative rewrite that simply does not fit the current table structure. Design how sequences, deletes, foreign keys and dual writes are reconciled before the final cutover. The write handoff still needs a bounded cutover plan.
  • A compatibility view can preserve a legacy read contract while a new underlying table evolves. Choose it for known read-only consumers, or explicitly define semantics for inserts and updates when the legacy view needs to remain writable.

Estimate duration with a rehearsal and measure database load

In a hypothetical migration, 12 million historical rows at 1,000 updated rows per committed batch gives about 12,000 batches. At an average cadence of two commits per second, that is about 100 minutes, excluding pauses and retries. Use that arithmetic to choose an operational window, then rehearse on comparable row and index shapes. Track remaining nulls, row count per commit, replication delay and latency for representative API queries. A faster worker can still leave the migration running longer if it forces unhealthy replica lag and needs emergency pauses.

Frequently asked questions

How do I rename a PostgreSQL column without breaking old clients?

Add the new column while keeping the original. Introduce a compatibility path that preserves writes from both versions, backfill old data, then move readers and writers to the new name. Keep both columns through the rollback window. Drop the old name only after every active application and dependency has moved.

Can PostgreSQL add a NOT NULL constraint without scanning twice?

Add a CHECK constraint proving the column is not null, using NOT VALID to defer the initial scan. Validate the check after backfilling. With the validated check still present, PostgreSQL can skip a new scan when setting NOT NULL. The final statement still needs a table lock.

Why does Alembic need autocommit for a concurrent index?

PostgreSQL refuses CREATE INDEX CONCURRENTLY inside a transaction block. Alembic normally runs PostgreSQL migrations transactionally, so put the index build in an isolated revision and use autocommit_block. If the command fails, check the index definition and validity before retrying. PostgreSQL may have persisted an invalid index.

What should CI test for expand-and-contract migrations?

Start from the previously deployed schema with representative data. Run the new expansion revision, exercise old and new binaries together, test the backfill restart path, and rehearse the contract with only compatible code. Alembic check can expose detectable differences between schema and metadata, while integration tests exercise behaviour.

Further reading

Planning zero-downtime Alembic migrations for a live service? Contact Dumb Potato to review the rollout phases, affected applications and evidence needed before the contract step.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with cloud and devops

Discuss your project