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
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_timeoutmakes a statement give up if it cannot acquire a lock in time;statement_timeoutlimits total execution time.CREATE INDEX CONCURRENTLYbuilds 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.
| Operation | Typical risk | Safer approach |
|---|---|---|
| Add nullable column without default | Brief exclusive lock, no rewrite | Safe with lock_timeout |
| Add column with constant default | No table rewrite in modern versions; brief lock | Safe with lock_timeout; check your version |
| Add index | Blocks writes for the whole build | CREATE INDEX CONCURRENTLY |
| Add NOT NULL or CHECK constraint | Full table scan under lock | Add as NOT VALID, then VALIDATE separately |
| Add foreign key | Scans and locks both tables | Add as NOT VALID, then VALIDATE |
| Change column type | Often rewrites the table | New column, dual write, backfill, switch |
| Rename column or table | Breaks running application code | Add 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.
- Expand — add the new structure in a backward-compatible way. Old code ignores it.
- Dual write — deploy code that writes both the old and the new structure.
- Backfill — copy existing data into the new structure in small batches.
- Switch reads — read from the new structure, behind a flag, and verify results.
- 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.
- Expand: add
id_new bigint(nullable) and a trigger that copiesidintoid_newon insert and update. - Backfill: a job copies
idtoid_newfor existing rows in batches of 10,000, throttled on replication lag. - Build a unique index on
id_newwithCREATE INDEX CONCURRENTLY, then add a NOT NULL constraint via a validated CHECK. - In a short transaction with a strict lock_timeout, swap the primary key to the new index and rename the columns.
- 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.