TL;DR
Expand/contract, dual-write, batched backfill and shadow-table cutovers — how to change a production schema without downtime, and the rollback that works.
Most database migrations are not hard. The hard part is that the old code and the new code have to run against the same database at the same time, while users are writing to it. A migration that works in staging and takes production down for forty minutes usually failed on one of three things: a lock that blocked every query, a rewrite that copied a table nobody realised was that big, or a deploy order that left the old code staring at a schema it did not understand.
The short version: never change a schema and the code that reads it in the same deploy. Expand the schema first, in a way old code tolerates; teach the new code to write both shapes; backfill the old rows in small batches; then, in a later release, remove the old shape. That sequence — expand, migrate, contract — is the whole discipline, and the rest of this guide is the machinery that makes each step safe: knowing which operations your engine does cheaply, how to copy a table that is too big to lock, and what the cutover and rollback actually look like.
Why schema changes take production down
Three failure modes account for nearly every migration outage, and they are worth naming precisely because they look identical in the incident channel — "the database is slow" — while needing completely different fixes.
Locks. Most ALTER TABLE statements take an ACCESS EXCLUSIVE lock, which blocks every other query on the table, including SELECT. The lock itself is usually brief. The outage happens when the statement cannot acquire the lock: it queues behind a long-running transaction, and then every new query queues behind it. The table is not slow; it is fenced off, and the queue grows until the application gives up. The defence is not a faster statement, it is a lock timeout — lock_timeout in PostgreSQL — so the migration fails fast instead of wedging the table.
Rewrites. Some operations copy every row. Changing a column type, adding a column with a volatile default, or rebuilding a table on MySQL rewrites the whole table and its indexes, holding that exclusive lock for the duration. On a table with tens of millions of rows, that is minutes to hours, not milliseconds. The defence is knowing, before you run it, whether your operation rewrites — and reaching for a shadow-table tool when it does.
Deploy overlap. During a rolling deploy, old and new application versions run side by side against one database. If the new code writes a column the old code does not know about, that is fine. If the new code removes a column the old code still reads, or renames one the old code still queries, the old pods start erroring the moment the migration lands. The defence is ordering: the schema change must be compatible with the code that is currently running, and the code change must be compatible with the schema that is currently deployed. Every strategy in this guide is a way of keeping those two statements true at every point in the sequence.
Expand and contract: the pattern everything else hangs on
The core pattern has a name in Martin Fowler's catalogue — parallel change, also known as expand and contract — and it breaks a breaking change into three phases that never require every consumer to switch at the same instant: expand the interface to support both shapes, migrate the callers across, then contract the interface by removing the old shape. Applied to a database, it is the difference between a rename that takes the site down and a rename that nobody notices.
Take a concrete case: renaming amount, a float holding dollars, to amount_cents, an integer holding cents, because the float has been producing rounding bugs. The naive version is one ALTER TABLE ... RENAME COLUMN in the same deploy as the code change — and every old pod still querying amount breaks the moment the rename lands. The expand/contract version is five small steps spread across three releases:
-- 1. Expand: add the new column. Nullable, so old code ignores it. -- On PostgreSQL 11+ this is a metadata-only change: no rewrite. ALTER TABLE orders ADD COLUMN amount_cents integer; -- 2. Deploy v2: write both columns, read the new one with fallback. -- 3. Backfill old rows in batches (next section). -- 4. Deploy v3: read and write only amount_cents. -- 5. Contract, in a later release, once nothing reads amount: ALTER TABLE orders DROP COLUMN amount;
The dual-write in step 2 is the part teams skip, and it is the part that makes the pattern work. The new code writes both columns on every insert and update, and reads the new column, falling back to the old one when it is empty:
def create_order(amount_cents: int) -> None:
# v2 writes both shapes so old and new code always agree.
db.execute(
"INSERT INTO orders (amount, amount_cents) VALUES (%s, %s)",
(amount_cents / 100, amount_cents),
)
def get_order_total(order_id: int) -> int:
row = db.execute(
"SELECT amount, amount_cents FROM orders WHERE id = %s",
(order_id,),
).fetchone()
# New column wins; old column covers rows not yet backfilled.
return row.amount_cents if row.amount_cents is not None \
else int(round(row.amount * 100))Two discipline points. First, the contract step happens in a later release, not the same one as the migrate step — dropping the old column in the same deploy as the code that stops reading it reintroduces the overlap problem you just solved. Second, prove the old column is unused before you drop it: query pg_stat_statements or your slow-query log for references, or watch a dashboard for a week. A column that "nobody uses" has a way of being read by one reporting job at 3 a.m.
The same pattern scales beyond renames. Splitting a table, changing an enum to a lookup table, moving a column to a new service's database — each is an expand, a migrate, and a contract, and each phase is a separate deploy that the currently running code can survive. Our modular monolith vs microservices guide covers the larger version of the same question: when a schema boundary becomes a service boundary, and what that split costs.
Backfill in batches, not in one statement
Once the new column exists and the new code is dual-writing, the old rows still hold NULL in the new column. The backfill is where migrations most often become outages, because the obvious statement is the dangerous one:
-- Do not do this on a large table. One transaction, one long lock, -- a flood of dead tuples, and replication lag while it runs. UPDATE orders SET amount_cents = CAST(amount * 100 AS integer);
A single UPDATE of every row runs as one long transaction, holds row locks for its whole duration, generates dead tuples across the entire table, and — on a replicated setup — ships as one enormous write to every replica. The fix is mechanical: update in small batches, keyed on the primary key, with a pause between batches so replication and other writes can breathe.
# Backfill in batches, keyed on the primary key — never OFFSET.
last_id = 0
while True:
batch = db.execute(
"SELECT id FROM orders WHERE id > %s AND amount_cents IS NULL "
"ORDER BY id LIMIT 1000",
(last_id,),
).fetchall()
if not batch:
break
ids = [row.id for row in batch]
db.execute(
"UPDATE orders SET amount_cents = CAST(amount * 100 AS integer) "
"WHERE id = ANY(%s)",
(ids,),
)
db.commit()
last_id = ids[-1]
time.sleep(0.1) # let replication and other writes breatheKeyset pagination (WHERE id > last_id) matters here: OFFSET re-scans from the start on every batch, so the job gets slower as it progresses, exactly when you want it to finish. A batch of 1,000 rows is a reasonable default; tune it by watching replication lag and lock waits, not by guessing. And make the backfill idempotent and resumable — it should be safe to stop and restart at any point, because on a large table you will want to pause it during peak traffic and resume it at night. A backfill that must run to completion in one go is a backfill that will eventually be killed halfway through, leaving the table half-migrated.
One more guard: run the backfill after the dual-write deploy, not before. Rows written between the backfill and the dual-write deploy would land with a NULL in the new column and never be revisited. With dual-write live first, every new write populates both columns, and the backfill only has to cover history.
When the table is too big for ALTER: shadow tables
Expand/contract handles shape changes. It does not help when the change itself is a rewrite — changing a column type, converting a character set, or adding an index to a table with hundreds of millions of rows — because the ALTER still has to copy the table. That is the job for a shadow-table tool: build a copy of the table with the new schema, copy the rows in chunks, replay the writes that happened during the copy, and swap the tables in one atomic rename.
On MySQL, the two tools are gh-ost (GitHub's online schema change tool) and pt-online-schema-change (Percona Toolkit). The difference between them is how they capture the writes that land while the copy is running. pt-online-schema-change installs triggers on the original table, so every application write does a little extra synchronous work. gh-ost is triggerless: it tails the binary log as a replica and replays the changes onto the ghost table asynchronously, which adds no synchronous overhead to application writes. Both end the same way — an atomic rename that swaps the ghost table into place, with a lock measured in milliseconds.
gh-ost \ --host=replica.internal --user=ghost --password="$GHOST_PASS" \ --database=shop --table=orders \ --alter="MODIFY COLUMN email VARCHAR(320)" \ --max-lag-millis=1500 --execute
Three things to know before you reach for either tool. First, both need a primary key or unique key to iterate the table — a table without one cannot be chunk-copied. Second, gh-ost does not support tables that are the parent side of a foreign key, or tables with triggers of their own; plan the migration around those limits, do not discover them in production. Third, "online" does not mean "free": the row copy, the change replay, and the cutover all run against the primary, so the migration still consumes I/O and still needs throttling — --max-lag-millis pauses the copy when replication lag crosses the threshold. Run every migration in noop mode first (omit --execute) to validate connectivity, permissions, and the ALTER itself before anything touches production data.
On PostgreSQL there is no direct equivalent of gh-ost in common use, because PostgreSQL's online DDL story is different: most additive operations are cheap, CREATE INDEX CONCURRENTLY covers the common heavy case, and the expand/contract pattern plus batched backfill covers the rest. When a genuine rewrite is unavoidable on PostgreSQL — a column type change on a billion-row table, say — the honest options are the same shadow-table idea built by hand (a copy table, a trigger or logical replication to keep it current, a rename), or a maintenance window. Pretending the third option does not exist is how teams end up running a six-hour ALTER at 2 a.m. with no plan.
Know your engine's cheap operations
Half of zero-downtime migration work is knowing what your database already does cheaply, so you do not build machinery for a problem you do not have. The table below is the short list worth memorising; the details live in the linked primary sources.
| Operation | PostgreSQL | MySQL 8.0 |
|---|---|---|
| Add a nullable column | Metadata-only | ALGORITHM=INSTANT |
| Add a column with a constant default | Metadata-only since PostgreSQL 11 (released 18 Oct 2018) | ALGORITHM=INSTANT |
| Add a column with a volatile default | Full table rewrite — random(), clock_timestamp() | Full rebuild |
Add a NOT NULL constraint | PostgreSQL 18 (25 Sep 2025): add NOT VALID, then VALIDATE CONSTRAINT under a weak lock. On 17 and earlier, use a validated CHECK (col IS NOT NULL) first, then SET NOT NULL | ALGORITHM=INSTANT in many cases; verify per operation |
| Add an index | CREATE INDEX CONCURRENTLY — no blocking lock | ALGORITHM=INPLACE for most secondary indexes |
| Add a foreign key | Add NOT VALID, then VALIDATE CONSTRAINT | Metadata-only for the constraint; the scan still costs |
| Drop a column | Metadata-only (the column is marked unused) | Table rebuild |
| Change a column type | Full table rewrite | Table rebuild — use gh-ost or pt-osc |
Two rows deserve emphasis because they surprise people. The PostgreSQL 11 fast default applies only to constant defaults: ADD COLUMN status text NOT NULL DEFAULT 'active' is a catalog change, while ADD COLUMN id uuid DEFAULT gen_random_uuid() must produce a different value per row and rewrites the whole table. And the PostgreSQL 18 NOT NULL ... NOT VALID change, covered in our PostgreSQL 18 what's-new guide, removes a workaround teams had lived with for years — before 18, the only way to add a NOT NULL without a blocking scan was a placeholder CHECK constraint, a validate, a SET NOT NULL, and a cleanup drop.
The practical rule: before any migration, check the operation against your engine's documentation, not against what worked on the other engine last year. PostgreSQL's ALTER TABLE reference documents the lock and rewrite behaviour per subcommand, and it is the page to read before you run the statement — not after the incident.
The cutover checklist
The cutover is the moment the new shape becomes the only shape, and it deserves a checklist rather than confidence. Run through it in order, and do not skip the boring items — they are the ones that catch real outages.
SET lock_timeout = '5s' and SET statement_timeout = '30s' in the migration session, so a statement that cannot get its lock fails in seconds instead of wedging the table for the duration of a long transaction. This belongs in the migration tool's configuration, not in a runbook someone has to remember.NULL and where the old and new columns disagree. A backfill that is 99.9% done is not done — the remaining 0.1% is the row a customer will complain about.If any step fails, the correct response is to stop, not to hurry. The migration can wait; the table cannot be un-locked.
Rollback: the plan that actually works
Most rollback plans are fiction. "Roll back the migration" usually means running the inverse ALTER, which on a large table is itself a rewrite — the thing you were trying to avoid — and it does not restore the data written in the new shape while the migration was live. A real rollback plan has three properties, and they are all decided before the migration runs.
Prefer a forward fix. The first question after a bad migration is not "how do we roll back" but "can we fix this forward in ten minutes". A bad default, a wrong column type on a small table, a missing index — these are fixed by a new migration, not by reversing the old one. Forward fixes keep the data written since the deploy; rollbacks discard it or, worse, leave it in a shape nothing can read.
Keep the old shape until the next release. This is why the contract step is delayed. If the new column is wrong, the old column still holds the truth, and the rollback is a code deploy that reads the old column again — a normal, tested operation — rather than a schema change under pressure. The moment you drop the old column, you have spent your rollback.
Version your migrations and make them one-way. Use a migration tool — Flyway, Liquibase, or your framework's runner — with versioned, append-only migration files and a recorded history of what has run. Never edit a migration that has already run in production; write a new one. And never write a migration that cannot be re-run safely: every statement should be idempotent or guarded, because the migration will be run twice somewhere — on a staging rebuild, on a developer's laptop, on the replica you forgot about.
The honest limit: some changes have no clean rollback. A column type change that has already converted the data, a table split that has already moved rows — these are one-way doors, and the plan for them is not a rollback but a rehearsal. Run the migration against a production-sized copy first, measure how long each step takes, and decide the go/no-go criteria before you start. If you cannot rehearse it, you should not run it outside a maintenance window.
Architecture Decision
Decision: Change production schemas with expand/contract as the default pattern — additive schema change first, dual-write code second, batched backfill third, removal of the old shape in a later release — with shadow-table tools (gh-ost / pt-osc) reserved for rewrites on large MySQL tables, and engine-native cheap operations used directly when the documentation confirms they are metadata-only.
Context: The team deploys several times a day with rolling deploys, so old and new code run side by side against one database. Tables are large enough that a rewrite takes minutes to hours. There is no regular maintenance window, and the last migration outage was a lock queue, not a bad statement.
Options considered: (1) Expand/contract as the default, above. (2) Maintenance windows for every schema change — simplest to reason about, but it caps deploy frequency at the window schedule and turns every rename into a 2 a.m. event. (3) Shadow-table tools for everything — works, but adds operational machinery (binlog tailing, throttling, ghost-table cleanup) to changes that are a metadata-only ALTER on PostgreSQL. (4) Direct ALTER in the deploy, guarded by lock timeouts — fine for small tables and cheap operations, and the right answer there, but it does not scale to the tables that matter. (5) Online DDL only, no pattern — relies on the engine doing the right thing, and fails the moment a change needs application-level coordination, which renames and splits always do.
Why this one: Expand/contract is the only option that makes the schema change independent of the deploy order — each phase is a deploy the currently running code can survive, which is the property a team deploying several times a day actually needs. The engine-native cheap operations and the shadow-table tools slot into it as tactics inside phases, not as competing strategies. And the delayed contract step is what makes rollback a code deploy instead of a schema change under pressure.
What it costs you: Every rename or split becomes three releases instead of one, with dual-write code that has to be written, reviewed, and then removed. The backfill needs monitoring — replication lag, batch progress, a pause button — and someone has to own the follow-up ticket that drops the old column, because it will be forgotten otherwise. Shadow-table migrations add a tool to operate and a ghost table to clean up.
When to reverse it: On a small table with no concurrent traffic, drop the ceremony and run the direct ALTER with lock timeouts — the pattern is overhead there. Reverse toward maintenance windows when the change is a genuine one-way door on a table too large to rehearse, or when the database is small enough that a five-minute window is cheaper than three releases. And reverse the dual-write habit the moment you stop needing it: if the application is deployed atomically with no overlap, the expand step alone may be enough.
When NOT to do a zero-downtime migration
The pattern is not free, and there are changes where the honest answer is a window. Do not run expand/contract on a table with no traffic and no users — a side project's schema change does not need three releases. Do not use a shadow-table tool for a change the engine does natively and cheaply; gh-ost on a 10,000-row table is machinery in search of a problem. Do not backfill a column whose values cannot be derived from existing data — if the new column needs a human decision per row, no amount of batching helps, and the migration is a product decision, not an engineering one. And do not attempt a zero-downtime migration on a database you have never rehearsed against at production size: the first time you learn how long a rewrite takes should be on a copy, not on the table your customers are writing to.
The test for whether the ceremony is worth it is one question: will old and new code run against this database at the same time? If the answer is yes — rolling deploys, blue-green with a shared database, a long-lived API version — then the pattern pays for itself the first time it saves an incident. If the answer is no, run the ALTER, set the timeouts, and move on.
The goal was never to make migrations clever. It is to make them boring: a schema change lands, the old code keeps working, the new code starts working, the old shape disappears a release later, and nobody in the incident channel notices anything happened. Expand first, migrate second, contract last — and keep the old column until you are sure. That is the whole discipline, and it is enough.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.