Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 25 min · revision 3

Zero-Downtime Changes with Expand and Contract

Measure what DDL really costs on a busy PostgreSQL table — lock queues, rewrites, index builds — then use the expand-migrate-contract pattern to change it while the old and new releases keep serving traffic.

Contentsand lesson path

On this page

  1. Why it matters
  2. What a metadata-only ALTER really costs
  3. Rewrites and index builds
  4. Expand, migrate, contract
  5. Check your understanding
  6. Apply it
  7. Review prompt

Lessons of Database Schema Migrations

  1. Why Schemas Need Version Control Concept · 15 min
  2. The Alembic Loop: Autogenerate, Review, Apply Worked example · 25 min
  3. Moving Data, Not Just Columns Worked example · 20 min
  4. Zero-Downtime Changes with Expand and Contract Concept · 25 min
  5. Lab: Ship a Column Rename Through CI Without Downtime Lab · 30 min
  6. Check: Is This Migration Safe to Ship? Knowledge check · 8 questions

What you will learn

  • Plan a zero-downtime schema change with the expand-migrate-contract pattern, avoiding long-held table locks.

Prerequisites: Data Access with SQLAlchemy

01. Why it matters

Your service runs more than one copy, and a deploy replaces them gradually, so for a while old and new code run against the same database at the same time. The schema you migrate into must keep both of them working. A migration that is instant on a 60-row dev table can stall a production site for minutes — not because it is slow, but because of which locks it takes and who queues behind them.

This lesson measures those costs on a real PostgreSQL 17 table with 2 million rows and a 178 MiB heap, using four connections playing the parts of a long report, a migration, and live API traffic. Then it shows the pattern that lets most schema changes run during working hours, each step holding its locks only briefly: expand, migrate, contract. The lab that follows ships a column rename as three such migrations.

02. What a metadata-only ALTER really costs

Almost every ALTER TABLE takes an ACCESS EXCLUSIVE lock on the table — the strongest there is: nothing else may read or write it, not even a plain SELECT, until the ALTER finishes. Adding a nullable column is metadata-only and takes milliseconds once it has the lock. The problem is getting the lock. If a five-second report holds a read lock, the ALTER waits — and while it waits, every new query on that table queues behind the ALTER, because waiting requests are granted in order. The migration is now a cork in the bottle.

Illustrative output · 2M-row table: one open reader transaction, one ALTER, one API read
[t= 0.06s] reader: counted 2000000 rows, transaction left open
[t= 0.71s] pg_stat_activity: 2 backends waiting on a lock
        active      Lock: ALTER TABLE readings ADD COLUMN IF NOT
        active      Lock: SELECT id FROM readings LIMIT 1
[t= 5.06s] reader: committed, lock released
[t= 5.06s] ddl: ALTER TABLE ... note_queue finished
[t= 5.07s] api:   SELECT ... LIMIT 1 finished
ddl total wait: 5.06s, api total wait: 5.07s

The API query should take about 2 ms; it took 5.07 s, waiting behind an ALTER that was itself only waiting. You can watch the pile-up in pg_stat_activity, where the wait_event_type = Lock rows appear. The defence is to refuse to queue: set a short lock_timeout, so the ALTER gives up instead of camping on the lock, and retry after a pause. The failed ALTER costs one aborted statement; the waiting one would have cost every query on the table for as long as the report ran.

Python · inside upgrade(): fail fast, undo the attempt, retry
conn = op.get_bind()
for attempt in range(5):
    try:
        with conn.begin_nested():  # SAVEPOINT: undo only this attempt
            conn.execute(text("SET LOCAL lock_timeout = '2s'"))
            conn.execute(text(
                "ALTER TABLE readings ADD COLUMN note text"
            ))
        break
    except OperationalError:
        time.sleep(2 ** attempt)  # back off, let readers finish
else:
    raise RuntimeError("could not get the lock on readings")
Illustrative output · same scenario, lock_timeout = 1s
[t= 1.10s] ddl: gave up: canceling statement due to lock timeout
[t= 1.11s] api:   SELECT ... LIMIT 1 finished
api total wait: 1.11s (stall bounded by the 1s lock_timeout)
Illustrative output · the retry loop (2s timeout) against a 4s reader
reader: lock held for 4s
alter: attempt 1 failed: canceling statement due to lock timeout
reader: committed
alter: succeeded on attempt 2 after 4.0s

