The user wants a design for a database migration framework that follows a specific pattern: expand -> migrate -> contract. This is a classic "expand-contract" pattern for schema changes, often used in distributed systems or zero-downtime migration scenarios.
The user also specified three additional features:
- Expand→Migrate→Contract: This is the core workflow.
- Shadow Reads: Reading from both the old and new sources to verify data consistency or performance without affecting the user.
- Auto-Abort: A safety mechanism to stop the migration if errors or inconsistencies exceed a threshold.
I need to structure this response as a high-level system design document or a technical proposal.
Core Components:
- Configuration/Orchestrator: Manages state, steps, and settings.
- Data Access Layer (DAL) / Proxy: Intercepts application queries to route them appropriately (dual writes, shadow reads).
- Migrator/Worker: Moves historical data.
- Verifier: Compares data (checksums).
- Monitor/Telemetry: Collects metrics for auto-abort.
Phase Breakdown:
-
Phase 0: Preparation
- Set up the new database/schema.
- Deploy the framework code (DAL hooks).
-
Phase 1: Expand (The "Dual Write" Setup)
- Schema change: Add new table/columns without removing the old ones.
- Code change: The application starts writing to both the old and new locations.
- Nuance: Often, we write to Old first, then async to New, or synchronous dual-write (riskier for latency). Let's assume a log-based or async replication for the "write" part to avoid blocking user writes, or a "write old, then write new" in a queue.
-
Phase 2: Migrate (Backfilling)
- Move existing data that was created before the dual-write started.
- This needs to be idempotent (handling conflicts with incoming dual-writes).
- Need a cursor or offset tracking.
-
Phase 3: Shadow Reads (Verification)
- The user explicitly asked for this.
- App reads from Old (source of truth).
- Framework simultaneously reads from New (shadow).
- Compare results.
- Action: Log differences. Do not return New's result to the user yet.
-
Phase 4: Contract (Cut-over & Cleanup)
- Once verification passes, switch reads to New.
- Stop writes to Old.
- Drop old schema/tables.
Feature: Auto-Abort
- Needs metrics:
- Lag time (sync latency).
- Error rates (write failures to new DB).
- Data inconsistency rate (from shadow reads).
- Performance impact (latency increase).
- Mechanism: Circuit breaker pattern. If thresholds breached, stop writes to new, alert humans, revert to Old-only.
Detailed Design Structure:
- Architecture Overview: Diagram concept.
- The Workflow (Expand -> Migrate -> Contract): Detailed steps.
- Key Mechanisms:
- Dual Writes (The "Expand" write path).
- Backfilling (The "Migrate" path).
- Shadow Reads (The Verification path).
- Safety Features (Auto-Abort): The feedback loop.
- Implementation Strategy: Where does the logic live? (Middleware, App Code, Sidecar).
Refining the "Shadow Read" concept:
Usually, shadow reads happen before the full cutover.
- Read from Old (return to user).
- Async read from New.
- Compare.
If errors found -> Auto-abort.
Refining the "Auto-Abort" concept:
What exactly triggers it?
- Sync Write Failure: If the write to the new DB fails critically, do we fail the user request? Usually, for migration, we might "fire and forget" the new write to avoid impacting availability, but if error rate spikes, we stop the migration process.
- Consistency Failure: Shadow read mismatch.
Drafting the Content:
- Introduction: Define the philosophy (Zero downtime).
- Component Design:
- Proxy/Interceptor: The core piece.
- State Machine: To manage the phase.
- Step-by-Step Execution:
- Expand: Schema + Code deploy. Start Dual-Write.
- Migrate: Backfill job.
- Shadow & Verify: Compare reads.
- Contract: Switch primary, drop old.
- Deep Dive: Shadow Reads: Implementation details (A/B testing traffic).
- Deep Dive: Auto-Abort: Metrics, thresholds, rollback.
Let's structure the "Expand -> Migrate -> Contract" clearly.
- Expand: We add the new column/table. We update code to write to A and B.
- Migrate: We copy historical data A -> B. (Idempotent upserts).
- Contract: We read from B. We stop writing to A. We drop A.
Self-Correction/Refinement during thought process:
The prompt asks specifically about "Shadow Reads" as a feature. In a standard flow, Shadow Reads are part of the verification phase, usually running alongside the migration or just before cutover. I will place it between Migrate and Contract (or concurrent with Migrate) to validate the "Migrate" step.
Auto-abort logic:
If Shadow Read detects > 0.1% diff -> Trigger ABORT.
If Dual Write lag > 5 mins -> Trigger ABORT (or pause).
Let's write out the design.
System Name: "SafeShift" (just to give it a name for clarity).
Core Logic:
- Write Path:
- Phase 1 (Expand): Write Source -> Success? -> Write Dest (Async/Fire & Forget or Sync). Ideally Async via a queue for high throughput, but let's keep it simple: Interceptors.
- Read Path:
- Phase 2 (Shadow): Read Source. Parallel Read Dest. Compare. Return Source.
- Phase 3 (Contract): Read Dest.
Let's flesh out the "Migrate" part.
It's a background worker. It reads chunks from Source, writes to Dest. It must check timestamps to ensure it doesn't overwrite newer data from the "Expand" (Dual Write) phase.
Auto-Abort Triggers:
- Data Drift: Mismatch in shadow reads.
- Pipeline Lag: Queue backing up (if using async writes).
- System Health: CPU/Memory spike on Destination.
Okay, the plan is solid. I will present it as a technical architecture design.
- Architecture Diagram (Text-based)
- Workflow Phases
- Deep Dive: Shadow Reads
- Deep Dive: Auto-Abort
- Data Structure & Idempotency
(Self-Correction on "Contract"): Contract usually means removing the old column/table and the code that references it. This is a two-step deployment.
Deploy 1: Add new schema, dual writes.
Deploy 2: Switch reads, remove old code.
Deploy 3: Drop old schema.
But for the framework design, I'll group the logical phases.
Let's refine the specific requirement "expand->migrate->contract".
This usually refers to the "Parallel Change" pattern (formerly Expand/Contract).
- Expand: Add new thing.
- Migrate: Move data.
- Contract: Remove old thing.
The framework needs to manage the state of these transitions.
Final check on Shadow Reads:
It acts as the "monitor" for auto-abort.
If read(Old) != read(New):
Increment Error Counter.
If Counter > Threshold -> Abort.
Let's go.
This design outlines a robust database migration framework designed for zero-downtime deployment. It follows the Expand-Migrate-Contract pattern (often called the "Parallel Change" or "Blue-Green Data" pattern), utilizes Shadow Reads for verification, and includes an Auto-Abort mechanism for safety.
1. High-Level Architecture
The framework consists of three main logical components:
- The Proxy/ORM Layer: Intercepts application database calls to decide routing (Old DB vs. New DB vs. Both).
- The Migrator Service: A background worker that moves historical data.
- The Inspector: Monitors system health and data integrity to trigger auto-aborts.
2. The Workflow: Expand → Migrate → Contract
This phased approach ensures the application remains online and functional throughout the schema change.
Phase 1: Expand (Dual-Write Start)
Goal: Introduce the new schema without breaking the old one.
- Schema Change: A new table/column
v2 is created alongside the existing v1.
- Code Deployment: Application code is deployed with the "Dual-Write" feature flag turned OFF (writing to
v1 only).
- Activation: The framework enables Dual-Writes.
- Writes: The application writes to
v1 (Primary). The framework asynchronously replicates this write to v2.
- Reads: The application still reads strictly from
v1.
- Buffer: A persistent buffer (e.g., Kafka or Redis Streams) captures writes to ensure
v2 eventually receives all data, even if v2 temporarily goes down.
Phase 2: Migrate (Backfill)
Goal: Move existing data while keeping new data in sync.
- Backfill Process: The Migrator Service iterates through
v1 in batches (e.g., ordered by ID or UpdatedAt).
- Idempotency: It copies rows to
v2.
- Conflict Resolution: If a row already exists in
v2 (because the Dual-Write captured a recent update), the Migrator checks timestamps. It ensures it does not overwrite newer data with stale data.
- Lag Monitoring: The framework monitors the "Replication Lag" (how far behind
v2 is from v1).
Phase 3: Contract (Cut-over & Cleanup)
Goal: Deprecate the old schema.
- Shadow Read (Verification): Before switching, the system enters a verification mode (detailed below).
- Switch Read: Once verified, the Proxy routes all Reads to
v2.
- Stop Writes: The Proxy stops writing to
v1. v2 is now the Source of Truth.
- Drop Old Schema: After a safety period (e.g., 1 week), schema
v1 is dropped.
3. Feature Deep Dive: Shadow Reads
Shadow Reads are performed during Phase 2 (Late Stage) or just before the Phase 3 Switch. This is the critical "Trust but Verify" step.
Mechanism:
- Simultaneous Query: When the application performs a read (e.g.,
SELECT * FROM users WHERE id=100):
- The framework queries
v1 (Source of Truth).
- Simultaneously (async), it queries
v2 (The Target).
- Response: The application receives the data from
v1 immediately. The user experiences no latency.
- Comparison: The Inspector process compares the result from
v1 and v2.
- Strict Equality: Do the columns match?
- Semantic Equality: If the migration involved data transformation (e.g., splitting a
full_name column into first and last), does the transformation logic hold?
Outcome:
If the mismatch rate exceeds a defined threshold (e.g., > 0.01%), the framework marks the migration as "Unhealthy."
4. Feature Deep Dive: Auto-Abort
This is the safety net. If the migration corrupts data or degrades performance, the system automatically rolls back to v1.
Triggers for Auto-Abort:
- Data Drift (Shadow Read Failure): High discrepancy found during Shadow Reads.
- Replication Lag: If
v2 falls too far behind v1 (e.g., > 10 minutes), it indicates the write volume exceeds the migration speed.
- Error Rate Spike: If writing to
v2 causes the application's error rate (5xx responses) to spike.
- Infrastructure Load: If CPU/Memory on the database host hits critical levels.
How Abort Works:
- Circuit Breaker: The Proxy immediately stops all Dual-Writes to
v2.
- Read Lock: Ensures Reads remain pinned to
v1.
- Alert: Triggers a PagerDuty/Slack alert for engineering intervention.
- State Preservation: The
v2 data is not deleted. It is frozen so engineers can debug why it failed.
5. Implementation Logic (Pseudocode)
Here is how the Proxy/ORM Interceptor logic would look:
class MigrationProxy:
def __init__(self, db_v1, db_v2, config):
self.primary = db_v1
self.secondary = db_v2
self.state = config.mode # Modes: DUAL_WRITE, SHADOW_READ, LIVE_ON_V2
def write(self, data):
# Always write to Primary (V1) unless fully cut over
if self.state == "LIVE_ON_V2":
return self.secondary.write(data)
# 1. Write to V1 (Synchronous)
result = self.primary.write(data)
# 2. Dual Write to V2 (Async/Fire and Forget with buffer)
if self.state in ["DUAL_WRITE", "SHADOW_READ"]:
try:
# Offload to queue to prevent V2 latency affecting user
queue.push(data)
except Exception as e:
log_error(e)
# DO NOT crash user request if V2 fails, unless in Strict Mode
return result
def read(self, query):
# Standard Read
if self.state == "DUAL_WRITE":
return self.primary.read(query)
# Live on new DB
if self.state == "LIVE_ON_V2":
return self.secondary.read(query)
# Shadow Read Verification
if self.state == "SHADOW_READ":
# 1. Get real data for user
real_data = self.primary.read(query)
# 2. Spawn background thread to compare
spawn_thread(self.compare_shadow, query, real_data)
return real_data
def compare_shadow(self, query, real_data):
try:
shadow_data = self.secondary.read(query)
if not DataComparator.is_equal(real_data, shadow_data):
Metrics.increment("migration.mismatch")
if Metrics.get("migration.mismatch") > THRESHOLD:
self.trigger_abort()
except Exception as e:
log_error(f"Shadow read failed: {e}")
def trigger_abort(self):
log_critical("AUTO-ABORT TRIGGERED")
self.state = "DUAL_WRITE" # Revert to safe state (V1 only reads/writes)
Alerting.pager_team("Migration Failed")
6. Summary of States
| State | Write Target | Read Target | Shadow Check? | Description |
|---|
| Baseline | V1 | V1 | No | Normal operation. |
| Expand | V1 & V2 (Async) | V1 | No | Backfill starts; new data flows to V2. |
| Verify | V1 & V2 (Async) | V1 | Yes | System compares V1 and V2 for accuracy. |
| Contract | V2 | V2 | No | Cutover complete. V1 is deprecated. |
| Aborted | V1 | V1 | No | System detected drift; reverted to safety. |