Zero-Downtime Data Migration: Phases and Rollback
Difficulty: Senior Level | Companies: Netflix, Uber, Airbnb, Stripe, Databricks
Migrating a live data platform is one of the few tasks where a partially completed job is worse than a failed one. If you stop halfway, you now have two systems of record, an argument about which one is correct, and a team that has to reason about both during every incident. The discipline of zero-downtime migration is therefore less about moving bytes quickly and more about designing a sequence in which every intermediate state is safe, observable and reversible.
Prerequisites
- !Warehouse and object storage table formats
- !How transactions and atomic renames work
- !Basic familiarity with schema contracts
What You'll Learn
- 1Classify a migration as lift-and-shift, strangler or rewrite
- 2Implement dual writes with sampling-based consistency verification
- 3Separate additive schema changes from breaking ones
- 4Write a rollback plan that is tested before cutover
Pick the migration shape before touching data
Six migration scenarios recur in practice, and each has a different risk profile. A platform migration moves workloads from one warehouse to another, for example Redshift to Snowflake, while keeping the logical model intact. A format migration converts Parquet to Delta Lake or Iceberg without changing semantics. A schema evolution adds, renames or retypes columns. A storage migration relocates files from on-premises hardware to object storage. A database migration moves an operational system between engines. A pipeline migration upgrades the orchestrator itself, such as Airflow v1 to v2.
The shape determines your blast radius. A format migration can usually be done with a bulk rewrite and a short read-only window, because the query surface is unchanged. A platform migration changes the query engine, the SQL dialect and the performance envelope at once, so it needs a shadow-read period. Choosing the wrong shape is the most common early mistake: teams treat a dialect-changing platform move as if it were a file copy, then discover during cutover that timestamp handling, case sensitivity and null ordering all behave differently.
The three phases of a strangler migration
The strangler fig pattern, borrowed from application architecture, keeps the legacy system alive while traffic moves gradually to its replacement. Phase one is dual-write: every mutation lands in both stores, with the legacy system remaining the source of truth. Phase two is shadow-read: reads are still served by the legacy system, but the new system is queried in parallel and the results compared on every request or on a sampled batch. Phase three is cutover: reads move to the new system, the legacy system becomes read-only, and it is retained as a backup for a fixed window, typically thirty days.
Each phase has an exit criterion, and the criteria must be numeric. Dual-write is complete when the sampled consistency rate stays above 99.9 percent for a full business cycle. Shadow-read is complete when result mismatches fall below your agreed tolerance for seven consecutive days. Cutover is complete only after the rollback trigger has been exercised at least once in a rehearsal. Phases without exit criteria turn into permanent states, which is how migrations end up taking two years.
| Phase | Writes | Reads | Exit criterion | Rollback |
|---|---|---|---|---|
| Dual-write | Legacy plus new | Legacy only | 99.9 percent consistency for one cycle | Stop writing to new store |
| Shadow-read | Legacy plus new | Legacy, compare new | Mismatches under tolerance for 7 days | Discard new results |
| Cutover | New only | New only | Rehearsed rollback, stakeholders notified | Flip reads back to legacy |
Dual writes and how to verify them
The dual writer must never let the new store take down the legacy path. Write to the legacy system first, treat any failure on the new side as a logged, retried discrepancy, and verify a sample of keys continuously rather than trusting that the code path is correct. Verification is the whole value of the pattern; without it, dual-write is just extra work.
import random
import threading
from typing import Any, List
class DualWriter:
def __init__(self, legacy_store, new_store):
self.legacy = legacy_store
self.new = new_store
self.lock = threading.Lock()
self.mismatches: List[str] = []
def write(self, key: str, value: Any) -> None:
with self.lock:
self.legacy.write(key, value)
try:
self.new.write(key, value)
except Exception as exc:
log_migration_error(key, exc)
def verify_consistency(self, key: str) -> bool:
return self.legacy.read(key) == self.new.read(key)
def verify_sample(self, keys: List[str], sample_size: int = 1000) -> float:
sample = random.sample(keys, min(sample_size, len(keys)))
matches = sum(1 for key in sample if self.verify_consistency(key))
rate = matches / len(sample) if sample else 1.0
if rate < 0.999:
self.mismatches.extend(k for k in sample if not self.verify_consistency(k))
return rate
Run the sampler from a separate scheduled job, not from the request path, so verification latency never reaches a user. Persist the mismatch keys; they are the fastest way to find the bug that produced them.
Schema changes that are safe versus breaking
Additive changes are safe: adding a nullable column, adding a new table, widening a numeric type. Compatible changes need care but are survivable: renaming a column if the old name is kept as a deprecated alias, or loosening a constraint. Breaking changes stop consumers dead: dropping a column, narrowing a type, changing a key, or altering the grain of a table.
class CannotDropColumnError(Exception):
pass
class SchemaEvolver:
@staticmethod
def add_column(df, name: str, default, column_type: str):
return df.withColumn(name, F.lit(default).cast(column_type))
@staticmethod
def add_alias(df, old_name: str, new_name: str):
return df.withColumn(new_name, F.col(old_name))
@staticmethod
def drop_when_unused(df, column: str, referenced_by: list):
if referenced_by:
raise CannotDropColumnError(
f"{column} still referenced by {', '.join(referenced_by)}"
)
return df.drop(column)
For a genuinely breaking change, build the new table alongside the old one, backfill it, publish a compatibility view that exposes the old shape, migrate consumers one at a time, and only then retire the original. The compatibility view is what buys you a week of consumer migration instead of a single coordinated deploy.
Proving the move with checksums and counts
Row counts alone are a weak proof because a bug can drop and duplicate the same number of rows. Combine three signals: an exact row count, a schema comparison, and a checksum computed over a deterministic ordering of the key and payload columns. When all three agree, you can state with confidence that the data moved intact.
from typing import List
class MigrationVerifier:
def __init__(self, source, target):
self.source = source
self.target = target
def verify_table(self, table: str) -> dict:
src = self.source.describe(table)
dst = self.target.describe(table)
src_sum = self.source.checksum(table, ["order_id", "order_total"])
dst_sum = self.target.checksum(table, ["order_id", "order_total"])
return {
"row_count_match": src.row_count == dst.row_count,
"source_rows": src.row_count,
"target_rows": dst.row_count,
"schema_match": src.columns == dst.columns,
"checksum_match": src_sum == dst_sum,
"passed": src.row_count == dst.row_count
and src.columns == dst.columns
and src_sum == dst_sum,
}
def verify_all(self, tables: List[str]) -> dict:
results = {t: self.verify_table(t) for t in tables}
failed = [t for t, r in results.items() if not r["passed"]]
return {"total": len(tables), "failed": failed, "passed": not failed}
Automate this check into the pipeline that performs the copy so a mismatch blocks the cutover rather than being discovered by an analyst two days later.
The rollback plan you write on day one
A migration without a tested rollback is a one-way door, and interviewers probe for exactly that. Write the rollback plan before the first byte moves: which flag flips reads back, how long the flip takes, what happens to writes that landed in the new system after the flip, and who is authorised to trigger it. Then rehearse it. A rollback that has never been executed is a hypothesis.
Sequence the work so early wins build confidence. Migrate the simplest tables first, prove the verifier catches an intentionally injected error, then take on the complex nested structures. Keep the legacy system untouched and available for at least thirty days after cutover, and only decommission it once the rollback window has closed and every stakeholder has confirmed their dashboards.
â ī¸Interview trap
Candidates who describe the forward path in detail but cannot say how they would revert are almost always asked a follow-up. Have an answer ready that names the mechanism, the time budget and the data-handling implications of returning to the old system.
Common Mistakes
Treating a warehouse swap as a simple file copy
Fix: Run a shadow-read period to surface dialect, timezone and null-ordering differences
Verifying with row counts only
Fix: Combine row counts, schema comparison and a deterministic checksum
Keeping the legacy system for only a few days after cutover
Fix: Hold it for at least thirty days and exercise the rollback once in rehearsal
Dropping a column as soon as your own pipeline stops using it
Fix: Query lineage first and drop only when every downstream reference is gone
Best Practices
- Define numeric exit criteria for every phase before starting it
- Write to the legacy store first so a new-store failure cannot break production
- Persist mismatched keys during verification instead of only logging a rate
- Ship a compatibility view for breaking changes so consumers migrate on their own schedule
- Migrate the easiest tables first to prove the tooling before tackling hard ones
Interview Questions
Q1: Walk me through your phases for migrating a warehouse with a thousand dashboards.
Inventory and dependency mapping, dual-write with sampled verification, shadow-read comparing query results for a week, staged dashboard cutover by business unit, then a thirty-day rollback window before decommissioning.
Q2: How do you handle foreign keys and constraints during a migration?
Disable or defer constraints during bulk load where the engine allows it, load in dependency order, then validate constraints explicitly before cutover and before enabling them on the target.
Q3: What makes a schema change safe?
It is additive and nullable, keeps existing consumers working unchanged, and can be rolled back by simply ignoring the new field. Everything else needs a compatibility layer and a coordinated consumer migration.
Q4: How would you migrate a streaming pipeline?
Dual-write topics, mirror consumers in shadow mode to compare emitted results, then shift consumer group offsets to the new topic while keeping the producer writing to both until lag on the old topic reaches zero.
Q5: What is your rollback mechanism?
A single feature flag or DNS change that returns reads to the legacy system, a defined time budget for the flip, a policy for writes accepted by the new system after the flip, and a named person authorised to trigger it.
Key Takeaways
- Classify the migration shape first because it determines the blast radius
- Strangler migrations need numeric exit criteria or they never finish
- Dual-write without continuous sampled verification is wasted effort
- Additive schema changes are safe; breaking ones need a compatibility view
- Row count, schema and checksum together are the minimum proof of a correct move
- Write and rehearse the rollback plan before moving the first byte