Explaining blue-green DB migrations
I need to explain blue-green database migrations in a clear yet informative way. I'll cover concepts like expand-migrate-contract, dual-write and compare, cutover window, and rollback processes. I should also touch on how to handle schema changes, data backfills, idempotency, and triggers. Instead of being overly detailed, I’ll provide clear steps and key considerations to help ensure an effective migration process. It's all about making it understandable!
Blue‑green database migrations aim to let you ship schema/data changes with near‑zero downtime by running two “versions” in parallel and controlling when traffic switches. In practice, you combine three ideas:
- Expand → Migrate → Contract (make changes backward/forward compatible)
- Dual‑write + compare (keep two sources in sync and prove correctness)
- A cutover window + rollback plan (controlled switch and safe retreat)
Below is how each works and how they fit together.
1) Expand → Migrate → Contract (a.k.a. parallel/compatible migrations)
This pattern avoids breaking either the “old” app version (blue) or the “new” app version (green) while both run at the same time.
Phase A — Expand
Make additive changes that are compatible with both versions.
Typical expand actions:
- Add new tables/columns (nullable or with safe defaults)
- Add new indexes (concurrently/online if supported)
- Add new enum values in a safe order (often “add first, remove later”)
- Add new constraints in “not valid” / deferred mode, then validate later (Postgres)
- Introduce new write path (new columns populated) without removing old path
Goal: After “expand”, old code still works and new code can work.
Phase B — Migrate
Move data and switch reads/writes gradually.
Typical migrate actions:
- Backfill new columns/tables from old data (batch jobs, idempotent)
- Start writing to both old and new representations (dual‑write)
- Move reads to the new representation once data is complete and verified
- Validate constraints after backfill (and after data is consistent)
Goal: New structures contain correct data and new code can rely on them.
Phase C — Contract
Remove old structures only after you’re confident everything uses the new ones.
Typical contract actions:
- Remove old columns/tables/indexes
- Drop compatibility triggers/dual‑write code
- Tighten constraints (make columns NOT NULL, enforce FK, etc.)
- Remove old code paths
Goal: Simplify and prevent drift, but only when rollback to the old schema is no longer needed.
Why it works: During blue‑green deployments, you must assume both old and new application versions may hit the database concurrently. Expand/contract ensures the DB is compatible with both until cutover is complete.
2) Dual‑write and compare (keeping blue and green consistent)
When you change where truth lives (new table, new column, new database), you often need a period where the system writes to both old and new to keep them synchronized.
Dual‑write approaches
Dual‑write correctness concerns
Dual‑write introduces edge cases; plan for them explicitly:
- Ordering: writes may arrive out of order to the target.
- Partial failure: one write succeeds, the other fails.
- Retries/idempotency: ensure repeated writes don’t duplicate or corrupt.
- Transactional boundaries: a single business transaction might span multiple statements.
Common mitigations:
- Use idempotent upserts keyed by immutable IDs.
- Use an outbox pattern: write a durable event in the source DB transaction; a worker reliably applies it to the target.
- Track replication lag and block cutover until lag is ~0 for required tables.
Compare / verification
You don’t cut over just because you “think” it’s correct—you prove it.
Techniques:
- Row counts and checksums (per table, per partition/time range)
- Spot checks (sample rows by ID)
- Shadow reads: serve from old, also read from new and compare in the background
- Consistency queries: domain invariants (e.g., sums match, no orphan rows)
- Monitoring: error rates, latency, constraint violations, replication lag
3) Cutover window (the controlled switch)
“Cutover” is when you move production traffic from blue to green (or move the app to reading the new schema/database). Even in “zero downtime” systems, you typically schedule a small cutover window to reduce risk.
What happens during cutover
Common sequence:
-
Pre‑cutover freeze
- Ensure backfills are complete.
- Ensure dual‑write/replication lag is acceptable (often zero or bounded).
- Confirm verification checks pass.
-
Traffic switch
- Switch read traffic first (if safe), or switch writers last (often safest).
- Use feature flags / routing (load balancer, service mesh, DNS, app config).
-
Post‑cutover validation
- Monitor errors, latency, DB load, deadlocks.
- Compare key business metrics (orders created, logins, etc.) between periods.
Minimizing the cutover blast radius
- Prefer gradual ramps (1% → 10% → 50% → 100%) for reads, then writes.
- If you must do a “hard switch,” keep the window short and well‑instrumented.
- Avoid long‑running locks during cutover (online index builds, concurrent DDL).
4) Rollback plan (what you do when it goes wrong)
A rollback plan answers: “If the new path fails at 2am, how do we restore service quickly without losing data?”
Rollback is easiest if you haven’t contracted yet (you still have the old schema/data path). The plan depends on whether you cut over reads, writes, or both.
Rollback types
A) Rollback before switching writes (safest)
If green has only been doing shadow reads/verification:
- Simply route traffic back to blue.
- No data reconciliation needed.
B) Rollback after switching reads but not writes
If blue is still the writer of record:
- Switch reads back to old.
- Low risk, because writes stayed on the old system.
C) Rollback after switching writes (hard case)
If green has been writing:
- You need a way to keep blue usable:
- Keep dual‑write active so blue stays up to date; then rollback is just traffic routing.
- Or have a reverse replication plan (green → blue) if green was primary.
- Or accept rollback means restore from backup + reconcile (slow, usually last resort).
Best practice: Do not end dual‑write/replication until you’re past the rollback horizon (e.g., several hours/days of stable operation).
Rollback checklist
A practical rollback plan includes:
- Decision trigger: what metrics/alerts force rollback (error rate, latency, data mismatch)
- Time target: e.g., “rollback within 10 minutes”
- Exact steps: routing change commands, feature flag toggles, config revert
- Data safety: confirm whether any writes could be lost; how to reconcile if needed
- Comms: who is paged, who approves, who executes
- Post‑rollback cleanup: disable green writes, investigate, and preserve evidence
Putting it together (typical end-to-end flow)
- Expand schema in production (compatible with both blue and green).
- Deploy green app that can write/read new fields but still supports old.
- Backfill data to new structures; keep idempotent jobs.
- Enable dual‑write (or CDC/outbox) to keep old+new in sync.
- Run compare/shadow reads until confidence is high.
- Cutover traffic (often reads first, then writes), with a defined window and monitoring.
- Keep dual‑write for a safety period; be ready to rollback by routing back.
- After the rollback window passes and stability is proven, contract: remove old schema/paths.
If you want, describe a concrete migration (e.g., splitting a table, moving to a new DB cluster, changing primary keys), and I’ll map the expand/migrate/contract steps plus a specific dual‑write + rollback design for that scenario.