LumenForgee

Zero-downtime schema migrations on busy PostgreSQL tables

Most migration incidents are not caused by slow migrations. They are caused by fast migrations that wait for a lock — and while they wait, every query behind them waits too. Understanding that queue is the first step to schema changes that never need a maintenance window.

Contents
  1. The lock queue problem
  2. Which operations are risky
  3. Expand and contract
  4. Backfills that do not hurt
  5. Guardrails in CI
  6. Worked example: changing an integer ID to bigint
  7. Common pitfalls
  8. FAQ
  9. Checklist
  10. Primary sources

Key facts

  • In PostgreSQL, many ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which conflicts with every other lock on the table, including plain SELECT.
  • A DDL statement waiting for a lock blocks later queries that need conflicting locks, so one long transaction plus one migration can stall a table.
  • lock_timeout makes a statement give up if it cannot acquire a lock in time; statement_timeout limits total execution time.
  • CREATE INDEX CONCURRENTLY builds an index without blocking writes, but cannot run inside a transaction block.

The lock queue problem

PostgreSQL grants table locks in order. A long analytical query holds an ACCESS SHARE lock on orders for several minutes. A migration then asks for an ACCESS EXCLUSIVE lock to add a column. It cannot get it while the query runs, so it waits. Every new query on orders — even simple reads — now also waits, because its lock would conflict with the migration's pending request.

From the application's point of view the table has disappeared. Connection pools fill with waiting queries, request timeouts fire, retries add load, and the incident looks like a database outage. When the long query finishes, the migration runs in milliseconds and everything recovers — which makes the cause easy to miss in a post-mortem.

The first defence is therefore not a smarter migration but a shorter wait. Setting lock_timeout to a few seconds for migration sessions means the migration fails cleanly if it cannot get its lock quickly. A failed migration can be retried; a stalled table cannot be undone.

Which operations are risky

The exact behaviour depends on the PostgreSQL version and the operation, so check the documentation for the version you run. Broadly, operations fall into three groups.

Common schema changes and their risk profile (PostgreSQL)
OperationTypical riskSafer approach
Add nullable column without defaultBrief exclusive lock, no rewriteSafe with lock_timeout
Add column with constant defaultNo table rewrite in modern versions; brief lockSafe with lock_timeout; check your version
Add indexBlocks writes for the whole buildCREATE INDEX CONCURRENTLY
Add NOT NULL or CHECK constraintFull table scan under lockAdd as NOT VALID, then VALIDATE separately
Add foreign keyScans and locks both tablesAdd as NOT VALID, then VALIDATE
Change column typeOften rewrites the tableNew column, dual write, backfill, switch
Rename column or tableBreaks running application codeAdd new name, migrate code, drop old later

The pattern behind the safer approaches is the same: split one dangerous step into several cheap ones, and move expensive work — scanning, rewriting, backfilling — outside the moment that holds a strong lock.

Expand and contract

Schema changes and code deployments do not happen at the same instant. During a rolling deployment, old and new application versions run side by side. A schema change is only safe if both versions can work with the database at every moment. Expand/contract makes that explicit.

  1. Expand — add the new structure in a backward-compatible way. Old code ignores it.
  2. Dual write — deploy code that writes both the old and the new structure.
  3. Backfill — copy existing data into the new structure in small batches.
  4. Switch reads — read from the new structure, behind a flag, and verify results.
  5. Contract — once nothing reads the old structure and rollback is no longer needed, remove it.

Each phase is a separate deployment with its own rollback. The cost is time: a rename that a single statement could do now takes several releases. The benefit is that no single step can take the system down, and any step can be paused when something unexpected appears.

Backfills that do not hurt

A single UPDATE orders SET new_col = old_col on a large table holds row locks for the whole run, generates a large amount of WAL, bloats the table and can delay replication. Backfills should instead be jobs: process a bounded batch by primary key range, commit, pause, record progress, repeat.

  • Choose batch sizes so each transaction finishes in well under a second.
  • Throttle based on database health — replication lag, CPU, p95 query latency — not only on a fixed sleep.
  • Make the job idempotent and resumable from the last committed key.
  • Run it during normal traffic and watch the same dashboards you would watch during an incident.

Guardrails in CI

Process is easier to follow when the tooling enforces it. Migration linters can flag statements that take strong locks, rewrite tables or add constraints without NOT VALID. A small wrapper can set lock_timeout and statement_timeout for every migration session automatically, and refuse to run CREATE INDEX CONCURRENTLY inside a transaction.

Review templates help too. A migration pull request should state which expand/contract phase it belongs to, which application version it is compatible with and how it is rolled back. Those three answers catch most mistakes before they reach production.

Worked example: changing an integer ID to bigint

An events table has an integer primary key that will run out of values within months. Altering the column type in place would rewrite a table of several hundred gigabytes under an exclusive lock.

  1. Expand: add id_new bigint (nullable) and a trigger that copies id into id_new on insert and update.
  2. Backfill: a job copies id to id_new for existing rows in batches of 10,000, throttled on replication lag.
  3. Build a unique index on id_new with CREATE INDEX CONCURRENTLY, then add a NOT NULL constraint via a validated CHECK.
  4. In a short transaction with a strict lock_timeout, swap the primary key to the new index and rename the columns.
  5. Update foreign keys referencing the table using the same NOT VALID / VALIDATE pattern, then drop the old column in a later release.

The only step that takes an exclusive lock is the final swap, which completes in milliseconds — and if it cannot get the lock within the timeout, it simply fails and is retried later.

Common pitfalls

  • Running migrations without lock_timeout, so a waiting statement stalls the whole table.
  • Building indexes without CONCURRENTLY on large, write-heavy tables.
  • Backfilling with one large UPDATE instead of batched, resumable jobs.
  • Dropping or renaming columns in the same release that stops using them.
  • Assuming behaviour from a blog post instead of checking the docs for your PostgreSQL version.
  • Ignoring long-running transactions, which turn harmless DDL into an outage.

FAQ

Can an ORM generate safe migrations automatically?

ORMs generate correct schema changes, not necessarily safe ones. Treat generated migrations as a draft and review them against the lock behaviour of each statement.

Is a maintenance window still useful?

For rare, very large changes it can be the pragmatic choice. The goal is that routine changes never need one.

How do we find long-running transactions before a migration?

Query pg_stat_activity for transactions older than a threshold, and set idle_in_transaction_session_timeout so abandoned sessions are closed automatically.

Checklist

  • lock_timeout and statement_timeout set for every migration session.
  • Indexes built concurrently; constraints added as NOT VALID and validated separately.
  • Changes split into expand, dual-write, backfill, switch and contract phases.
  • Backfills batched, throttled on health metrics and resumable.
  • CI linting for dangerous DDL and a migration review template.
  • Long-running and idle transactions monitored and limited.

Primary sources

  1. PostgreSQL documentation — Explicit Locking
  2. PostgreSQL documentation — ALTER TABLE
  3. PostgreSQL documentation — CREATE INDEX (building indexes concurrently)
  4. PostgreSQL documentation — Client Connection Defaults (lock_timeout, statement_timeout)
  5. Martin Fowler — Parallel Change

Related research