Yousef AldabbasSystems & backend engineering
โ— ENGINEERING NOTESAMMAN, JORDAN
← back to posts

Zero-Downtime Database Migration: The 8-Step Pattern, Run in Code

2026-11-09 ยท databases

Based on Aviran Mordo's 8 Steps to Safely Migrate a Database Without Downtime (DZone, first published on his own blog as Safe Database Migration Pattern Without Downtime), and on Wix's newer write-up of a different approach, How We Built a Zero-Downtime Database Migration Service at Wix. I implemented the 8 steps as a small simulation and ran it, so the numbers below are from that run, not from the articles.

You want to move data from an "old" database (or schema) to a "new" one while the app keeps serving traffic. You cannot stop the world, copy everything and flip a switch, because the copy takes hours and users keep writing during it. Mordo's answer is a lazy migration driven by a feature toggle: the app moves through a series of states, and every state can be reversed until one specific point.

The 8 steps as toggle states

type Step =
  | "OLD_ONLY"            // 1-2  new schema deployed, new DAO (data access code) exists but is unused
  | "WRITE_BOTH_OLD_PRI"  // 3    write old first, then new. Read old.
  | "READ_BOTH_OLD_PRI"   // 4    still write both. Read both, old is authoritative.
  | "WRITE_BOTH_NEW_PRI"  // 5    write new first, then old (best effort). Read both, prefer new.
  | "WRITE_NEW_ONLY"      // 6    stop writing old. Old becomes read-only.
  | "NEW_ONLY";           // 7-8  backfill the rest, then delete the old DAO

The key idea is that exactly one database is "primary" at a time: the one whose write must succeed. The other write is best effort, because writing to two databases can never be made atomic. In steps 3 and 4 the old database is always correct and the new one may have holes. In step 5 the roles swap.

The experiment

Two in-memory SQLite databases, with a real schema change: the old table stores full_name, the new one splits it into first_name and last_name. Each step adds 600 writes (half inserts, half updates to existing rows). The secondary write fails 5% of the time to simulate the "can't be 100% sure both writes succeed" problem. A ground-truth map records what every row should be, so I can check both databases and every read against it. The PRNG is seeded, so the run is reproducible. The full script is db-migration-sim.mjs; it needs Node's built-in node:sqlite.

The heart of it is two small functions:

function write(u) {
  const [primary, ...secondary] = STATES[state].write;
  dao[primary].upsert(u);                       // must succeed, else the request fails
  for (const s of secondary) {
    try { dao[s].upsert(u); }                   // best effort
    catch { stats.secondaryFailed++; }          // swallowed: this is the inconsistency window
  }
}

function read(id) {
  const o = oldDao.get(id), n = newDao.get(id);
  if (mode === "both-old-auth")                  // step 4: prefer new only if timestamps match
    return n && o && n.ts === o.ts ? n : (o ?? n);
  return n && o ? (n.ts >= o.ts ? n : o) : (n ?? o);   // step 5+: newest timestamp wins
}

What came out

step                               rows   old correct   new correct   wrong reads
0. before migration (old only)      484           484             0             0
3. dual write, old primary          783           783           465             0
4. read both, old authoritative    1095          1095           826             0
5. new primary (point of no return)1405          1376          1194             0
6. stop writing old                1689          1121          1513             0

(The 1000 pre-migration writes produced 484 distinct rows because half of them were updates.) Two things stand out:

Step 7 has a trap for mutable data

The article says to eagerly copy the records that are not yet present in the new database. For immutable data that is enough. My run showed it is not enough when rows get updated:

before backfill:                      rows wrong/missing in new = 176
pass A (copy rows missing in new):    copied 168
                                      a blind overwrite would have clobbered 268 newer rows
after pass A:                         rows wrong/missing in new = 8
pass B (copy where old.ts > new.ts):  fixed 8 stale rows
after pass B:                         rows wrong/missing in new = 0

Pass A fixed 168 missing rows but left 8 rows that existed in the new database with an old value: an update whose secondary write failed in step 3 or 4. They are not "missing", so "copy what's missing" skips them. If I had deleted the old DAO at that point (step 8), reads would have returned 8 wrong values. Two rules follow:

Then verify: compare the two databases (counts and checksums, or a sampled row-by-row diff) before deleting the old DAO.

What this simulation does not cover

It is a single process with in-memory SQLite and a random 5% failure rate. It has no concurrent writers, so it does not show two requests racing on the same row across the two databases. It does not model slow queries, replication lag, missing indexes or memory pressure. Mordo's side note says those are what actually bite in production: Wix runs steps 3 and 4 for at least two weeks each, sometimes a month, and the problems they hit there included large objects held in memory causing GC storms at peak traffic, replication not configured properly, missing monitoring, missing indexes and a data model that read poorly. Also, I swallowed secondary failures silently; in real code each one needs a metric and an alert, since the failure count is how you know when step 3 is ready to graduate.

The other way: let the infrastructure do it (Wix DB Mover)

Mordo's pattern lives in application code: you add a DAO, a toggle and merge logic. Wix's later post describes the opposite approach for moving a database between clusters: the application changes nothing, and a migration service does the work.

Cheatsheet

QuestionMordo's app-level patternWix DB Mover (CDC)
Where does it live?In your app: DAO + toggleIn a separate service; app unchanged
Good fitDifferent databases or schemas (MySQL to MongoDB, schema redesign)Same kind of database, cluster to cluster
Consistency while movingOne DB is primary; other is best effort and may have holesDestination follows the source via the change stream
RollbackFree until step 5Free until the write cutover
Main costMerge-read code, two DAOs, weeks of dual runningExtra infrastructure (Kafka, connectors, a service)

Conclusion

The pattern works because it turns one risky cutover into many small, reversible ones. The simulation backed up the shape of it: the new database was only about three quarters correct halfway through, the app stayed correct anyway, and the old database became unsafe to return to after step 5. It also found one place where the written steps are incomplete for data that gets updated: the final backfill has to fix stale rows, not only missing ones.

References