Proposing migration verifier design
The user is asking about designing a canary database migration verifier using techniques like shadow reads and writes. I think I should propose an architecture that includes traffic mirroring, dual-write, and error budgets. It sounds like they are looking for a reliable way to ensure data consistency.
I might need to clarify some details, but I can offer a general plan, including pseudocode for diffing and operational steps for verifying data correctness during the migration from one database system to another.Structuring migration verifier details
I'm outlining the details for verifying a database migration. For reads, I plan to serve from the source while shadow reading the same query on the target. This involves making sure both have consistent snapshots at the same log sequence number. I’ll compare results after canonicalization and utilize statement capture for parameters.
I need to address how to handle mismatches automatically, ensuring safe rollouts, and establishing audit logs. It’s important to ensure clear goals, a high-level flow, and various implementation options for shadow writes.Finalizing design blueprint
I’m preparing the details for implementing shadow reads and a diff engine. It includes aspects like query capture, read consistency, and determinism. I’ll also lay out automated abort rules and practical tips to avoid pitfalls related to sequence differences, collation, and float precision.
I need to keep things concise, focusing on a design blueprint with bullet points, and consider highlighting the "Verifier" service, which will operate separately from the production path. Asynchronous shadow reads will run in the background, ensuring that the original data remains unaltered.Considering microservices design
I'm thinking about how to approach microservices better. Instead of relying on raw SQL, it might be more effective to use "compare at boundaries" within domain models. This allows for a more structured way of handling data comparisons while ensuring that our architecture remains clean and maintainable. It's an interesting consideration, and I feel it could lead to more efficient handling of data interactions in a microservices environment. Let's explore this further!
Below is a practical blueprint for a canary DB migration verifier that uses shadow reads/writes, diffing, and automated aborts. It’s written generically (works for MySQL→Postgres, self-hosted→cloud, sharding changes, schema refactors, etc.).
1) Core goals
- Correctness: New DB returns the same logical results as old DB (within defined tolerances).
- Safety: Verification must not break prod (bounded overhead, no side effects).
- Actionability: When there’s a mismatch, you can quickly answer what diverged and why.
- Automation: Progressively ramp canary; automatically halt/rollback on error budget breaches.
2) High-level architecture
Components
- Primary path (prod): App continues to read/write the source DB initially.
- Shadow Writer: Replays prod writes to the target DB (async or sync depending on phase).
- Shadow Reader: Replays sampled reads against target DB.
- Diff Engine: Canonicalizes and compares results; classifies mismatches.
- Verifier Control Plane: Sampling policy, allow/deny lists, tolerances, abort rules, feature-flag toggles.
- Evidence Store: Stores mismatches, query context, row-level diffs, and “known differences” suppressions.
- Metrics/Alerts: mismatch rate, severity, lag, latency overhead, error types, top offenders.
Data flow (typical)
- App performs write/read on source.
- Capture the operation (SQL+binds or domain-level request) into a verification stream.
- Shadow subsystem replays operation on target.
- Compare outputs (reads) or compare resulting state (writes).
- If mismatch rates exceed thresholds, automatically abort ramp / disable shadowing / revert traffic.
3) Shadow writes (safe ways to do it)
Shadow writes are the hardest part because they touch state.
Option A (recommended): Outbox + replay (strong consistency, low coupling)
- In the same transaction as the source write, insert an outbox event describing the logical mutation:
- entity keys
- mutation type
- normalized payload
- source commit timestamp / LSN
- A replay worker consumes outbox and applies to target.
Pros: deterministic, retryable, debuggable, avoids dual-write inconsistencies.
Cons: requires plumbing an outbox.
Option B: CDC-based replay (low app changes)
- Use binlog/WAL capture (Debezium, native CDC) → transform → apply to target.
Pros: minimal app changes.
Cons: harder to map complex transformations; can get tricky with schema drift or non-deterministic columns.
Option C: In-app dual write (fast but riskier)
- App writes to source, then writes to target.
Must-have safeguards:
- idempotency keys (per logical mutation)
- retry safety
- clear failure policy (don’t block prod on target failure during early phases)
Pros: quick to implement.
Cons: failure modes (partial writes, ordering), transactional mismatch.
Write verification strategy
You can verify writes by either:
- State-based checks: after applying the write, read the affected entity from both DBs and diff.
- Invariant checks: counts, constraints, derived fields, checksums.
- Periodic reconciliation: background job compares tables/partitions by key-range.
In practice: do state-based on canary + periodic reconciliation for coverage.
4) Shadow reads (how to replay and compare)
Capturing reads
Choose one:
- Capture domain-level queries (preferred): e.g.,
GetUser(id=123) → run equivalent queries on both DBs. Less fragile than raw SQL.
- Capture raw SQL + binds: replay the exact SQL if dialect-compatible, or map to target SQL via a translation layer (often painful across engines).
Consistency problem (the #1 source of false mismatches)
A shadow read must compare source vs target at an equivalent point in time.
Common approaches:
- Read-your-writes token: attach a “source commit position” (LSN/GTID/timestamp) to the request; only compare once the target has replayed up to that position.
- Lag-aware compare: if target replication lag > X, skip/queue the comparison instead of declaring mismatch.
- Entity-level gating: only compare entities known to be fully migrated/backfilled.
Determinism rules
Before diffing, normalize away expected non-determinism:
- ordering (sort rows by stable keys)
- floating point tolerances
- timestamps with different precision
- collation/case-folding differences
- generated IDs/sequence values (compare logical relationships, not raw sequences)
- pagination semantics (ensure stable ordering keys are included)
5) Diffing: what “equal” means
Canonicalization pipeline
For read results (rows/JSON):
- Project to comparable fields (exclude “known-different” fields).
- Normalize types (int vs bigint, decimal scale, timezone normalization).
- Sort arrays/rows by primary key (or declared stable key).
- Canonical serialize (stable JSON encoding).
- Compare:
- exact match on canonical form, OR
- per-field rules (tolerances, regex normalization), OR
- hash match (fast path) + deep diff on mismatch (slow path).
Useful diff outputs
Store structured evidence:
- request context (tenant/user/request id)
- query name + parameters
- source result digest + target result digest
- row-level diff (missing/extra keys, field mismatches)
- classification tag:
REPLICATION_LAG
SCHEMA_MAPPING
NULL_SEMANTICS
COLLATION
BUG_TARGET_QUERY
BUG_SOURCE_QUERY (yes, you find these)
NON_DETERMINISM
Sampling strategy
Start narrow, expand:
- 0.1% of traffic for reads, 100% of writes in shadow (if safe), or 1–10% writes if expensive.
- Prefer sampling by tenant/account so you get coherent datasets.
6) Automated aborts / circuit breakers
What you can automatically abort
- Ramp-up (stop increasing canary percentage)
- Shadowing (disable shadow reads/writes to protect target and prod)
- Serving from target (if you’ve started reading from target for canary users, revert them)
Typical abort rules (example)
Define a rolling window (e.g., 5 minutes) + a longer window (e.g., 1 hour):
Hard stops (immediate):
- any mismatch tagged
DATA_LOSS / MISSING_ROWS above N events
- target write failures > X/min
- target replication lag > Y seconds for Z minutes (prevents bogus diffs and indicates instability)
Soft stops (error budget):
- mismatch_rate > 0.1% over 10k comparisons
- p95 verification overhead > 20ms added latency (if on-request)
- diff backlog age > 10 minutes (system can’t keep up)
Automation mechanics
- Put canary % and shadow toggles behind a feature flag system.
- Verifier emits an “abort” decision to:
- feature flag service
- deployment controller (Argo/Spinnaker)
- on-call alert with a bundle of top mismatch exemplars
- Require human approval to resume ramp (prevents flapping).
7) Phased rollout plan (battle-tested)
- Backfill + reconciliation (offline):
- bulk copy data
- run key-range checksum comparisons (counts + hash per chunk)
- Shadow writes on (not serving from target):
- replay writes to target
- verify write-applied state for sampled entities
- Shadow reads on (still serving from source):
- compare read results
- tune canonicalization + allowlists
- Canary reads from target (small tenant cohort):
- serve canary tenants from target
- still do shadow reads to source for verification (reverse direction)
- Ramp up → majority → full cutover
- Post-cutover verification window:
- keep dual path for a limited time to catch long-tail issues
8) Common pitfalls (and how to avoid them)
- Transaction isolation differences: compare at entity boundaries, use commit-position gating.
- Default values & null semantics: explicitly map defaults; treat absent vs null carefully.
- Collation/text comparison: normalize or align collations; beware
LIKE behavior changes.
- Timezones/precision: normalize to UTC; define rounding rules.
- Pagination without stable ordering: add a deterministic tie-breaker key or skip comparing.
- Side effects: ensure shadow replay does not trigger external side effects (triggers, jobs). Use feature flags or target-side guards.
9) Minimal “config surface” you’ll want
- Sampling rules: by endpoint/query name, tenant cohort, %.
- Compare rules per query/entity:
- stable sort keys
- excluded fields
- tolerances
- “known differences” suppressions with expiry
- Abort thresholds and severity mapping
- Lag gating thresholds
- Target capacity budgets (QPS limits) for shadow reads
If you share:
- source/target DB engines,
- whether schema changes are involved, and
- whether you can add an outbox/CDC,
…I can propose a more concrete design (including exact consistency tokens to use, and an implementation outline for diffing + abort logic).