Working with Data Migrations

1. Understanding Schema Migration Strategies

StrategyDetail
Expand / contractAdd new → migrate → remove old
Big-bangStop-the-world; only for tiny windows
Online (gh-ost)Shadow table, apply binlog, atomic swap
Versioned toolsFlyway, Liquibase, Alembic, Atlas
Forward-onlyNever edit applied migration

2. Implementing Dual-Write Pattern

PropertyDetail
DefinitionWrite to both old + new stores during migration
RiskPartial failure → divergence
MitigationOutbox + CDC; or write to one, sync to other
ReadCompare or shadow-read to verify parity

3. Implementing Incremental Migration

StepDetail
1Migrate small slice (per tenant / region)
2Validate, monitor SLOs
3Expand slice; iterate
4Cleanup old once 100% migrated

4. Implementing Data Backfilling

Example: Idempotent batch backfill (Java)

long lastId = readCheckpoint();
while (true) {
    List<Row> batch = jdbc.query(
        "SELECT id, payload FROM src WHERE id > ? ORDER BY id LIMIT 1000", lastId);
    if (batch.isEmpty()) break;
    for (Row r : batch) {
        jdbc.update("INSERT INTO dst(id, payload) VALUES(?, ?) "
                  + "ON CONFLICT (id) DO UPDATE SET payload = EXCLUDED.payload",
                  r.id, transform(r.payload));
    }
    lastId = batch.get(batch.size() - 1).id;
    writeCheckpoint(lastId);
    rateLimiter.acquire(batch.size());
}
PracticeDetail
IdempotentRe-run safely (UPSERT)
CheckpointResume after crash
Rate-limitedDon't saturate prod DB
Off-peakRun nights/weekends

5. Implementing Zero-Downtime Migrations

PhaseDetail
Add new (compat)New column nullable
Dual-writeWrite both
BackfillFill historical rows
Dual-read + verifyCompare; pick new if matches
Switch readsNew is source of truth
Stop dual-writeDrop old

6. Handling Data Transformation

PatternDetail
ETL / ELTSpark, dbt, Airflow
CDC streamDebezium → Kafka → transform → sink
Schema evolutionSchema Registry compat checks
Idempotent transformPure function of input

7. Implementing Migration Rollback

ApproachDetail
Reversible stepEach migration has up + down
Compat phasesOld schema still works during cutover
Snapshot beforePITR / logical backup
Forward-fixOften safer than reversing destructive ops

8. Implementing Data Validation During Migration

CheckDetail
Row countSELECT COUNT(*) parity
Checksum / hashPer-partition aggregate
Random sample diffSpot-check N rows
Shadow readsCompare prod responses live

9. Understanding Blue-Green Data Migration

PropertyDetail
Two DBsOld (blue) + new (green)
SyncCDC keeps green current
CutoverStop writes briefly → flip → resume
RollbackFlip back to blue

10. Implementing Parallel Run Strategy

StepDetail
Both systems liveOld + new compute results
CompareDiff outputs; investigate mismatches
ConfidenceAfter N days of parity, retire old
UseCritical financial / billing migrations