The stall shrank from "as long as the report" to "one timeout", and the retry succeeded the moment the reader finished. Three details in the loop matter. First, a timed-out statement aborts the transaction, so the attempt must be undone, but only the attempt: op.get_bind() is the transaction Alembic opened in env.py, which by default covers every pending revision of the run, so a plain conn.rollback() would also throw away the earlier revisions and the alembic_version row, and the upgrade would fail. begin_nested() wraps each attempt in a savepoint instead. Second, SET LOCAL scopes the timeout to this transaction, not to every session as postgresql.conf would. Third, the else branch fails the deploy loudly when five attempts are not enough. While the loop sleeps, locks taken by earlier statements of the same upgrade stay held, so keep a lock-sensitive ALTER in a revision of its own, or set transaction_per_migration=True in env.py. For which locks conflict with which, follow transaction isolation.

03. Rewrites and index builds

Two more DDL costs are worth measuring before you fear them. First, ADD COLUMN with a default: PostgreSQL stores a constant or stable default in the table metadata and does not touch any row — but a volatile one such as clock_timestamp() rewrites the whole table and its indexes while holding that ACCESS EXCLUSIVE lock. On the 178 MiB lab table:

Illustrative output · same table, three defaults
heap before any ADD COLUMN:          177.6 MiB
after DEFAULT false (constant):      177.6 MiB
after DEFAULT now() (stable):        177.6 MiB in 0.00 s
after DEFAULT clock_timestamp():     223.5 MiB in 7.85 s  <- rewrite

now() is stable — one value per transaction — so it qualifies; clock_timestamp() really varies per row, so all two million rows are rewritten, the heap grows, and the table is locked for the whole rewrite. The safe recipe for "column with a per-row computed value" is the one you already know: add the column nullable, backfill, then tighten.

Second, indexes. A plain CREATE INDEX blocks writes (reads continue) for the whole build — 1.3 s of blocked writes on this table, an eternity at production traffic. CREATE INDEX CONCURRENTLY builds without blocking them, at the price of a slower build:

Illustrative output · one INSERT timed during each build
plain         INSERT while index building:  1263.0 ms
concurrent    INSERT while index building:     1.9 ms

INSERT with no build running:             1.8 ms

The catch: CONCURRENTLY cannot run inside a transaction block, and Alembic wraps migrations in one. The escape hatch is an autocommit block, which commits anything before it and runs the index statement outside a transaction:

Python · migration that built ix_books_slug on the lab database
def upgrade() -> None:
    with op.get_context().autocommit_block():
        op.create_index(
            'ix_books_slug', 'books', ['slug'],
            unique=False, postgresql_concurrently=True,
        )

Because the block commits prior work unconditionally, put it last in the migration. Whether a given index helps a query at all is a question for query optimisation; here the concern is only building it without a write outage.

The second catch is what a failed build leaves behind. A concurrent build runs as several transactions: it records the index in the system catalogue as invalid, scans the table twice, and before it finishes it waits for every transaction whose snapshot is older than its second scan — anywhere in the database, not only on books. In a test run, one REPEATABLE READ session left open on a different table held the build in pg_stat_activity with wait_event = virtualxid until a 3 s lock_timeout cancelled it.

If the build fails at any point — a duplicate in a unique index, a deadlock, a cancel, that timeout — the command errors but the index stays, marked INVALID. Queries ignore it. If it failed after the build scan, as the timeout did, every insert and update still maintains it, and a unique one still rejects duplicates. The autocommit block has already committed, so nothing rolls it back. Here is a failure on purpose: a unique index over a column with one duplicate, in a scratch database cic (PostgreSQL 17.12):

SQL · cic=# (setup: 200,000 slugs, one duplicate)
CREATE TABLE books (
  id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slug text NOT NULL
);
INSERT INTO books (slug) SELECT 'book-' || g FROM generate_series(1, 200000) g;
INSERT INTO books (slug) VALUES ('book-42');  -- one duplicate slips in
SQL · cic=# (fail, rerun, detect, recover)
CREATE UNIQUE INDEX CONCURRENTLY ux_books_slug ON books (slug);
\d books
CREATE UNIQUE INDEX CONCURRENTLY ux_books_slug ON books (slug);
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ux_books_slug ON books (slug);
SELECT indexrelid::regclass AS index, indisvalid
  FROM pg_index WHERE NOT indisvalid;
DELETE FROM books WHERE id = 200001;
DROP INDEX CONCURRENTLY ux_books_slug;
CREATE UNIQUE INDEX CONCURRENTLY ux_books_slug ON books (slug);
Expected output (the \d table header trimmed)
ERROR:  could not create unique index "ux_books_slug"
DETAIL:  Key (slug)=(book-42) is duplicated.
Indexes:
    "books_pkey" PRIMARY KEY, btree (id)
    "ux_books_slug" UNIQUE, btree (slug) INVALID

ERROR:  relation "ux_books_slug" already exists
NOTICE:  relation "ux_books_slug" already exists, skipping
CREATE INDEX
     index     | indisvalid 
---------------+------------
 ux_books_slug | f
(1 row)

