Description
1. Background & motivation
- Reliability: All of Orders runs in us-east-1 on a single Postgres 15 primary with 2 read replicas. During INC-2291, a 3h12m regional outage, checkout was completely down, costing about $1.2M in GMV and roughly 4,800 support tickets.
- Latency: EU users make up 38% of traffic. Their p95 checkout latency is 920 ms against 210 ms for US users, and about 70% of that gap is cross-Atlantic round trips.
- Compliance: Under the new EU contracts (LEGAL-88), PII for EU customers must be stored and processed in the EU from Q3 onward. Missing that deadline puts 3 enterprise renewals worth about $4M ARR at risk.
- Scale: The current primary peaks at 68% CPU, and write volume is growing 9% month over month. Vertical scaling runs out in about 2 quarters.
2. Goals
| # | Goal | Target |
| G1 | Survive full loss of a region | RPO ≤ 5s, RTO ≤ 60s |
| G2 | EU checkout latency | p95 < 300 ms |
| G3 | Data residency | 0 EU PII persisted outside eu-west-1 |
| G4 | Payment correctness | 0 double charges and 0 lost orders, including during failover |
| G5 | Headroom | Each region carries 100% of global load at 1.5× current peak |
3. Non-goals
- Multi-region search, recommendations or the analytics warehouse (tracked in a separate epic)
- A third region (the design must allow N regions, but only 2 are built)
- Changes to how the mobile app talks to the API, beyond honoring redirects
- Moving off Postgres
4. Current architecture
Client → CloudFront → ALB (us-east-1) → orders-api (EKS, 24 pods)
↘ billing-svc → Stripe
orders-api → Postgres primary (r6g.4xl) → 2 read replicas
orders-api → Redis (sessions, cart) → SQS (order events) → fulfillment
Known pain points:
orders.id is a BIGSERIAL
- The cart lives only in Redis
- Billing retries rely on the payment_intent ID and no client-supplied idempotency key, so a duplicate charge can happen
5. Proposed architecture
Client → Global LB (geo + affinity) ─┬─ us-east-1: gateway → orders-api → PG (US shard)
└─ eu-west-1: gateway → orders-api → PG (EU shard)
PG ⇄ Debezium → Kafka (regional) ⇄ MirrorMaker2 ⇄ Kafka (other region)
Outbox → billing-svc (regional) → Stripe (idempotent)
Failover controller: 3 observers (use1, euw1, usw2 tiebreaker)
5.1 Data partitioning
- Add
customers.home_region ENUM('us','eu'), which is immutable except through the region-migration flow (§5.6).
- Every order-scoped table (
orders, order_items, payments, shipments, addresses) is homed by customer.
- EU PII never leaves the EU. The US region only receives a redacted projection: order ID, status, totals and a hashed customer reference, used for global ops dashboards.
5.2 Identifiers
- IDs become ULIDs with a region prefix:
us_01HF… / eu_01HF….
- During transition, the existing
BIGSERIAL stays as legacy_id, and the public API accepts either format for 2 releases.
- ID generation needs no cross-region coordination.
5.3 Replication & conflict resolution
- Each region is the authoritative writer for its own customers.
- Data flows Postgres → Debezium CDC → regional Kafka, and MirrorMaker 2 copies it to the other region, where it lands as read-only replicas or the redacted projection.
- A write for a foreign-homed customer during normal operation is routed to the home region; it is never written locally.
- When the home region is down, the surviving region may accept writes under a failover lease (§5.5). Those writes are tagged with a fencing epoch and reconciled when the home region comes back:
order.status uses a state-machine merge: the furthest-forward legal state wins, so cancelled beats paid only if a refund was issued
- Scalar fields use last-writer-wins on a hybrid logical clock (HLC)
- Line items use an add-wins observed-remove set (OR-Set)
- Anything that can't be merged automatically goes to
conflict_queue for manual review in an admin UI.
5.4 Payments & idempotency
- The client generates an
Idempotency-Key per checkout attempt; the server falls back to a hash of cart + customer.
- Keys are stored in
idempotency_keys (24h TTL) and replicated synchronously to the other region for payments only, using a lightweight quorum write.
- Billing uses the transactional outbox:
orders and outbox are written in one transaction, and a relay publishes to billing.
- Billing consumers deduplicate on
(idempotency_key, attempt), and Stripe calls pass the same key.
- Reconciler runs every 15 min and compares Stripe charges ↔
payments ↔ orders:
- Drift above $0 pages Payments on-call
- Auto-refund is allowed only for duplicates under $500 that have the same key and the same amount
5.5 Failover
- The failover controller is a small Go service backed by etcd, with observers in use1, euw1 and usw2.
- Deciding that a region is down needs 2 of 3 observers to agree for 20s, and the region must fail its synthetic checkout probe.
- The controller then:
- Increments the epoch
- Grants a write lease to the surviving region
- Flips the global LB weights
- Every DB write includes
epoch, and a trigger rejects any write with a stale epoch. That fencing stops a deposed primary from writing.
- Failback is manual only: an operator runs
failover-ctl failback --region eu once the region has caught up and its lag is below 1s.
5.6 Routing
- The global LB does latency-based geo-routing.
- After login, the JWT carries
home_region, and the gateway proxies requests internally to the home region. Clients never see redirects except on the very first login.
- Anonymous carts are created in the nearest region and moved to the home region at login.
- A customer moving countries triggers an async region-migration job:
- Freeze writes for that customer (< 5s)
- Copy the data
- Flip
home_region
- Unfreeze
- Purge the source after 30 days, per legal
5.7 Caching & sessions
- Redis is regional. Sessions are stateless JWTs, and carts persist in Postgres with Redis as a write-through cache.
- Cache invalidation is driven by CDC events.
6. Migration plan
| Phase | Description | Exit criteria | Rollback |
| 0 | ADRs, threat model, legal sign-off | ADRs approved | n/a |
| 1 | ULID columns, outbox, idempotency keys (single region) | Running in prod for 2 weeks, 0 dup charges | Feature flag off |
| 2 | Stand up eu-west-1 infra, start CDC/Kafka replication | Lag < 1s p99 for 7 days | Tear down |
| 3 | Backfill home_region for 14M customers (billing country → shipping country → IP history → default US) | 99.9% classified; leftovers reviewed manually | Column ignored |
| 4 | Dual-write EU customers to both regions behind a flag; shadow reads with diff logging | Diff rate < 0.001% for 7 days | Flag off |
| 5 | Cut over EU customers in 1% → 10% → 50% → 100% steps | SLOs met at each step for 48h | Shift LB weight back |
| 6 | Purge EU PII from us-east-1, including backups and logs | DPO audit passes | n/a (one-way, needs sign-off) |
| 7 | Enable automatic failover | Game day passed | Controller in manual mode |
7. Observability
- Metrics:
replication_lag_seconds{src,dst}
conflict_queue_depth
failover_epoch
idempotency_hits_total
reconciler_drift_usd
cross_region_proxy_requests_total
- Alerts:
- Replication lag above 2s warns; above 5s for 1 min pages
- Any reconciler drift pages
- Conflict queue above 50 warns
- Dashboards:
- "Multi-region overview" (Grafana)
- Per-region checkout funnel
- Tracing: The OTel span attribute
region.home / region.served makes misrouted traffic visible.
- Logs: EU logs ship to the EU logging cluster only, with a PII scrubber in the log pipeline.
8. Security & compliance
- KMS keys are per region, and EU keys are never usable from the US.
- IAM enforces that US workloads cannot read EU buckets or databases, and this is checked by a CI policy test.
- EU backups stay in eu-west-1, with cross-AZ redundancy only.
- The DPIA must be updated, and the Records of Processing Activities (RoPA) entry amended.
- The threat model must cover:
- Region spoofing through a forged JWT claim
- Replay of idempotency keys
- A compromised MirrorMaker cluster
9. Testing strategy
- Unit and property tests for the merge functions (state machine, HLC, OR-Set), using generated concurrent histories.
- Jepsen-style tests in staging: partitions, clock skew of ±500 ms, and killing the primary in the middle of a transaction.
- Chaos (Gremlin/Litmus), run weekly in staging and quarterly in prod:
- Blackhole an entire region
- Kill Kafka brokers
- Pause MirrorMaker
- Load tests (k6) at 2k RPS sustained and 5k RPS burst, run in each region alone.
- Payment tests run in Stripe test mode with duplicate requests, retry storms and webhook replays injected.
- Residency audit script scans US datastores, logs and backups for EU customer identifiers.
10. Acceptance criteria
- Blackholing eu-west-1 under 2k RPS loses 0 orders, produces 0 duplicate charges, and restores checkout in ≤ 60s
- Same result for us-east-1
- EU p95 checkout latency < 300 ms over 7 days
- Residency audit finds 0 EU PII outside eu-west-1, covering DBs, logs, backups and Kafka
- Replication lag p99 < 1s, with dashboards and alerts live
- Reconciler shows $0 drift for 14 consecutive days after cutover
- Conflict queue sits at 0 in steady state; the admin UI resolves every conflict type
- Runbooks reviewed by SRE; game day passed with an on-call engineer who wasn't on the project
- DPO sign-off and updated DPIA on file
- Old
BIGSERIAL endpoints deprecated, with no traffic for 2 weeks
11. Dependencies
- Infra: EKS cluster, VPC peering / Transit Gateway, and EU account setup (INFRA-412)
- Kafka: self-hosted or MSK, decision in ADR-3
- Stripe: idempotency is already supported, but EU entity routing needs to be confirmed with Finance
- Mobile: app release that sends
Idempotency-Key (iOS and Android, ~3-week release cycle)
- Legal: ruling on whether hashed emails count as PII
12. Risks
| Risk | Likelihood | Impact | Mitigation |
| Split-brain double writes | Med | High | Quorum observers, fencing epochs, DB trigger |
| Kafka ops burden | High | Med | Use MSK; runbooks; dedicated on-call rotation |
| Backfill misclassifies residency | Med | High | Conservative default to EU when signals conflict; manual review queue |
| Latency for travelers | Med | Low | Proxy, plus opt-in region migration |
| Duplicate charges during cutover | Low | High | Idempotency shipped first (Phase 1), reconciler, auto-refund |
| Infra costs ~1.9× | High | Med | Right-size the EU footprint; reserved instances; Finance approved budget |
| Team ramp-up on CRDT/HLC | Med | Med | Spike + ADR + pairing; limit CRDTs to 3 fields |
13. Cost estimate
| Item | Monthly |
| EU EKS + RDS (r6g.4xl + 2 replicas) | ~$18k |
| MSK (2 clusters, 3 brokers each) | ~$7k |
| Cross-region data transfer | ~$3k |
| Observability (extra metrics/logs) | ~$2k |
| Total incremental | ~$30k/mo (compared with $1.2M lost per major outage) |
14. Rollout & communication
- Weekly status in #proj-multiregion, and an exec summary every 2 weeks.
- Support gets a macro and FAQ before Phase 5 covering the "your data is now stored in the EU" message.
- Status-page template prepared for failover events.
- Enterprise customers covered by LEGAL-88 get written confirmation after Phase 6.
15. Open questions
- Should a failed-over region accept new customer signups for the other region, or queue them?
- Should idempotency keys replicate synchronously for payments only, or for every mutating call?
- Does Finance need separate Stripe accounts per legal entity, US Inc vs EU BV?
- Is a 30-day purge window enough, or does legal require immediate deletion?
- Kafka: is MSK Serverless enough at our throughput?
16. Child issues
✓ORD-1ADR-1: Data partitioning & residency3dTO DO
✓ORD-2ADR-2: Conflict resolution (HLC, state machine, OR-Set)5dTO DO
✓ORD-3ADR-3: Kafka hosting & replication topology3dTO DO
✓ORD-4ULID columns, dual IDs in API8dTO DO
✓ORD-5Idempotency-Key middleware + storage5dTO DO
✓ORD-6Transactional outbox + relay8dTO DO
✓ORD-7Payments reconciler + alerting5dTO DO
✓ORD-8eu-west-1 infra (Terraform)10dTO DO
✓ORD-9Debezium + MirrorMaker 2 pipeline10dTO DO
✓ORD-10home_region backfill job + review queue8dTO DO
✓ORD-11Gateway region-affinity proxy8dTO DO
✓ORD-12Failover controller + fencing triggers13dTO DO
✓ORD-13Merge functions + property tests8dTO DO
✓ORD-14Conflict admin UI5dTO DO
✓ORD-15Region-migration job8dTO DO
✓ORD-16Observability: metrics, dashboards, alerts5dTO DO
✓ORD-17Chaos + Jepsen suite10dTO DO
✓ORD-18Residency audit tooling + PII log scrubber5dTO DO
✓ORD-19Runbooks + game day3dTO DO
✓ORD-20US PII purge (Phase 6)3dTO DO
17. Definition of done
- Every sub-ticket is closed and all acceptance criteria are checked
- ADRs merged, runbooks in the wiki, on-call trained
- Postmortem-style retrospective held, with learnings documented
To Do ▾
Details
Type⚡ Epic
Assignee?TBD (Tech Lead, Platform)
Priority⇈P1 – High
Estimate6–8 sprints (~14 weeks)
Componentsorders-apibillinggatewayinfradata-platform
Labelsreliabilitygdprmulti-regionq1-okr
StakeholdersSRE, Payments, Legal/DPO, Customer Support, Finance
Linked issuesINC-2291 (us-east-1 outage postmortem)
LEGAL-88 (EU residency)