How do you migrate 40 million live rows with zero downtime?
Question
You must move a live orders table (40 million rows) from old_db to a new partitioned store new_db with a redesigned schema and zero downtime.
Live traffic serves 600 writes/s and 2,400 reads/s (3,000 QPS total). Throttled backfill workers can safely copy 2,500 rows/s in 1,000-row key-range batches without hurting live p99 latency.
- How long does the backfill take, and why can a late backfill row corrupt a live order?
- Design a 4-phase expand-and-contract migration (dual-write, guarded backfill, shadow reads, cutover) with a safe rollback path.
Show hints (3)
- "SIZE THE RACE WINDOW"
Divide
40,000,000rows by2,500 rows/s. Now multiply those seconds by600 writes/sto see how many live writes happen during backfill. - "GUARD STALE WRITES"
If dual-write saves version
2(paid) tonew_db, what stops a slow backfill worker from overwriting it with version1(new)? - "KEEP ROLLBACK ALIVE"
Compare shadow reads until mismatch hits
0%. After flipping writes tonew_db, keep reverse dual-writes toold_dbuntil the rollback window ends.
Show checked explanation
Backfilling 40 million rows at 2,500 rows/s takes 16,000 seconds (about 4.4 hours), while 9.6 million live writes run. Use four expand-and-contract phases: dual-write with old_db as primary, then run a throttled version-guarded backfill. Shadow-read until mismatch stays at 0%, cut over reads and writes, and keep reverse dual-writes for rollback.
def apply(store, row, guarded): oid, ver, status = row cur = store.get(oid) if guarded and cur is not None and cur[0] >= ver: return store[oid] = (ver, status) old_db = {1: (2, "paid"), 2: (1, "new")} for name, guarded in (("unguarded", False), ("guarded", True)): new_db = {} apply(new_db, (1, 2, "paid"), guarded) # live dual-write lands first apply(new_db, (1, 1, "new"), guarded) # stale backfill arrives late apply(new_db, (2, 1, "new"), guarded) # normal backfill row diffs = [k for k in old_db if new_db.get(k) != old_db[k]] rate = len(diffs) / len(old_db) * 100 print(f"{name:9} new={new_db} diffs={diffs} mismatch={rate:.0f}%")
unguarded new={1: (1, 'new'), 2: (1, 'new')} diffs=[1] mismatch=50%
guarded new={1: (2, 'paid'), 2: (1, 'new')} diffs=[] mismatch=0%Author-checked on CPython 3.12.10: ran the backfill-vs-live-write race and shadow-read parity simulator, checked throughput and duration math, and tested SQLite 3.49.1 version-guarded upserts. Checked by an editor other than the author.
Walkthrough
At 2,500 rows/s, copying 40,000,000 rows in 40,000 batches of 1,000 takes 16,000 seconds (about 4.4 hours). You cannot lock writes for 4.4 hours. Meanwhile, 600 writes/s * 16,000 s = 9.6 million live updates hit orders. Any naive copy races with those writes.
Run four reversible expand-and-contract phases:
| Phase | Write path | Read path | Exit gate |
|---|---|---|---|
| 1. Expand and dual-write | old_db primary, mirror to new_db | old_db (100%) | Dual-write error rate ~0% |
| 2. Guarded backfill | Dual-write + throttled 2,500 rows/s | old_db (100%) | All 40,000 batches done |
| 3. Shadow-read check | Dual-write (old_db primary) | old_db + async diff new_db | 0% mismatch for 24 h |
| 4. Cutover and contract | Flip primary to new_db + reverse mirror | Ramp new_db 1%->100% | Rollback window clean, drop old_db |
Phase 1 (Dual-write, old primary). Write every mutation to old_db first, then mirror to new_db (or stream via CDC / logical replication). Include a monotonic version (or updated_at plus sequence) and propagate deletes as versioned tombstones. If new_db fails during Phase 1, log the failed key for repair instead of failing customer checkout.
Phase 2 (Guarded backfill). Scan old_db by primary key range (WHERE id > last_id ORDER BY id LIMIT 1000), never OFFSET. In new_db, upsert conditionally: INSERT ... ON CONFLICT (id) DO UPDATE SET ... WHERE excluded.version > orders.version. As the trace shows, an unguarded worker overwrites live v2 (paid) with stale v1 (new), creating a 50% mismatch. The version guard drops stale rows and stays idempotent on retries.
Phase 3 (Shadow reads). For sampled live reads (1% -> 10% -> 100%), query new_db asynchronously, compare normalized records against old_db, and record mismatch counts. Fix any schema or serialization bugs until mismatch stays 0% over a full 24-hour cycle.
Phase 4 (Cutover and rollback). Ramp reads to new_db (1% -> 10% -> 50% -> 100%). Next, flip write primary to new_db while keeping reverse dual-writes to old_db for 24 to 72 hours. If new_db stalls under full load, switch reads and writes straight back to old_db without losing post-cutover orders. Only then stop reverse writes and retire old_db.
Common mistakes
- Running backfill before dual-write or CDC starts. Rows updated between the scan and cutover are missed or overwritten with stale snapshots.
- Using
SELECT ... OFFSETpagination across 40 million rows. Deep offsets scan millions of skipped rows and overloadold_db; paginate by primary key instead. - Stopping writes to
old_dbthe second you flip primary tonew_db. Without reverse dual-writes, rolling back drops every order created after cutover. - Ignoring deletes during dual-write and backfill. Without versioned tombstones, an order deleted in
old_dbstays alive as a zombie row innew_db.
Follow-up questions
- "Should you mirror writes from application code or use database CDC (logical replication)?" Prefer CDC or logical replication when moving between compatible engines: every writer (including admin jobs and background workers) is captured automatically with strict commit order. Use app dual-writes when the schema transform depends on domain logic not stored in one table, paired with a reconciliation job.
- "Shadow reads show a 0.02% mismatch rate. Could that just be replication lag?" Yes. Measure lag separately by re-checking each mismatched key after 2 seconds. Transient lag clears on re-check; persistent mismatches mean a real writer bug, missing code path, or transform mismatch that must be fixed before cutover.
- "How do you avoid dual-write latency spikes hurting checkout during Phase 1?" Commit to
old_dbplus a local outbox (or readold_db's WAL via CDC) and ship writes tonew_dbasynchronously. That keepsnew_dblatency and brief outages completely off the checkout critical path.
What a strong answer covers
Computes the 4.4-hour (16,000 s) backfill and 9.6 million concurrent writes. Sequences dual-write, key-range version-guarded backfill, async shadow-read parity down to 0%, gradual read cutover, and a reverse dual-write rollback window before retiring old_db.
Open in interactive practice deck →