DELETE 1
DROP INDEX
CREATE INDEX

Read it in order. The rerun fails with already exists, usually the first symptom in a deploy log. Worse, IF NOT EXISTS reports success: it checks only the name, so the broken index satisfies it, and the documentation warns that an existing index need not resemble the one requested. The reliable test is pg_index.indisvalid (or INVALID in \d). Recovery is to fix the cause, DROP INDEX CONCURRENTLY, and build again; REINDEX INDEX CONCURRENTLY is the documented alternative. A migration that may be retried can make that check itself:

Python · retry-safe version of the migration (from sqlalchemy import text)
def upgrade() -> None:
    with op.get_context().autocommit_block():
        valid = op.get_bind().execute(text(
            "SELECT indisvalid FROM pg_index"
            " WHERE indexrelid = to_regclass('ix_books_slug')"
        )).scalar()  # None: no index yet; False: a failed build left it
        if valid is False:
            op.execute("DROP INDEX CONCURRENTLY ix_books_slug")
        if valid is not True:
            op.create_index(
                'ix_books_slug', 'books', ['slug'],
                unique=False, postgresql_concurrently=True,
            )
Illustrative output · revision id differs per run; a timed-out build had left ix_books_slug INVALID
$ psql -d cic -c '\d books' | grep ix_books_slug
    "ix_books_slug" btree (slug) INVALID
$ alembic upgrade head
INFO  [alembic.runtime.migration] Running upgrade  -> bd0f2fc1d1d6, index books slug
$ psql -d cic -c '\d books' | grep ix_books_slug
    "ix_books_slug" btree (slug)

04. Expand, migrate, contract

Every measurement above says the same thing: a single migration that restructures a busy table in place has no safe window. The expand-migrate-contract pattern replaces that one big change with a series of small, dull ones, each compatible with the code deployed before and after it:

  1. Expand — a migration adds the new structure alongside the old: a new column, nullable or with a safe default. No data moves; old code ignores it. Deploy code that writes both the old and the new (dual-write).
  2. Migrate — the backfill copies old values into the new structure in batches, idempotently, while traffic continues. When reads are ready, switch the application to read the new column.
  3. Contract — first ship a release that reads and writes only the new structure (the dual-write stops), and wait until no older version is running anywhere; only then run the final migration that drops the old structure. In the opposite order, code that still dual-writes would fail on every write the moment the column disappears.

A rename, the worst case, becomes three migrations: add display_title (expand), copy title into it (migrate), drop title (contract). At no point does a query touch a column that is missing, and at no point is a lock held longer than a batch needs. The rule that makes it safe is N-1 compatibility: the schema works for the current release and the one before it, because during a rolling deploy both are live.

The pattern is not free — two extra migrations, a dual-write window and a backfill — so apply it where the table is large or the service must stay up. For a fifty-row table in a maintenance window, one well-reviewed ALTER TABLE is the better choice. The lab walks a full rename through all three phases, with old app versions exercising every intermediate schema.

05. Check your understanding

Practice check · 3 questions

Locks, defaults and the pattern

Three situations from the measurements above.

Q1. On PostgreSQL 17, ADD COLUMN flagged boolean DEFAULT false completes instantly on a 178 MiB table. Why?
Q2. A deploy's CREATE INDEX CONCURRENTLY ix_orders_ref was cancelled by lock_timeout. The rerun uses CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_orders_ref and prints CREATE INDEX. What state is the index in?
Q3. When is the contract step — dropping the old column — safe to run?
Practice only: not graded, not saved, not evidence.

06. Apply it

Reproduce the measurements on your own machine, then decide with data:

  1. Build a 2-million-row table with generate_series. Time a plain CREATE INDEX against CREATE INDEX CONCURRENTLY, and one INSERT during each build. Record CPU and RAM, and mark the numbers as trends for your hardware, not universal constants.
  2. Run the reader-blocking demo with lock_timeout values of 500 ms, 2 s and 10 s. At which value would you feel comfortable running the migration at peak traffic? Then leave a REPEATABLE READ transaction open on another table, start a concurrent index build, and find it waiting in pg_stat_activity.
  3. Pick a real table in a project you know and classify it: does it need expand-migrate-contract for its next change, or is it small or quiet enough for a single migration? Write the one-paragraph justification you would put in the pull request.

07. Review prompt

Without looking back: which lock does ALTER TABLE take, and why can a waiting ALTER stall queries that conflict with nothing? Explain the difference between DEFAULT false, DEFAULT now() and DEFAULT clock_timestamp() when adding a column, what CREATE INDEX CONCURRENTLY costs and forbids, and what a failed concurrent build leaves behind, how you detect it and how you recover. Finally, name the three phases of expand-migrate-contract and the compatibility rule that makes them safe.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check