1. Understand the Goal: The user wants a design for a "safe parallel schema migration runner." Key requirements include:
* Safe: Minimize downtime, prevent data loss/corruption, handle errors gracefully.
* Parallel: Run migrations concurrently (or run chunks of data updates concurrently) to speed up the process.
* Schema Migration: Specifically focused on database schema changes and data backfills.
* Specific Features:
* Chunking: Breaking down large operations into smaller batches.
* Canaries: Testing the migration on a small subset before full deployment.
* Invariant Checks: Verifying data integrity before, during, and after the migration.
Target Audience: Likely a backend engineer or system architect looking for a robust solution to handle large-scale database changes without causing production outages.
Core Concepts & Architecture:
The Problem:ALTER TABLE locks the database. Large data backfills block replication. The "Stop-the-world" problem.
The Solution: Online Schema Migration (OSM) principles (like gh-ost, pt-online-schema-change, pg_repack, or generic application-level backfilling).
Concurrency: The user asked for parallel. This implies either parallelizing the backfill across multiple workers or running the migration steps in a non-blocking way. I will focus on a "Shadow Table + Chunked Backfill" approach, orchestrated by a distributed runner.
Design Components:
Phase 0: Preparation (The Setup)
Create a shadow table (_new).
Apply schema changes to the shadow table.
Set up triggers (or a CDC stream) to keep original and shadow in sync. Self-correction: Triggers add overhead. CDC (Change Data Capture) is better for modern systems, but Triggers are easier to explain as the standard OSM approach. Let's stick to Triggers or dual-writes for the design.
Phase 1: The Canary (The "Test")
Run the migration on a tiny slice.
Check for application errors.
Check for invariant violations.
Phase 2: Chunking & Parallelism (The "Work")
We need to iterate over the primary keys.
Divide keyspace into ranges (chunks).
Use a queue (e.g., Kafka, Redis, or a DB table as a queue) to distribute work to N workers.
Safety: Throttle (pause) if database load (replication lag, CPU) gets too high.
Phase 3: Invariant Checks (The "Verify")
Hash checks? Count checks? Business logic checks?
Need to check during the run (sampling) and after the run (final verification).
Phase 4: Cutover (The "Switch")
The critical moment.
Lock writes briefly (or use renames).
Swap tables.
Detailed Mechanism Breakdown:
Chunking Strategy:
How to define boundaries? Min/Max ID is standard.
Dynamic chunk sizing? If a chunk is slow (hot rows), shrink the next chunk size.
"Golden Chunk" concept: Don't copy data that hasn't changed if using CDC, but for a backfill, we usually just copy ranges.
Parallel Runner Architecture:
Controller: Manages state, assigns chunks.
Workers: Execute the INSERT INTO shadow ... SELECT ... queries.
Monitor: Checks DB health (Lag, CPU).
Canary Logic:
Instead of just "1% traffic," apply the migration to "Rows 1-1000".
Run read-only queries against the shadow table to ensure data looks right.
Invariant Checks:
Structural: Does the column exist?
Data: Are FKs valid? Are NULL constraints met?
Business: (e.g., Total balance == sum of transactions).
Structuring the Answer:
Introduction: Define the philosophy (Zero-downtime, online DDL).
High-Level Architecture: Visualize the flow.
Key Strategies (The "How"):
The "Shadow" Pattern (Foundation).
Chunking Strategy (Parallelism).
Canary Strategy (Risk Mitigation).
Invariant Checks (Integrity).
The Workflow (Step-by-Step): From start to cutover.
Code/Pseudo-code Example: Concrete implementation details (Go or Python style).
Handling Failures: Rollback and safety valves.
Refining the "Parallel" aspect:
Simply running ALTER TABLE isn't parallelizable by the user.
The parallelism comes from copying data from Table A to Table B.
I need to emphasize cooperative scheduling. If 10 workers run full tilt, they will kill the DB. We need adaptive throttling.
Drafting Content - Specific Points to Hit:
Backfill:INSERT INTO target SELECT * FROM source WHERE id > x AND id <= y.
Lag Monitor: Must check Seconds_Behind_Master (MySQL) or Replica Lag (Postgres).
Cut-over: Needs a lock. RENAME TABLE source TO old, target TO source.
Self-Correction/Review during drafting:
Initial thought: Use database triggers. Correction: Triggers are expensive and hard to debug. Mention "Dual Write" at the application layer as an alternative, but stick to Triggers/gh-ost style for a generalized "Runner" design as it's more database-agnostic (conceptually).
Invariant Checks: Make sure to distinguish between structural invariants (schema) and data invariants (values).
Final Polish: Use clear headings, code blocks for logic, and a diagram description (since I can't draw, use Mermaid-style text representation).
(Self-Correction on "Parallel"): If the user means running multiple different migrations in parallel, that's a different problem. The prompt implies one migration that is parallelized (chunking) to be fast. I will assume the latter (data backfill parallelization).
Output Generation: (Proceed to generate the response based on these steps.)
Designing a schema migration runner for high-traffic systems requires moving away from naive "locking-and-updating" strategies. We need an architecture that treats migrations as application releases: iterative, observable, and reversible.
Below is a design for a Safe Parallel Schema Migration System based on the "Shadow Table" pattern (often used by tools like gh-ost or pg_repack), extended with application-level logic for canaries and invariant verification.
High-Level Architecture
Instead of running an ALTER TABLE directly on the production table (which causes locking), the runner operates on a Ghost/Shadow Table and synchronizes data asynchronously. The migration is only "cut over" to the new schema after invariant checks pass.
The 4 Phases:
Preparation: Create shadow schema.
Catch-up (Chunking): Parallel bulk data copy.
Verification (Canary & Invariants): Compare data samples.
Cutover: Atomic swap.
1. The Core Mechanism: Chunking & Parallelism
To migrate terabytes of data, we cannot copy row-by-row. We must partition the dataset into chunks and process them in parallel threads/workers.
The Chunking Strategy
We rely on the Primary Key (usually auto-increment integer or UUID) to define boundaries.
Range Calculation: Determine Min and Max IDs.
Stride: Divide the range into chunks (e.g., 10,000 rows per chunk).
Queue: Push chunk definitions [start_id, end_id] into a work queue.
The Parallel Runner Logic
We use a worker pool. Each worker picks up a chunk range and performs an INSERT IGNORE or UPSERT operation.
python
class MigrationWorker:
def __init__(self, source_db, shadow_db, chunk_size=1000):
self.source = source_db
self.target = shadow_db
self.chunk_size = chunk_size
def run_chunk(self, start_id, end_id):
# 1. Fetch batch from Source
rows = self.source.execute(
f"SELECT * FROM original_table WHERE id BETWEEN {start_id} AND {end_id}"
)
# 2. Transform (if needed)
transformed = [self.transform_row(r) for r in rows]
# 3. Bulk Insert into Shadow
# Use batching to reduce network round-trips
self.target.bulk_insert("shadow_table", transformed)
# 4. Throttle: Check replication lag/DB load
if self.system_load_too_high():
sleep(adaptive_delay)
def transform_row(self, row):
# Apply schema logic here (e.g., splitting a column, encrypting PII)
return row
2. Safety Layer: Invariant Checks
We cannot trust that the code ran perfectly. We must mathematically verify that the source and target represent the same reality.
A. Structural Invariants
Before starting, verify that indexes match and constraints are compatible.
Example: If Source has UNIQUE(email), Shadow must have it to prevent duplicates during parallel copy.
B. Data Invariants (Sampling)
During the chunking phase, every N chunks, run a verification probe.
Checksum Check:
Run CRC32 or MD5 aggregation on a specific range in both DBs.
sql
-- Source
SELECT BIT_XOR(CRC32(CONCAT(col1, col2))) FROM source WHERE id BETWEEN 100 AND 200;
-- Target
SELECT BIT_XOR(CRC32(CONCAT(col1, col2))) FROM shadow WHERE id BETWEEN 100 AND 200;
If mismatch →HALT.
Business Logic Invariants:
Run SQL queries that assert logical truths.
Example: "Total order amount in Shadow must equal sum of line items."
Example: "No user in Shadow should have a NULL created_at date."
3. Risk Mitigation: The Canary Deployment
We do not want to run the migration on 100% of the data immediately. We apply the "Canary Release" concept to data processing.
The Canary Phase
Select Canary Set: Pick 1% of the data (e.g., specific user IDs or a specific time range).
Run Migration on Canary: Execute the chunking/parallel runner only for this set.
Smoke Tests:
Run the application's read-only integration tests against the Shadow DB.
Run the Invariant Checks specifically on the Canary set.
Observability:
Did DB CPU spike?
Did replication lag increase?
Were there deadlocks?
If Canary passes → Resume migration for remaining 99%.
If Canary fails → Drop Shadow Table, fix code, retry.
4. The Cutover (The "Swap")
Once the Shadow table has caught up (bulk copy finished) and is streaming live updates (via triggers or CDC), we perform the cutover.
Safety Mechanism: We must ensure no writes are lost in the split second between renaming tables.
The Algorithm (Atomic Swap):
Lock: Briefly lock the original table (write-lock) to drain remaining pending queries.
Rename: In a single transaction:
sql
RENAME TABLE original TO archive, shadow TO original;
(This operation is typically metadata-only and very fast, < 1 second).
Unlock: Release locks.
Cleanup: Drop the archive table (or keep for rollback).
5. Summary Workflow
Here is the state machine for the Runner:
INIT:
Create shadow_table.
Setup CDC/Triggers to sync new writes from original→shadow.
CANARY:
Chunk 1% of IDs.
Run parallel backfill.
Stop.
Run Invariant Checks.
Decision: If Pass →MIGRATE. If Fail →ABORT.
MIGRATE:
Chunk remaining 99%.
Parallel Workers run bulk copy.
Auto-throttle if DB load > Threshold.
Continuous Invariant Sampling (1 in 100 chunks).
VERIFY:
Compare MAX(id) and COUNT(*) of Source vs Shadow.
Check Replication Lag = 0.
CUTOVER:
Acquire write lock.
RENAME TABLE.
Release lock.
POST-CHECK:
Run application smoke tests.
Success.
Key Technical Safeguards
Backpressure / Throttling: The runner must actively monitor the database's "Stall Ratio." If the DB slows down, the runner pauses chunk processing.
Idempotency: The chunk copy SQL must use INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE. This allows retrying failed chunks without creating duplicate data.
Lag Awareness: If using replication, the runner must check Seconds_Behind_Master. If lag exceeds 10s, stop all migration workers immediately to let the replicas catch up.