0) Target outcome (what “good” looks like)
A shadow-traffic harness lets you:
- Mirror production requests to the new platform (shadow) while the old platform remains authoritative.
- Prevent any side effects in shadow (no emails sent, no writes to prod data stores, no external charges).
- Compare outcomes (status codes, payload semantics, latency) and surface actionable discrepancies.
- Provide clear rollback triggers, stakeholder dashboards, and rehearsed runbooks for cutover.
1) Reference architecture (high level)
Authoritative path
Client → Edge/LB/API GW → Old Platform → Response to client
Shadow path
Same request (mirrored) → Shadow Router → New Platform (isolated deps) → Capture response/metrics → Diff engine → Alerts/Dashboards
Core components:
- Mirroring point (API gateway / service mesh / sidecar / tap)
- Shadow router (fanout + sampling + backpressure)
- Sanitizer (PII/token scrubbing + deterministic tokenization)
- Shadow environment (isolated DBs, queues, third-party stubs)
- Capture & correlation (trace/span IDs, request IDs)
- Diff engine (schema-aware comparison + tolerances)
- Telemetry & dashboards (SLIs + diff KPIs)
- Rollback controller (thresholds + automation hooks)
- Runbooks + rehearsal plan (game days)
2) Traffic mirroring design (options + recommended pattern)
2.1 Where to mirror
Choose the earliest point that still preserves identity/context and is operationally stable.
Option A: API Gateway / Ingress mirroring (common)
- Pros: central, easy to control sampling, less code change
- Cons: may miss internal service-to-service calls; payload limits; streaming can be tricky
Option B: Service mesh (Envoy/Istio/Linkerd)
- Pros: mirrors service-to-service, per-route policy, rich telemetry
- Cons: more moving parts; needs care for mTLS identities and headers
Option C: Application-level dual write/dual call
- Pros: best semantic control; can do “dry-run” headers
- Cons: code changes; risk of performance impact
Option D: Async replay (log/Kafka-based)
- Pros: zero latency impact; great for batch verification
- Cons: not true real-time; can drift from real request timing
Recommended baseline: Gateway or mesh mirroring + asynchronous diffing, with the shadow call not on the critical path.
2.2 Mirroring mechanics (what to implement)
Key requirements:
- Non-blocking fanout: client response must never wait for shadow.
- Sampling controls: start at 0.1–1%, ramp up; per-route and per-tenant allowlists.
- Backpressure: if shadow is slow/unhealthy, drop shadow traffic (do not overload prod).
- Correlation: inject/propagate
X-Request-Id / traceparent and a X-Shadow-Id.
A typical flow at the mirror point:
- Forward request to old platform as usual.
- Clone request → push to shadow router (queue/buffer).
- Shadow router sends to new platform with:
X-Shadow-Traffic: true
X-Shadow-Mode: read-only|dry-run
X-Shadow-Request-Id: <uuid>
- Capture shadow response + timing.
- Diff engine compares with authoritative response asynchronously.
2.3 Handling writes safely (the hard part)
You have three patterns; pick per endpoint:
Pattern 1: Read-only endpoints
- Mirror freely (GET/list/search) with sanitization.
Pattern 2: Write endpoints with “dry-run” support (best)
- New platform must implement:
- validation + business logic execution
- generate predicted effects
- but do not commit (or commit to isolated DB)
- Return
200 OK with a dry-run result or metadata headers.
Pattern 3: Write endpoints via isolated dependencies
- Shadow environment uses:
- separate DBs
- separate queues/topics
- stubbed third-party integrations (payments, email, SMS)
- Still risky if any shared resource remains (caches, shared IDs, rate-limited vendors).
Rule: If you cannot guarantee “no side effects,” do not mirror writes—use record/replay into a sandbox instead.
2.4 Edge cases you must account for
- Streaming (SSE/websocket/gRPC streaming): mirror metadata only, or sample and replay offline.
- Non-determinism: timestamps, randomized IDs, “top N” results ordering—handle in diff logic.
- Auth context: ensure shadow uses a shadow identity or sanitized tokens; never forward raw session tokens to non-prod.
- Rate limits: shadow must have independent quotas so it can’t burn prod/vendor quotas.
3) Data sanitization & privacy controls
3.1 Sanitization goals
- Shadow must be usable for functional comparison.
- Shadow must not store or expose regulated data unnecessarily.
- Sanitization must be deterministic where needed (to preserve join keys, grouping, and idempotency).
3.2 What to sanitize
- Direct identifiers: name, email, phone, address
- Sensitive identifiers: SSN/National ID, passport, driver’s license
- Auth secrets: cookies, bearer tokens, API keys, CSRF tokens
- Payment: PAN, CVV, bank acct numbers
- Free text: support tickets, notes (requires DLP scanning)
3.3 Techniques (use a combination)
- Allowlist extraction (preferred): only forward needed fields; drop everything else.
- Field-level redaction: replace with
"[REDACTED]".
- Deterministic tokenization:
token = HMAC_SHA256(k, value) to preserve equality checks without exposing raw value.
- Format-preserving masking: keep shape but not content (e.g., emails
u***@example.com).
- Structured logging discipline: never log raw headers/payloads by default; use explicit “safe fields.”
3.4 Implementation guardrails
- Centralize policies in a sanitization schema per route:
- JSONPath rules for request/response fields
- header allowlist/denylist
- Add DLP scans on captured payloads (sampled) and block on violations.
- Encrypt captured artifacts at rest; short TTL (e.g., 7–14 days).
- Access control: least privilege; audit logs for who viewed diffs.
4) Discrepancy detection & alerting (make diffs meaningful)
4.1 What to compare (layers)
- Transport: status code class, headers (allowlisted), content-type
- Schema: response shape, required fields, enum values
- Semantics (domain-level): totals match, item counts, eligibility decisions, pricing, authorization outcomes
- Performance: p50/p95/p99 latency deltas, timeouts, tail amplification
- Stability: error-rate deltas by endpoint/tenant
4.2 Diff engine design
- Store a paired record:
- request (sanitized)
- authoritative response (sanitized)
- shadow response (sanitized)
- metadata: route, tenant, versions, timestamps, latency
- Canonicalize before comparing:
- sort arrays when order is not meaningful
- ignore volatile fields (timestamps, request IDs, generated links)
- numeric tolerance (epsilon) for floats/monetary rounding rules
- Support rules per endpoint:
- “ignore fields” list
- “key fields must match” list
- custom comparator hooks (e.g., compare as sets)
4.3 Discrepancy metrics (KPIs)
Track at minimum:
- Match rate:
% requests with acceptable equivalence
- Hard mismatch rate: semantic mismatch
- Soft mismatch rate: expected differences (known gaps) / tolerances exceeded
- Shadow error rate vs authoritative error rate
- Latency delta: p95 and p99 difference
- Top mismatch reasons (bucketed)
4.4 Alerting strategy (avoid noise)
Alert on rates and regressions, not single diffs.
- Page/urgent:
- Shadow crash loops affecting harness (can’t measure)
- Massive divergence spikes after a deployment
- Ticket/async:
- mismatch rate > threshold for N minutes on critical routes
- latency delta increases beyond threshold
- Always include:
- link to diff samples
- recent deployments/feature flags
- suspected rule category (schema vs semantic)
5) Rollback triggers (define before you start)
5.1 Cutover phases (recommended)
- Shadow only (0% live): validate harness + diffing
- Canary (1–5% live): new platform serves real traffic for a slice
- Ramp (10% → 25% → 50% → 100%)
- Stabilize (100% + shadow old for a short window if desired)
- Decommission old
5.2 Rollback trigger categories
Define explicit thresholds per tier (critical vs non-critical endpoints).
Functional
- mismatch rate (hard) > X% for Y minutes on critical endpoints
- authorization/entitlement mismatches > very small threshold (often near zero)
Reliability
- new error rate exceeds old by > Δ for Y minutes
- elevated timeout rate or saturation (CPU/mem/connections)
Performance
- p95 latency exceeds old by > Δ ms for Y minutes
- p99 tail exceeds SLO or shows step change after release
Business
- checkout/payment success drops
- conversion/engagement drops beyond agreed guardrails (if measurable quickly)
5.3 Automation
- Rollback controller can:
- flip routing weights (gateway/mesh)
- disable feature flags
- halt progressive delivery pipeline
- Require a “two-key” approach for large rollbacks if your org needs it, but pre-authorize who can execute quickly.
6) Stakeholder dashboards (who needs what)
6.1 Executive / program dashboard (migration confidence)
- Traffic coverage: % routes mirrored, % traffic sampled, % tenants included
- Match rate trend (7d/24h), hard mismatch trend
- Open discrepancy backlog by severity
- Cutover readiness checklist completion
- Risk register items and owners
6.2 Engineering / SRE dashboard (operational truth)
- SLIs side-by-side: availability, error rate, latency p50/p95/p99
- Saturation: CPU/mem, GC, thread pools, DB connections, queue lag
- Shadow harness health: mirror drops, sanitizer errors, diff pipeline lag
- “Top endpoints by mismatch rate” + drill-down to diff samples
- Deploy markers (old/new + harness components)
6.3 Product / domain dashboard (semantic correctness)
- Business invariants:
- totals/prices/taxes discrepancies
- eligibility decisions mismatch
- search result relevance deltas (if applicable)
- Breakdown by:
- tenant/region
- app version
- feature flag state
7) Runbooks + rehearsal plan (don’t skip this)
7.1 Core runbooks to write
- Harness failure: mirroring stopped, diff lag rising, sanitizer misconfigured
- Shadow platform unhealthy: high 5xx, timeouts, dependency failures
- Mismatch spike: triage workflow + rule tuning + rollback decision tree
- Canary rollback: step-by-step commands, verification, comms
- Data incident: PII leak response, artifact purge, access review, audit trail
Each runbook should include:
- Symptoms → dashboards to check
- Immediate mitigations (throttle sampling, disable routes, drop shadow)
- Owner/rotation + escalation path
- Verification steps and “all clear” criteria
- Post-incident follow-ups (diff rule updates, tests, policy changes)
7.2 Rehearsals (“game days”)
Run at least these drills in a pre-prod and then in prod with safe sampling:
- Shadow overload: force shadow to slow down; confirm drops don’t affect prod
- Diff pipeline lag: pause consumers; confirm alerts and recovery
- Intentional mismatch injection: deploy a known-breaking change; validate detection and triage
- Rollback dry-run: flip weights to old and back (during low risk window)
- Sanitization regression: introduce a forbidden field in a response; validate DLP block + incident workflow
Define success criteria per rehearsal:
- time to detect
- time to mitigate
- correctness of comms
- no customer impact
8) Practical build plan (phased deliverables)
Phase 1 — Harness skeleton (1–2 weeks)
- Mirror point configured (gateway/mesh) + sampling + non-blocking
- Correlation IDs propagated
- Shadow router with backpressure/drop metrics
- Basic telemetry (request counts, shadow errors, mirror drops)
Phase 2 — Sanitization + capture (1–3 weeks)
- Route-based sanitization policies
- Secure storage with TTL
- DLP checks + deny rules
- Access control + audit logs
Phase 3 — Diff engine (2–4 weeks)
- Canonicalization + per-route rules
- Mismatch classification (schema/semantic/allowed)
- Dashboards + alert rules
Phase 4 — Cutover tooling (ongoing)
- Progressive delivery hooks + rollback controller
- Business KPI guardrails (where measurable)
- Full runbooks + rehearsals
9) Key design choices to settle early (questions for you)
If you answer these, the design can be made much more concrete:
- What is the “platform” being migrated (API layer, microservices, data store, monolith → services)?
- What protocols are in scope (HTTP/REST, gRPC, websockets)?
- Do you need to mirror internal service-to-service traffic, or only edge requests?
- Which endpoints perform writes, and can the new platform support dry-run?
- Data constraints: any PCI/PHI/GDPR obligations that require strict minimization?
- What’s your observability stack (OpenTelemetry, Prometheus, Datadog, Splunk)?
- What progressive delivery tool do you use (Argo Rollouts, Flagger, Spinnaker, LaunchDarkly)?
If you share your stack (gateway/mesh, languages, observability, and whether you can do dry-run writes), I can propose a concrete architecture with specific components, configs, and a sample discrepancy rule set per endpoint class.