The user wants a design for a "zero-downtime schema migration kit."
Key components requested:
- Expand/Migrate/Contract (EMC) pattern implementation.
- Verifiers (safety checks).
- Rollback mechanisms.
Deconstruct the Request:
- Goal: Zero-downtime (online) schema changes in a distributed database environment (likely relational, e.g., Postgres/MySQL).
- Pattern: The "Expand-Contract" pattern is the standard for online migrations. The user included "Migrate" in the middle, making it "Expand-Migrate-Contract".
- Kit: This implies a CLI tool, a library, or a framework design. I should structure the response as a technical design document or a project blueprint.
Phase 1: Conceptual Architecture (The "Kit")
- I need to define the interface. Is it a CLI? A library? Let's assume a CLI tool (like
flyway or liquibase but specialized for EMC) wrapping a library.
- I need a state store (to track migration progress).
- I need a workflow engine.
Phase 2: The Expand/Migrate/Contract (EMC) Workflow
- Step 1: Expand. Add new schema elements without breaking the old ones.
- Add column (nullable/default).
- Add table.
- Add trigger/CC (for dual-writing).
- Step 2: Migrate (Backfill). Move existing data to the new structure.
- Chunking updates.
- Throttling (don't kill the DB).
- Step 3: Contract. Remove old schema elements.
- Stop using old code paths.
- Drop old columns/tables.
Phase 3: Verifiers (Safety Net)
- When do we run these? Before, During, After.
- Pre-flight: Permissions, disk space, locks (waiting for locks).
- Sanity: Data consistency (checksums), schema drift detection.
- Performance: Query performance impact.
Phase 4: Rollback Strategy
- This is tricky with EMC. You can't just revert the binary.
- Rollback usually means going backwards through the EMC steps.
- Expand Rollback: If expansion fails, drop the new stuff.
- Migrate Rollback: Revert the backfill? (Hard, usually just fix forward or ignore). Actually, if it's a dual-write scenario, you might need to backfill back to the old column if aborting. Or just stop.
- Contract Rollback: If you dropped the column, you can't rollback easily. You must re-expand.
Phase 5: Detailed Design & Code Structure
I will structure the output as a "Technical Design Document" for a tool called ZenMigrate.
- Architecture: CLI + Execution Engine + State DB.
- The Workflow (The Core Logic):
- State Machine:
IDLE -> EXPANDING -> EXPANDED -> MIGRATING -> MIGRATED -> CONTRACTING -> DONE.
- Key Features (Verifiers):
Assertion: Check data integrity.
Guard: Check load.
- Handling Rollbacks:
- Each phase needs a corresponding "undo" operation.
Refining the "Migrate" step:
The user specifically asked for "Expand/Migrate/Contract". Usually, the "Migrate" part involves two things:
- Code Deployment: Deploy code that writes to both old and new (dual-write).
- Backfill: Update old data to new data.
I need to make sure the "Dual Write" (Trigger or App logic) is part of the Expand or Migrate phase. Usually, it's better to set up triggers in Expand, run Backfill in Migrate.
Drafting the Content - Section by Section:
- Introduction: Define the philosophy (decoupling DB changes from App deploys).
- The 3-Phase Pattern (EMC):
- Expand: Add new column, add triggers (sync old -> new).
- Migrate: Backfill data (old -> new) in batches.
- Contract: Remove triggers, drop old column.
- The Kit Architecture:
- Components: Planner, Runner, Verifier, Logger.
- Verifiers (The "Quality Gate"):
- Examples:
RowCountVerifier, ChecksumVerifier, LatencyGuard.
- Rollbacks: The "Inverse Operation" approach.
- Example DSL/Config: How does the user define this?
- Need a YAML or Code definition.
Self-Correction/Refinement during drafting:
- Critique: Just defining "Drop Column" is dangerous.
- Fix: Emphasize that Contract only happens after the application has stopped querying that column. The migration kit manages the DB; the user manages the App code lifecycle. I must mention the "Four-Step Deployment" context (App v1 -> App v2).
Detailed Workflow Logic (The "Recipe"):
- Scenario: Rename
user_name to full_name.
- Expand: Add
full_name. Add Trigger: ON UPDATE user_name -> update full_name.
- Migrate:
UPDATE users SET full_name = user_name WHERE full_name IS NULL LIMIT 1000.
- Contract: Drop Trigger. Drop
user_name.
Wait, what about the reverse sync?
If the app is still writing to user_name during Expand/Migrate, the trigger covers it. If the app writes to full_name (the new column), do we need a trigger back to user_name?
- Strict EMC: Yes, until the very end, you maintain compatibility.
- Optimized EMC: If the app only writes to the new column after the deploy, you don't need the reverse trigger. But the prompt implies a generic kit. I will assume the kit sets up bidirectional syncing or at least provides hooks for it.
Let's focus on the "Kit" aspect:
The user wants a design for the toolkit, not just the theory.
So, I need to define:
- The Interface:
migration.yaml
- The Verifier Hooks:
pre_verify, post_verify.
- The Execution Engine: How it handles errors.
Formatting: Use clear headers, code blocks for YAML/Python examples, and diagrams (Mermaid).
Plan:
- High-Level Architecture: State Machine approach.
- The 3 Phases (Detailed): Specific actions for Expand, Migrate, Contract.
- The Verifier System: Hooks for data integrity and performance.
- Rollback Strategy: The "Undo" chain.
- Implementation Example (Pseudo-code/YAML): A concrete scenario (Splitting a column).
Let's write it.
This design outlines a robust, production-grade Zero-Downtime Schema Migration Kit. This kit is designed to decouple deployment from migration, allowing you to change database schemas without causing service interruptions or locking tables.
The core philosophy relies on the Expand-Migrate-Contract pattern, ensuring backward compatibility at every step.
1. Architecture Overview
The kit consists of three logical components:
- The Planner: Analyzes current DB state and application code requirements to generate a safe path.
- The Runner: Executes state transitions (Expand, Migrate, Contract) with throttling and locking mechanisms.
- The Safety Net: Includes Verifiers (pre/post conditions) and the Rollback Engine.
The State Machine
Instead of a linear "up/down," this kit treats a migration as a state machine:
IDLE → EXPANDING → MIGRATING → CONTRACTING → DONE
2. The Migration Lifecycle (Expand / Migrate / Contract)
This pattern allows you to deploy application code that works with both the old and new schemas simultaneously.
Phase 1: Expand (The "Add" Phase)
Goal: Add new elements without breaking the old application version.
- Action: Run
ALTER TABLE to add new columns (nullable only), new tables, or new indexes.
- Constraint: Never remove or rename anything. Never add a
NOT NULL constraint immediately (use a default value or allow nulls).
- Triggers (Optional): If migrating data format (e.g., splitting a
full_name column into first and last), create database triggers to keep old and new columns in sync during the transition.
Phase 2: Migrate (The "Backfill" Phase)
Goal: Massage existing data to fit the new structure.
- Dual-Write: The application begins writing to both the old and new schema structures.
- Backfill: A background process iterates over the table in batches (chunks) to update existing rows.
- Feature: Smart Chunking. The runner adapts chunk size based on replication lag or CPU load.
- Feature: Shadow Mode. Run the backfill in "audit only" mode to verify data transformation logic before applying it.
Phase 3: Contract (The "Remove" Phase)
Goal: Clean up unused legacy elements.
- Pre-requisite: Verification that no application instances are reading/writing to the old columns.
- Action: Drop triggers, drop old columns, rename columns to final names (if aliases were used).
- Finalization: Database schema now matches the new application code exclusively.
3. The Verifiers (Safety Checks)
Verifiers are assertions that run before and after specific phases. If a verifier fails, the migration halts or pauses for manual intervention.
A. Pre-Flight Verifiers
Run before any execution begins.
- Identity Check: Is this the primary database? (Prevent running migrations on read replicas directly).
- Version Compatibility: Does the current DB version match the expected starting version?
- Disk Space: Is there enough free space for temporary tables/indexes?
B. Sanitize Verifiers
Run during the "Migrate" phase.
- Checksum Validation: Compare MD5 hashes of data in old vs. new columns for a random sample of rows.
- Null Check: Ensure no unexpected NULLs exist in critical fields that were just migrated.
- Constraint Check: Verify foreign keys still hold integrity after data movement.
C. Performance Verifiers (Live Monitoring)
Run continuously during long-running operations.
- Replication Lag Monitor: If DB lag > X seconds, pause the migration thread immediately.
- Lock Wait Monitor: If the migration waits for a lock > Y seconds, abort to prevent blocking user traffic.
4. Rollback Strategy
Zero-downtime migrations require Code-Level Rollbacks distinct from Schema Rollbacks.
Strategy A: The "Reverse Step" (Code Rollback)
If you detect a bug in the application logic during the migration window:
- App Rollback: Deploy the previous version of the application code.
- Result: The system continues running. Since we are in the "Expand/Migrate" phase, the old code still works perfectly with the expanded schema (old columns still exist).
- Cleanup: Once stable, you can execute a "Contract-Rollback" migration to drop the new (unused) columns if desired.
Strategy B: The "Undo" (Schema Rollback)
If the migration itself corrupted data or the schema change broke the DB engine:
- Expand Undo:
DROP COLUMN new_col (Safe, as it wasn't used yet).
- Migrate Undo: This is hard. If you backfilled data, you need a script to revert the transformation logic.
- Contract Undo: Impossible (Zero-downtime). If you dropped a column, the data is gone. You must restore from a snapshot (PITR).
5. Implementation Kit (Design Spec)
Here is a design for the configuration file and the CLI interface.
The Configuration (migration.yaml)
version: 1
name: "split_user_name_column"
description: "Split 'full_name' into 'first_name' and 'last_name'"
steps:
- phase: EXPAND
actions:
- type: ADD_COLUMN
table: users
column: first_name
definition: "VARCHAR(255)"
- type: ADD_COLUMN
table: users
column: last_name
definition: "VARCHAR(255)"
- type: ADD_TRIGGER
name: sync_names
logic: |
ON UPDATE OF full_name
SET first_name = SPLIT_PART(NEW.full_name, ' ', 1)
- phase: MIGRATE
strategy: CHUNKED_BACKFILL
config:
table: users
chunk_size: 1000
throttle_ms: 50
sql: |
UPDATE users
SET first_name = SPLIT_PART(full_name, ' ', 1),
last_name = SPLIT_PART(full_name, ' ', 2)
WHERE id BETWEEN :start_id AND :end_id
verifiers:
- type: SAMPLE_CHECKSUM
sample_rate: 0.01
expected_logic: "concat(first_name, ' ', last_name) == full_name"
- phase: CONTRACT
actions:
- type: DROP_TRIGGER
name: sync_names
- type: DROP_COLUMN
table: users
column: full_name
The CLI Interface
# 1. Plan and Verify
$ migrate plan --file migration.yaml
> Plan generated: 3 steps, estimated time 45 mins.
# 2. Run the Expansion (No downtime)
$ migrate run --phase expand
> [OK] Columns added. Triggers active.
# 3. (User Action) Deploy Application Code v2.0 (Dual-Write logic)
# 4. Run the Migration (Backfill)
$ migrate run --phase migrate --throttle auto
> Backfilling... 10%... 20%... [PAUSED] Replication lag high...
> Resuming... 100%.
> [VERIFY] Checksum passed.
# 5. (User Action) Verify App v2.0 is stable.
# 6. Run the Contraction
$ migrate run --phase contract
> [OK] Legacy columns removed.
Summary of Best Practices
- Nullable Columns First: Add columns as nullable. Add constraints (NOT NULL) in the next deployment cycle after data is populated.
- Small Transactions: Never run a single
UPDATE on 10 million rows. Always process in chunks of 1,000–5,000 rows with pauses.
- Orphan Detection: The kit should detect if an "Expand" step was run but the application code wasn't updated, alerting the user to finish the migration.