Skip to content

    System Design

    Data Modeling, Schema Evolution and Zero-Downtime Migrations

    Learn expand and contract, which PostgreSQL ALTER TABLE forms rewrite a table or take heavy locks, and run a lab that migrates a column without downtime.

    By Published 12 min read

    Share

    Standard lessonintermediatePostgreSQL labBackend System Design

    Before this: Normalization (1NF to BCNF) and Denormalization

    What you'll learn: By the end of this lesson you will be able to treat a database schema as a contract shared by several versions of your code, split a risky change into expand, migrate and contract steps, say which PostgreSQL ALTER TABLE forms rewrite the table or take an ACCESS EXCLUSIVE lock and which do not, backfill a column in batches, add a NOT NULL rule without a long lock, and run a lab on an in-process PostgreSQL that prints the lock and rewrite behaviour of each statement.

    Picture a supermarket that cannot close while you rearrange its shelves. You do not clear an aisle and hope. You put the new shelf up first, carry stock across in small trips, point shoppers to the new shelf, and take the old one away only when nobody is walking to it. Each step leaves the shop open and usable.

    A live database migration is the same job. The table is the aisle, the application servers are the shoppers, and a deploy takes minutes during which old and new code run side by side. Normalization, B-tree indexes, ACID and locking are separate lessons and appear here only as far as a migration needs them.

    Verified on 2026-12-01 against the PostgreSQL 18 manual, the PGlite documentation and Martin Fowler's page on parallel change. The lab output comes from the PostgreSQL 19.0 build inside PGlite 0.6.1; the course targets PostgreSQL 18, so each behaviour below is stated from the 18 pages and the lab only confirms it on the build it ran on.

    The core idea

    A schema change is safe on a live system when every step works with both the code that ran before it and the code that runs after it, and when no step holds a heavy lock for long. Expand and contract gives you the first property. Knowing what each statement costs gives you the second.

    Three labelled illustrations run through the lesson: a minimal example (the lab's column swap), a realistic example (ShopStream's orders table at target scale) and a failure example (a migration that waits for a lock).

    The schema is a contract with more than one reader

    A table's columns are an interface. The application reads and writes them, reporting jobs query them, and a migration changes them. During a rolling deploy, versions 1 and 2 of the service both run. A change that is correct for version 2 alone breaks version 1 the moment it lands.

    So the hard changes are the ones that change meaning rather than add something. A nullable column is invisible to code that does not know about it. Renaming a column, changing a type, splitting a column or adding a NOT NULL rule changes what old code may do. Prefer additive shapes and keep a column's meaning stable.

    Realistic example (illustrative). ShopStream's target is 500,000 orders per day, about 182 million rows a year in one orders table (500,000 times 365). At that size a statement that touches every row, or waits for a lock while traffic piles up, is an incident. See the ShopStream data model stage and databases basics.

    Expand, migrate, contract

    Martin Fowler describes "parallel change, also known as expand and contract" as a pattern "to implement backward-incompatible changes". Its phases are expand ("you augment the interface to support both the old and the new versions"), migrate ("you update all clients using the old version to the new version") and contract ("remove the old version"). It lowers risk by letting you migrate clients and test the new version incrementally. The same shape at system scale is the strangler fig migration.

    For a database the phases map onto five concrete steps.

    stateDiagram-v2 accTitle: Expand, migrate and contract for one column accDescr: The schema moves from the old column only, to both columns with a sync mechanism after the expand step, to both columns filled after the backfill, to a new column with a NOT NULL rule once the constraint is validated, and finally to the new column only after the contract step removes the old column. [*] --> OldOnly OldOnly: Old column only Both: Both columns, old writers still work Filled: Both columns filled for every row Enforced: New column enforced as NOT NULL NewOnly: New column only OldOnly --> Both: expand Both --> Filled: backfill in batches Filled --> Enforced: validate, then SET NOT NULL Enforced --> NewOnly: contract after the last old reader is gone NewOnly --> [*]

    Figure 1. The five states of a column migration. How to read this: each arrow is one deploy or job, and every state can run for days. Only the last arrow is hard to undo.

    The steps, in the order the lab runs them:

    1. Expand. Add the new column as nullable with no default, and add a way to keep it correct when old code writes only the old column (a trigger, or dual writes in the new application version).
    2. Migrate, part one. Deploy the application version that writes both columns.
    3. Migrate, part two. Backfill existing rows in small batches.
    4. Tighten. Add the rule you wanted (NOT NULL, a foreign key, a unique index) in the cheap, non-blocking form.
    5. Contract. Once every reader and writer uses the new column and rollback is no longer wanted, drop the old column and the sync trigger.
    A column migration in flight: old and new writers share one tableApp version 1 to Sync trigger (old write); Sync trigger to orders table (both columns); App version 2 to orders table (both columns); Backfill job to orders table (fill old rows)App version 1: writes old columnApp version 1writes old columnSync trigger: copies old to newSync triggercopies old to neworders table: old and new columnsorders tableold and newcolumnsApp version 2: writes bothApp version 2writes bothBackfill job: batches of rowsBackfill jobbatches of rowsold writeboth columnsboth columnsfill old rows

    Figure 2. The middle of a migration. How to read this: nothing is switched off. Old writers go through the trigger, new writers write both columns, and the backfill fills the rows nobody has touched since the expand step.

    sequenceDiagram accTitle: Deploy order for a column migration accDescr: The release adds the new column and a sync trigger first, while version 1 of the app keeps working. It then deploys version 2 which writes both columns, a backfill job fills the old rows, the constraint is validated and made NOT NULL, a later version reads only the new column, and the old column is dropped last. participant R as Release participant D as Database participant A1 as App v1 participant A2 as App v2 participant B as Backfill job R->>D: expand, add column and sync trigger Note over A1,D: version 1 keeps working R->>A2: deploy the version that writes both columns B->>D: fill old rows in batches R->>D: validate constraint, then SET NOT NULL R->>A2: deploy the version that reads only the new column R->>D: contract, drop trigger and old column

    Figure 3. The order of the deploys. How to read this: time runs downward. Schema first, then writers, then readers, removal last, so no running version meets a schema it cannot use.

    What each statement costs

    Two things decide whether a statement is safe on a busy table: whether it rewrites the table, and which lock it holds and for how long.

    Rewrite or metadata only

    With a non-volatile DEFAULT, ADD COLUMN stores the evaluated default "in the table's metadata", which makes it "very fast even on large tables"; with no default the column is NULL and also needs no rewrite. A volatile default (the manual's example is clock_timestamp()), a stored generated column, an identity column or a constrained domain type "will cause the entire table and its indexes to be rewritten". A type change "will normally cause the entire table and its indexes to be rewritten", except when the old type is binary coercible to the new one and USING does not change the contents. DROP COLUMN "simply makes it invisible to SQL operations" and does not reclaim the space at once. RENAME has "no effect on the stored data".

    Which lock

    An ALTER TABLE takes ACCESS EXCLUSIVE "unless explicitly noted", and the strictest lock wins when subcommands are combined. ACCESS EXCLUSIVE "conflicts with locks of all modes": "only an ACCESS EXCLUSIVE lock blocks a SELECT". The exceptions that matter:

    Statement Lock named in the manual Note
    ALTER TABLE ... VALIDATE CONSTRAINT SHARE UPDATE EXCLUSIVE Scans, but does not lock out updates
    ALTER TABLE ... ADD FOREIGN KEY SHARE ROW EXCLUSIVE, on both tables Not the default ACCESS EXCLUSIVE
    CREATE INDEX SHARE Blocks writes, not reads
    CREATE INDEX CONCURRENTLY SHARE UPDATE EXCLUSIVE Two scans; not allowed in a transaction block

    The cheap path is ADD CONSTRAINT ... NOT VALID. It skips "this potentially-lengthy scan"; the constraint is enforced for new writes, but the database "will not assume that the constraint holds for all rows" until VALIDATE CONSTRAINT runs. SET NOT NULL skips its scan "if a valid CHECK constraint exists" that proves no NULL can exist. So: add a NOT VALID check, validate it under the lighter lock, SET NOT NULL, then drop the check.

    flowchart TD accTitle: Is this statement safe on a hot table accDescr: A decision flow. A statement that needs to scan or rewrite the whole table under an ACCESS EXCLUSIVE lock is unsafe as written. Split it into a NOT VALID constraint and a validation, or into an expand and contract sequence. A statement that is metadata only is safe if it cannot wait long for its lock, so run it with a lock timeout. A["Statement to run"] --> B{"Rewrites the table or
    scans it under ACCESS EXCLUSIVE?"} B -->|yes| C{"Can it be split?"} C -->|"constraint"| D["NOT VALID, then VALIDATE CONSTRAINT"] C -->|"type or meaning change"| E["Expand and contract with a backfill"] B -->|no| F["Metadata only:
    safe if the lock is quick to get"] F --> G["Run with a short lock_timeout
    and retry"]

    Figure 4. A first check before any migration statement. How to read this: ask whether the statement touches every row while holding a strong lock. If so, it is split. If not, the remaining risk is waiting for the lock, which the next section covers.

    Waiting for a lock is part of the cost

    A statement that needs ACCESS EXCLUSIVE must wait for every transaction already holding a conflicting lock, and a plain SELECT holds ACCESS SHARE until its transaction ends. The manual says a transaction seeking a table-level lock "will wait indefinitely for conflicting locks to be released".

    lock_timeout is the documented guard: it aborts "any statement that waits longer than the specified amount of time while attempting to acquire a lock". Its default is zero (disabled), and the manual says setting it in postgresql.conf "is not recommended because it would affect all sessions". A migration sets it for its own transaction (SET LOCAL lock_timeout = '2s') and retries on failure. In pg_locks, granted is false for a lock that is "awaited", which is how you find a stuck migration.

    The pages cited here do not say how a waiting lock request affects queries that arrive after it, so this lesson claims nothing either way. Test that on your own version and workload.

    Backfill in batches

    A single UPDATE of 182 million rows is one long transaction. The manual says an UPDATE "does not immediately remove the old version of the row" and that VACUUM reclaims outdated versions, so a one-statement backfill leaves a dead version per row at once. Short batches let vacuum keep up and keep each statement's locks brief. The loop updates a limited set of rows where the new column is still NULL until none are left; the lab uses batches of 1,000 on 5,000 rows (illustrative).

    Build it: a column migration on PGlite

    Setup. The lab is examples/postgres-labs/labs/zero-downtime-migration/. It runs on PGlite, whose documentation says it has "a single exclusive connection to the database". That is the lab's limit, stated plainly:

    • It shows which locks a statement takes (read from pg_locks inside its own transaction), never a second session waiting. A lock wait, a lock queue and lock_timeout firing are not shown.
    • It cannot show whether SET NOT NULL skipped its scan; that rests on the manual.
    • Tables are tiny and illustrative, so no timing is printed.
    cd examples/postgres-labs
    npm install
    node --test labs/zero-downtime-migration/test.mjs
    node labs/zero-downtime-migration/run.mjs

    A rewrite is detected by a changed relfilenode, documented as the "name of the on-disk file of this relation"; the page does not say what a rewrite does to it, so this is an observation on this build, backed by the ALTER TABLE text for each case.

    Expected output, captured from a real run (section 1 of the demo, PostgreSQL 19.0 in PGlite 0.6.1):

    ADD COLUMN contact_phone text                              rewritten: no
    ADD COLUMN source text DEFAULT 'web'                       rewritten: no
    ADD COLUMN stamp timestamptz DEFAULT clock_timestamp()     rewritten: yes
    ALTER COLUMN shopper_phone TYPE varchar                    rewritten: no
    ALTER COLUMN total_cents TYPE bigint                       rewritten: yes
    RENAME COLUMN shopper_phone TO phone_old                   rewritten: no
    DROP COLUMN source                                         rewritten: no

    The volatile default and the bigint change rewrite the table; the nullable column, the constant default, the varchar change (consistent with the manual's exception for types that are binary coercible), the rename and the drop do not.

    Expected output, captured from a real run (section 2, the locks each statement takes, tables only):

    SELECT count(*) FROM orders
        orders: AccessShareLock
    INSERT INTO orders VALUES (9001, 1, '555-9001', 700)
        orders: RowExclusiveLock
    ALTER TABLE orders ADD COLUMN contact_phone text
        orders: AccessExclusiveLock
    ALTER TABLE orders ADD CONSTRAINT c CHECK (total_cents > 0)
        orders: AccessExclusiveLock
    ALTER TABLE orders ADD CONSTRAINT c CHECK (total_cents > 0) NOT VALID
        orders: AccessExclusiveLock
    ALTER TABLE orders VALIDATE CONSTRAINT c (after NOT VALID)
        orders: ShareUpdateExclusiveLock
    ALTER TABLE orders ADD FOREIGN KEY (shopper_id) REFERENCES shoppers
        orders: AccessShareLock, orders: ShareRowExclusiveLock, shoppers: AccessShareLock, shoppers: RowShareLock, shoppers: ShareRowExclusiveLock
    CREATE INDEX ON orders (shopper_id)
        orders: ShareLock
    CREATE INDEX CONCURRENTLY ON orders (shopper_id)
        error: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
    ALTER TABLE orders ALTER COLUMN shopper_phone SET NOT NULL
        orders: AccessExclusiveLock
    ALTER TABLE orders ALTER COLUMN total_cents TYPE bigint
        orders: AccessExclusiveLock, orders: ShareLock
    ALTER TABLE orders RENAME COLUMN shopper_phone TO phone_old
        orders: AccessExclusiveLock

    Each documented row matches the manual: plain ALTER TABLE forms take ACCESS EXCLUSIVE, VALIDATE CONSTRAINT takes SHARE UPDATE EXCLUSIVE, the foreign key takes SHARE ROW EXCLUSIVE on both tables, CREATE INDEX takes SHARE. The extra SHARE lock on the bigint change and the ACCESS SHARE and ROW SHARE rows on the foreign key are the lab's own observations. ADD CONSTRAINT ... NOT VALID still takes ACCESS EXCLUSIVE; it is the cheap form because no scan runs while the lock is held. CREATE INDEX CONCURRENTLY is refused inside a transaction block, which matters if your migration tool wraps each file in one.

    Expected output, captured from a real run (section 3, the migration itself):

    -- expand: add the nullable column (no default, so no rewrite) and a trigger that keeps old writers working
    orders with contact_phone NULL: 5000
    old writer inserts order 9001 with only shopper_phone: contact_phone = 555-9001
    -- migrate: backfill in small batches, each its own transaction
    batch 1: updated 1000 rows, still NULL: 4000
    batch 2: updated 1000 rows, still NULL: 3000
    SET NOT NULL attempted after batch 2: column "contact_phone" of relation "orders" contains null values
    batch 3: updated 1000 rows, still NULL: 2000
    batch 4: updated 1000 rows, still NULL: 1000
    batch 5: updated 1000 rows, still NULL: 0
    rows where contact_phone differs from shopper_phone: 0
    -- tighten: a NOT VALID check, validate it, then SET NOT NULL
    after ADD ... NOT VALID: convalidated = false
    after VALIDATE CONSTRAINT: convalidated = true
    contact_phone NOT NULL: true
    -- index without blocking writes (outside a transaction block)
    orders_contact_phone_idx: indisvalid = true, indisready = true
    -- contract: the app now reads and writes only contact_phone; remove the trigger and the old column
    visible columns: id, shopper_id, total_cents, contact_phone
    dropped columns still in the catalog (marked attisdropped): 1
    orders: 5001 rows, contact_phone NULL: 0

    The trigger fills contact_phone for an old-style insert, the backfill runs in five batches, and the early SET NOT NULL, attempted with 3,000 rows still NULL, fails with the engine's own message. Afterwards the columns agree on every row, the NOT VALID check turns valid, the column is NOT NULL, the index is valid, and the contract step leaves one dropped column in the catalog.

    Break it. In lab.mjs, move the SET NOT NULL before the first backfill batch and read the error. Restore the file and re-run the tests.

    Trade-offs: ways to change a live schema

    Approach Gain Cost Wrong when
    Maintenance window, one big ALTER Simplest; one step Downtime for the duration, which grows with table size You have a real SLO or a global user base
    In-place expand and contract No downtime; reversible until contract Several deploys, sync logic, a backfill to watch The change is trivial
    Copy to a new table, then swap names Rewrite happens off to the side Keep the copy in sync; a short lock for the swap The table has many dependents

    In practice: ShopStream adds a delivery contact phone

    This is a realistic scenario, not a case history. Every number is illustrative.

    The situation

    Couriers need to call whoever will be at the door, often not the shopper on the account. Product asks for a per-order contact phone, always present on new orders, in the largest and busiest table (about 182 million rows a year).

    Starting architecture

    Several app servers share one primary orders table, and a deploy replaces them gradually. A nightly reporting job reads orders in a long transaction.

    Options considered

    • One statement. ADD COLUMN ... NOT NULL fails on a table with rows unless a default is supplied, and a constant default would label every old order with a made-up contact.
    • Maintenance window. Safe but visible to every shopper.
    • Expand and contract. The lab's five steps, with the old phone copied as the starting value for old orders.

    The decision

    Expand and contract: a 2-second lock_timeout with retry on the expand step, a new application version that writes both columns, an off-peak batched backfill, then the NOT VALID check, SET NOT NULL and a concurrent index build outside a transaction. Contract comes one release later, after the rollback window closes.

    Rollout and verification

    Each step has a check before the next: after the backfill, zero rows where the new column is NULL or differs from the old one (the lab's two counts); after tightening, convalidated is true and the column is NOT NULL; after the index, it is valid and ready. Contract waits until no deployed version or job reads the old column.

    The 2 a.m. failure

    The deploy stalls on step one. The ALTER TABLE is waiting behind the reporting job's long transaction, which holds ACCESS SHARE on orders, and with no lock_timeout it will wait indefinitely.

    Checks: look in pg_locks for a lock on orders with granted false, and find the process holding a conflicting one. Mitigation: cancel the ALTER, not the report, then retry with a short lock_timeout in a quiet window; also check whether other queries are queuing behind it, since the sources used here do not say. Lasting fix: a migration runner that always sets lock_timeout and retries, and reports that do not hold one transaction open for hours.

    Architect's notes

    • Keep DDL transactions tiny. Run the backfill in its own transactions, apart from any ALTER.
    • Make contract a separate, later release. It is the only step you cannot undo from SQL.
    • Check the version. Rewrite and lock behaviour is documented per release.

    Common mistakes

    • Adding a NOT NULL column with no plan for old rows.
    • Using a volatile default on a big table.
    • Putting CREATE INDEX CONCURRENTLY in a transaction block. It fails, as the lab shows. A failed concurrent build can also leave an invalid index that still costs write overhead.
    • Backfilling in one statement.
    • Running with no lock_timeout. The statement can wait indefinitely.
    • Dropping the old column in the same release that stops using it. There is then no rollback.

    Key takeaways

    • A schema is a contract between every version of the code that is running, not just the newest.
    • Expand, migrate, contract turns one risky change into several safe ones.
    • Know two things per statement: does it rewrite, and which lock does it hold.
    • NOT VALID plus VALIDATE CONSTRAINT plus SET NOT NULL avoids a long ACCESS EXCLUSIVE scan.
    • Backfill in short batches; set lock_timeout for DDL.
    • Contract last, in its own release.

    The other side of this topic is the client. When a field changes meaning, the client must keep working too, which is the problem in API contract evolution for clients.

    Practice exercises

    Exercise 1 (20 min). For each, say whether the manual makes it metadata-only and which lock it takes: a nullable column, a constant default, a rename, integer to bigint.

    Exercise 2 (45 min). Run the lab. Change the batch size to 500 and read how the section 3 output changes. Restore it.

    Exercise 3 (1 hour). Write the expand and contract plan to constrain ShopStream's free-text orders.status, with the checks between steps.

    Exercise 4 (2 hours). Extend the lab with a foreign key added NOT VALID then validated, and compare its locks with the plain form.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments