As Sherlock, I'll design a comprehensive, battle-tested Zero-Downtime Schema Migration Kit (ZDSM Kit) for relational databases (e.g., PostgreSQL, MySQL). This kit follows the Expand/Migrate/Contract (EMC) pattern, popularized by GitHub and tools like gh-ost or Strong Migrations. It ensures:
Zero downtime: Application remains fully operational.
Reversibility: Every step has a rollback.
Verification: Automated checks for data integrity, performance, and app compatibility.
Idempotency: Steps can be re-run safely.
The kit is modular, scriptable (Bash/Python/SQL), and CI/CD-friendly (e.g., GitHub Actions). Assumes:
Dual-write app support (write to old + new paths).
For a canonical example: Adding a non-nullable status column to users table (old implicit status via active bool → new status ENUM('active', 'inactive', 'pending')).
Add new structures without breaking existing app code. App ignores new column initially.
Migration Script (01_expand.sql):
sql
-- Idempotent: Use CHECK constraints or IF NOT EXISTS
ALTER TABLE users ADD COLUMN IF NOT EXISTS status VARCHAR(20) DEFAULT NULL;
ALTER TABLE users ADD CONSTRAINT chk_status_enum CHECK (status IN ('active', 'inactive', 'pending') OR status IS NULL);
-- Index for perf (concurrent to avoid locks)
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_status ON users(status);
App Changes (deploy first or in parallel):
Writes: Continue using active; optionally write to status (dual-write).
Reads: Use old active field.
Rollback (rollback_01.sql):
sql
-- Safe: Data is NULL, no loss
DROP INDEX IF EXISTS CONCURRENTLY idx_users_status;
ALTER TABLE users DROP CONSTRAINT IF EXISTS chk_status_enum;
ALTER TABLE users DROP COLUMN IF EXISTS status;
Phase 2: Migrate (Data backfill + app switch)
Backfill: Copy data from old → new (online, batched).
App Switch: Deploy code to read from new + dual-write (old + new).
Backfill Script (02_migrate.sql, run in batches via Python/Bash):
python
# migrate.py (using psycopg2 or similar)
import psycopg2
conn = psycopg2.connect(...) # Your DB conn
# Batch backfill (e.g., 10k rows at a time)
while True:
cur = conn.cursor()
cur.execute("""
UPDATE users
SET status = CASE
WHEN active THEN 'active'
ELSE 'inactive'
END
WHERE status IS NULL
AND id % 10000 = 0 -- Batch by modulo for progress tracking
LIMIT 10000;
""")
updated = cur.rowcount
conn.commit()
if updated == 0: break
print(f"Backfilled {updated} rows")
App Changes (deploy after backfill starts):
Writes: SET active=..., status=map(active) (dual-write).
Reads: Prefer status; fallback to active if NULL.
Verifier (run continuously):
sql
-- Data parity check
SELECT
COUNT(*) as total,
COUNT(CASE WHEN status IS NULL THEN 1 END) as null_status,
COUNT(CASE WHEN active != (status = 'active') THEN 1 END) as divergence
FROM users;
-- Fail if divergence > 0 or null_status > threshold (e.g., 0.1%)
Rollback (rollback_02.sql):
Stop app dual-write.
Revert backfill: UPDATE users SET status=NULL WHERE ... (batched).
Drop partial index if needed.
Phase 3: Contract (Cleanup after verification)
Remove old structures only after full verification.
Migration Script (03_contract.sql):
sql
-- Make non-nullable (after 100% migration)
ALTER TABLE users ALTER COLUMN status SET NOT NULL;
ALTER TABLE users DROP COLUMN IF EXISTS active; -- Or CASCADE if FKs
DROP INDEX CONCURRENTLY IF EXISTS idx_users_active; -- Old index
Rollback (rollback_03.sql):
sql
-- Restore old column (recreate from new data)
ALTER TABLE users ADD COLUMN active BOOLEAN;
UPDATE users SET active = (status = 'active');
ALTER TABLE users ALTER COLUMN active SET NOT NULL;
ALTER TABLE users DROP CONSTRAINT chk_status_enum; -- Allow NULL temporarily
ALTER TABLE users ALTER COLUMN status DROP NOT NULL;
2. Verifiers (Automated Checks)
Run via verify.sh script at each phase + continuously (e.g., via cron/Lambda).
Kit Script Template (verify.py):
python
#!/usr/bin/env python3
import psycopg2
import sys
def run_query(query, max_error=0):
cur.execute(query)
result = cur.fetchone()[0]
if result > max_error:
print(f"❌ FAIL: {result}")
sys.exit(1)
print(f"✅ PASS: {result}")
# Examples
run_query("SELECT COUNT(*) FROM users WHERE status IS NULL;", 0) # Post-migrate
run_query("""
SELECT COUNT(*) FROM users
WHERE active IS NOT NULL AND status != CASE WHEN active THEN 'active' ELSE 'inactive' END;
""", 0) # Parity
# Perf verifier: Shadow query comparison
run_query("EXPLAIN ANALYZE SELECT COUNT(*) FROM users WHERE status='active';") # Log/monitor
# App verifier: Deploy smoke tests (e.g., via test suite)
# Run app queries on shadow DB replica
Integration:
Pre-deploy: verify.py --phase=expand
Post-deploy: CI job with --phase=migrate
Monitoring: Prometheus/Grafana alerts on divergence.
#!/bin/bash
PHASE=$1
psql -f "rollback_${PHASE}.sql" $DB_URL
# Trigger app config revert (e.g., via Kubernetes rollout)
kubectl rollout undo deployment/app --to-revision=$(kubectl rollout history deployment/app | tail -n2 | head -1 | awk '{print $1}')
echo "Rolled back to phase ${PHASE}"
Safe Rollback Principles:
Expand: Always safe (additive).
Migrate: Partial backfill → reset to NULL.
Contract: Recreate from new data.
Detection: Use triggers for auto-rollback on divergence:
sql
CREATE OR REPLACE FUNCTION migration_trigger() RETURNS TRIGGER AS $$
BEGIN
IF NEW.status != map_from_old(OLD) THEN
PERFORM pg_notify('migration_divergence', TG_TABLE_NAME);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Large Tables: Use gh-ost or triggers for online backfill.
FKs/Indexes: Add with NOT VALID then VALIDATE CONSTRAINT.
Multi-DB: Orchestrate with pglogical or app-level.
MySQL: Swap pt-online-schema-change.
Monitoring: Integrate pg_stat_statements for query regressed detection.
This kit scales to petabyte tables (e.g., GitHub migrates 100GB+ tables). Test on staging replica first. Questions? Provide your schema for a custom migration! 🕵️♂️