Highlights

Contents

Part VII
07

Zero-downtime migrations

We make the risky schema changes, renames, type changes and data moves, without a maintenance window. The method is always the same, adding the new shape beside the old one and moving across in small, reversible steps. We will cover expand and contract, batched backfills, and dual writes with a careful cutover.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Connections and pools2Queries from code3Inside an ORM4Transactions in code5Concurrency control6Schema migrations7Zero-downtime migrations8Scaling database access9The order write end toend

#Section 23Expand and contract

Wren’s orders table has a column called note, which the kitchen reads. Product wants it renamed to kitchen_note, because a separate customer note is coming. ALTER TABLE orders RENAME COLUMN note TO kitchen_note takes a millisecond. It also breaks every running instance at once, because old code selects note and the column no longer exists. During a rolling deploy, some instances run old code and some new, so there is no single moment when renaming is safe.

The answer is expand and contract, also called parallel change, a pattern Danilo Sato described on Martin Fowler’s site in 2014. The change is split into steps, and each step is compatible with the code running before it and the code running after it.

EXPAND AND CONTRACT: RENAMING note TO kitchen_note WITHOUT DOWNTIMEEXPAND AND CONTRACT: RENAMING note TO kitchen_note WITHOUT DOWNTIME1add column2write both3backfill4read new5stop old6drop oldnotekitchen_notewritten and readread by nobodygonewritten, filling upwritten and readsix deploys or migrations; each step is safe with the code before it and after itexpand adds things the old code ignores; contract removes things the new code no longer usesthe same shape handles column type changes, table splits and moving data between stores
Figure 6.40Six steps. At every moment, the code that is running works with the schema that exists.

For the rename, there are six steps. First, expand the schema by adding kitchen_note as a nullable column, which old code ignores. Second, deploy code that writes to both columns on every insert and update but still reads note. Third, backfill, copying note into kitchen_note for every existing row, in batches as the next section describes. Fourth, deploy code that reads kitchen_note, while still writing both, so instances that have not yet updated keep working. Fifth, deploy code that stops writing note. Sixth, contract by dropping note once nothing references it.

Each step can be rolled back on its own. If step four reveals a bug, the previous version still reads note, which is still being written, so rolling back loses nothing. That is the point. A single big change has one moment of truth and no way back. A sequence of small changes has many safe stopping points.

MID-ROLLOUT: OLD AND NEW CODE SHARE ONE SCHEMA, AND BOTH MUST BE HAPPYMID-ROLLOUT: OLD AND NEW CODE SHARE ONE SCHEMA, AND BOTH MUST BE HAPPYv41v41v42v42idnotekitchen_note123no onionsno onions124extra raitaextra raitareads notereads kitchen_noteboth versions write both columnsdrop note now and the v41 instances crash; drop it after the rollout and nobody notices
Figure 6.41During a rollout, two versions of the code share one schema. Both must be satisfied.

The cost is calendar time and discipline. A rename that looks like one line takes six steps, often spread over several days so that each can be observed in production. Teams track multi-step migrations in a ticket with a checklist, and some write the contract step as a dated reminder, because forgotten old columns pile up for years. The same shape handles changing a column type, splitting a table in two, moving data to another database and replacing an enum with a lookup table.

#Section 24Batched backfills

Step three copies data in 5,000,000 rows. The obvious statement is one UPDATE orders SET kitchen_note = note. On a big busy table it causes several kinds of damage at once. It runs as one transaction, so it holds row locks on all 5,000,000 rows until it commits, and any order update by a customer or the kitchen waits. It writes a new version of every row, so the table and its indexes temporarily double in size until vacuum cleans up. It generates gigabytes of write-ahead log in one burst, which replicas must replay, so their lag climbs. And if it fails after 20 minutes, everything rolls back and the next attempt starts from zero.

A batched backfill updates a small slice at a time, each in its own short transaction.

sql
UPDATE orders SET kitchen_note = note
WHERE id BETWEEN $1 AND $1 + 999
  AND kitchen_note IS NULL;
BACKFILL 5,000,000 ROWS IN 5,000 BATCHES OF 1,000BACKFILL 5,000,000 ROWS IN 5,000 BATCHES OF 1,000each square is 10 batches; each batch is one short transactionUPDATE orders SET kitchen_note = note WHERE id BETWEEN $1 AND $1 + 999 AND kitchen_note IS NULL;50 ms work + 50 ms sleep5,000 × 100 ms = 500 sresumable, throttled, idempotent
Figure 6.425,000 batches of 1,000 rows. Each one is a short transaction, so customers never notice.

With batches of 1,000 rows, 5,000,000 rows take 5,000 batches. At an illustrative 50 ms per batch, the work itself takes 5,000 × 0.05 = 250 s. Wren adds a 50 ms sleep between batches so the database and its replicas can keep up, which doubles the total to 5,000 × 0.1 = 500 s, a little over eight minutes. Each batch locks at most 1,000 rows for 50 ms, so a customer editing an order waits at most that long.

Three properties make the job safe to run in production. It is resumable, because it walks the primary key range and records its position, so a crash restarts from the last completed batch. It is idempotent, because kitchen_note IS NULL skips rows already done, and running it twice is harmless. And it is throttled, slowing down or pausing when replication lag or database CPU crosses a threshold.

ONE GIANT UPDATE VERSUS SMALL BATCHES, AS SEEN BY A REPLICA (ILLUSTRATIVE)ONE GIANT UPDATE VERSUS SMALL BATCHES, AS SEEN BY A REPLICA (ILLUSTRATIVE)secondsreplica lag (s)one UPDATE commits 5,000,000 rowsbatched: lag stays near zeroa huge transaction also holds 5,000,000 row locks until it ends and cannot be resumed
Figure 6.43Illustrative. One giant UPDATE pushes replicas minutes behind; small batches keep lag flat.

Batch size is a trade. Bigger batches finish sooner and hold locks longer, smaller ones are gentler and slower. Start with 1,000, watch the lock waits and lag, and adjust.

#Section 25Dual writes, verification and cutover

Between steps two and five, the application writes the same data to two places. That window has its own risks, and the larger the data move, the more they matter.

Within one database, dual writes are simple. The code sets both columns in the same UPDATE, inside the same transaction, so they can never disagree. A database trigger can do the same job, copying note to kitchen_note on every write, which also covers writers outside the main application, such as an admin tool or a script. Triggers are invisible to most developers, so Wren uses them sparingly and removes them in the contract step.

Across two systems, say moving the orders table to a new database, dual writes cannot be atomic without a distributed transaction. Writing to the old store and then the new one leaves a gap where one write succeeds and the other fails. The safer pattern is to write to the old store as the source of truth and feed the new one from its change stream, through change data capture or an outbox as Unit VIII explains, so the new store converges even after failures.

Before cutting reads over, verify. Wren runs a shadow read for a day. The code reads from both columns, returns the old one to the user and logs any difference, with the order id. A comparison job also scans in batches and counts mismatches. Cutover happens when both report zero. For a cross-database move, shadow reads also prove that the new store can handle production query patterns and latency before any user depends on it.

The cutover is a code change behind a feature flag, so it can be flipped back in seconds without a deploy. Wren moves 1% of reads first, then 10%, then all, watching error rates and latency at each step. Only after a quiet week does the contract step drop the old column, because a drop is the one step that cannot be undone.