How do you migrate a live database without downtime?
Most outages during migrations aren't failed migrations; they're migrations that held a lock while traffic queued behind them. Measured on a 5M-row table under load: one-step changes that stalled every request for 2-8 seconds, and the online versions that stalled them for a fraction of a second…
Short answer: the verdict, which the measurements below will earn: never do in one step what can be done in several small, reversible ones.
- For schema changes, use expand → migrate → contract: add the new structure alongside the old one, backfill it in small batches while the application writes to both, switch reads, and only then remove the old one.
- Use the online form of every operation:
CREATE INDEX CONCURRENTLY, constant defaults,NOT VALIDconstraints validated later. - Set
lock_timeouton every migration. The worst stalls come not from slow migrations but from a migration waiting for a lock while every query queues behind it.
For moving to a different database or service, the same idea scales up: copy the data with change data capture, compare old and new, move reads first and writes last, and keep the old path until you’re sure.
Here’s the case. A migration that ran in a blink on staging goes out to production, and for several long seconds every request on the site hangs. Sometimes the migration was huge; sometimes it was a single tiny ALTER. I find this one of the most satisfying corners of database work. The tools are all there, added to PostgreSQL over many releases; the craft is in sequencing them so that a big change becomes a series of small, boring, reversible steps.
The evidence below comes from database-tradeoffs-lab (make livemigrate): a 5-million-row PostgreSQL 17 table. While each change ran, 8 clients kept reading and updating rows; the slowest of their requests is how long a user would have waited.
Case file
The case A migration that was instant on staging hangs every request in production for seconds Suspects A huge migration, a slow ALTERCulprit The lock queue: a migration waiting for a lock, with every later query queued behind it The fix Expand → migrate → contract, the online form of every operation, lock_timeouton every migrationEvidence A 5-million-row PostgreSQL 17 table under 8 clients, database-tradeoffs-lab ( make livemigrate)
The evidence: schema changes, measured #
| Change | How | Change took | Slowest client request | Requests over 1 s |
|---|---|---|---|---|
int → bigint |
ALTER COLUMN … TYPE bigint |
7.6 s | 7.5 s | 8 (every client) |
int → bigint |
expand / backfill / validate / contract | 62 s | 165 ms | 0 |
| An index | CREATE INDEX |
2.1 s | 2.1 s | 8 |
| An index | CREATE INDEX CONCURRENTLY |
4.5 s | 378 ms | 0 |
A NOT NULL column |
DEFAULT clock_timestamp() (volatile) |
7.6 s | 7.5 s | 8 |
A NOT NULL column |
DEFAULT 'active' (constant) |
21 ms | 82 ms | 0 |
Any ALTER, while a 5 s report runs |
no lock_timeout |
5.2 s | 5.0 s | 8 |
Any ALTER, while a 5 s report runs |
lock_timeout = '200ms' |
gave up after 200 ms | 203 ms | 0 |
Diagram source
xychart-beta
title "Client requests over 1 s during each change (of 8 clients)"
x-axis ["ALTER TYPE", "Expand/contract", "CREATE INDEX", "CONCURRENTLY", "Volatile default", "Constant default", "No lock_timeout", "lock_timeout"]
y-axis "requests over 1 s"
bar [8 , 0 , 8 , 0 , 8 , 0 , 8 , 0]
The pattern: the blocking form stalls every client for about as long as the operation runs, and operations grow with the table. The online forms take longer in total, and nobody notices. That’s the whole trick, and it’s a generous one: trade a longer migration for a shorter wait.
The expand/contract pattern #
The case: a column is running out of range (an int ID approaching 2.1 billion), or needs a different type.
The obvious move, ALTER COLUMN … TYPE bigint, rewrites the whole table under an exclusive lock: 7.5 seconds of every request waiting, at 5 million rows. At 500 million it would be at least 100 times longer, over 12 minutes if it scaled linearly, and worse once the table no longer fits in memory. Instead:
- Expand. Add the new column (
owner_id_new bigint), which is instant. Keep it in sync for new writes, with a trigger or with application code that writes both. - Backfill in batches.
UPDATE … SET owner_id_new = owner_id WHERE id BETWEEN $1 AND $2, 10,000 rows at a time, each batch its own short transaction. Pause between batches if replicas fall behind. - Prove it’s complete without a long lock. This is the clever step, and my favourite.
ADD CONSTRAINT … CHECK (owner_id_new IS NOT NULL) NOT VALIDis instant;VALIDATE CONSTRAINTthen scans the table while allowing reads and writes. - Switch. Deploy code that reads the new column.
- Contract. In one short transaction, with
lock_timeout: drop the trigger, drop the old column, rename the new one, andSET NOT NULL. That last step reuses the validated check (PostgreSQL 12+) instead of rescanning.
Diagram source
flowchart LR
A["Expand: add new column, dual-write"] --> B["Backfill in small batches"]
B --> C["NOT VALID check, then VALIDATE"]
C --> D["Switch reads to the new column"]
D --> E["Contract: drop old, rename, SET NOT NULL"]
A false lead I followed myself: my first version skipped step 3, and the final SET NOT NULL scanned all 5 million rows under an exclusive lock: a 3.2-second stall at the very end of an otherwise careful migration. With the validated constraint, the worst request was 165 ms. Every “online” recipe has one step like that; find it before production does.
The same pattern covers renaming a column (add, dual-write, backfill, switch reads, drop), splitting a table, and changing what a column means. It needs two or three deploys, because the application must work with both old and new structures in between. That’s the real cost, and it’s worth it.
Indexes and defaults: use the online form #
CREATE INDEXblocks writes for its whole run: 2.1 seconds here, much longer on a big table.CREATE INDEX CONCURRENTLYtook twice as long, and the slowest request was 378 ms. It can’t run in a transaction, and if it fails it leaves anINVALIDindex that you drop and retry. Most migration tools need a flag to run it outside their transaction.- Adding a
NOT NULLcolumn with a constant default is instant in PostgreSQL 11+. The default is stored once in the catalogue, not written to every row, so the cost doesn’t grow with the table. That’s a lovely piece of design. A volatile default (clock_timestamp(),gen_random_uuid()) can’t be stored once, so PostgreSQL rewrites the table: a 7.5-second stall. Add the column with a constant (or nullable) default, then backfill in batches. - Foreign keys and check constraints: add them
NOT VALID, thenVALIDATE CONSTRAINTseparately, for the same reason as above.
The real culprit: the lock queue #
This is the one that surprises people most, and once you’ve seen it you never forget it.
The case: a tiny migration takes the site down. ALTER TABLE … ADD COLUMN flag boolean takes milliseconds of work, but it needs an exclusive lock on the table. If a report or a forgotten transaction (long-transaction post) is reading the table, the ALTER waits, and every query that arrives after the ALTER waits behind it, even plain reads, because locks are granted in order. The migration isn’t slow at all. It’s standing in the doorway.
With a 5-second report running, the trivial ALTER stalled every client for 5.0 seconds. With lock_timeout = '200ms', it gave up after 200 ms, traffic carried on, and the migration could be retried later.
SET lock_timeout = '2s'; -- in every migration; retry with backoff if it fails
SET statement_timeout = '15min'; -- and a ceiling on how long any step may run
Most migration tools let you set these per migration. Make it the default, not something you remember during an incident.
A bigger case: moving to a different database or service #
The case: replacing the system itself: a new database engine, a new service, a rewrite (the refactor or rewrite post covers whether to). The schema-change ideas scale up:
| Strategy | How | Good for | Watch out for |
|---|---|---|---|
| Dual writes from the application | Write to old and new; read from old; switch reads later | Small, simple data | The dual-write bug: one write succeeds, the other doesn’t. Needs reconciliation (consistency post) |
| Change data capture (CDC) + backfill | Bulk-copy a snapshot; stream every later change from the old database’s log (e.g. Debezium reading PostgreSQL’s WAL) into the new one | Large data, different engines | Schema mapping; ordering per key; how far behind the stream is |
| Shadow reads | Serve from the old system, also query the new one, compare, log differences | Proving the new system gives the same answers | Extra load; comparing fairly (timing, ordering) |
| Blue/green cutover | Two full environments; switch traffic at the load balancer or DNS | Stateless tiers; a final cutover | The database usually can’t be “blue/green” without CDC underneath |
A typical sequence:
- backfill plus CDC;
- shadow reads until differences are zero;
- move reads gradually (1%, 10%, 50%, 100%);
- move writes in one short, rehearsed step, with the old system still receiving changes in reverse so you can roll back;
- keep the old system until you’re sure; only then decommission it.
At Jio News, I led the backend re-architecture of a service with about 5 million active users in more than 12 languages, migrating legacy services from Go to Node.js (TypeScript) within two months, while also designing the new microservices for real-time publishing and personalised feeds at sub-200 ms latency under peak load. A move like that only stays invisible to users if it follows the sequence above: build the new path next to the old one, check that both give the same answers, shift traffic in steps you can reverse, and retire the old code only once the new path has carried real peak traffic.
Remember this
- Never do in one step what can be done in several small, reversible ones.
- Use the online form: CONCURRENTLY, constant defaults, NOT VALID then VALIDATE.
- Set lock_timeout on every migration: the lock queue is the real culprit.
Case closed: what I’d do by default #
- Expand → migrate → contract for every non-trivial schema change, across separate deploys.
- The online form of every operation:
CONCURRENTLY, constant defaults,NOT VALIDthenVALIDATE. lock_timeouton every migration, retried with backoff, plus astatement_timeout.- Backfills in small batches, throttled by replica lag, and resumable.
- Rehearse on a production-sized copy. Every number above grows with the table. A migration that took 2 seconds in staging can take an hour in production.
- For system moves: CDC, shadow reads, gradual read cutover, a short write cutover with a reverse path, and the old system kept until you’re sure.
Done well, the best migration is the one nobody outside the team ever hears about. There’s a particular pride in that: a table rebuilt, a system replaced, and every request along the way answered as if nothing had happened.
Measured Nov 2026 on PostgreSQL 17.11 in Docker on a laptop (Intel i7-8550U): a 5M-row table, 8 clients reading and updating throughout, two runs (the first, without the validated check, is described above). Code and full results: database-tradeoffs-lab/11-live-migrations.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.