# Global A/B Experiment Router Architecture
# =========================================
# Purpose: Edge-distributed router for A/B experiments balancing:
# - Latency: <50ms P99 globally via edge compute (e.g., Cloudflare Workers, Fastly Compute@Edge).
# - Fairness: Sticky bucketing with consistent hashing + stratified sampling.
# - Regulatory: Consent gates, geo-fencing, data residency (e.g., EU data stays in EU).
#
# Core Principles:
# - Stateless edge decisions with eventual sync.
# - Decision tree for routing logic.
# - CRDT-based sync for config/experiment state.
# - Immutable audit logs + shadow testing.
# - Atomic rollbacks via versioning.
#
# Deployment: Multi-region edge network (e.g., 300+ POPs). Central control plane in AWS/GCP/Azure.
1. System Components
[User Request] --> [Edge Node (Global POP)]
|
v
Decision Tree
|
+----------+----------+
| |
Assignment Cache Central Sync (Async)
| |
v v
[Serve A/B Variant] [Config DB + Audit Sink]
- Edge Node: Runs router in WASM/JS (e.g., Cloudflare Workers). Handles 100% traffic.
- Config DB: DynamoDB Global Tables + Redis Cluster (TTL=5min for hot configs).
- Sync Service: Pub/Sub (Kafka/SNS) + CRDTs (e.g., Automerge) for conflict-free merges.
- Audit Sink: Apache Iceberg tables in S3 (partitioned by date/geo/experiment_id).
- Control Plane: API for experiment CRUD (e.g., GraphQL on AppSync).
2. Decision Tree (Core Routing Logic)
Pseudocode for edge-executed tree (latency: ~5ms). Uses MurmurHash3 for deterministic bucketing.
// Decision Tree Function (Edge)
function routeToVariant(userId, geo, consentFlags, requestCtx) {
// Leaf 1: Regulatory Consent Gate (Hard Block, 0.1% traffic)
if (!consentFlags.optInAB || geo in ['restricted_regions']) {
audit('DENIED_REGULATORY', userIdHash, geo);
return 'CONTROL'; // Or geo-default variant
}
// Leaf 2: Experiment Active + Eligibility (Config Cache Miss <0.01%)
const exp = getCachedExperiment(experimentId, requestCtx); // Redis fetch
if (!exp.active || !isEligible(userId, exp.segments, geo)) {
return exp.defaultVariant;
}
// Leaf 3: Fairness - Sticky Bucket (Hash-based, 50/50 split)
const bucket = murmurHash3(userId + exp.salt, exp.totalBuckets) % 100;
const variant = bucket < exp.aPercentage ? 'A' : 'B'; // e.g., 50/50
// Leaf 4: Fairness Check - Strata Balance (Guardrail, sample 1%)
if (shouldSampleForBalance(requestCtx.timestamp)) {
asyncAuditBalanceCheck(userIdHash, exp.id, variant, geo);
}
// Leaf 5: Overrides (Admin/Personalization, <0.01%)
if (exp.overrides[userIdHash]) {
return exp.overrides[userIdHash];
}
cacheAssignment(userIdHash, exp.id, variant, TTL=24h); // Sticky for session+day
audit('ASSIGNED', userIdHash, exp.id, variant, geo);
return variant;
}
// Helpers
function isEligible(userId, segments, geo) {
return segments.device?.includes(requestCtx.device) &&
segments.geo?.includes(geo) &&
!blacklist.has(userId); // Bloom filter for globals
}
function murmurHash3(key, seed) { /* Deterministic 32-bit hash */ }
Balance Guarantees:
- Fairness: ±0.1% deviation via hash salt rotation + post-hoc rebalancing.
- Latency: Tree depth=5, all ops O(1). Cache hit=99.99%.
- Regulatory: Consent from user profile (fetched via JWT/cookie, GDPR-compliant).
3. Data Sync (Global Consistency)
- Model: Eventual consistency with strong reads for configs.
- CRDT Flow:
- Control plane writes experiment config → Pub/Sub topic.
- Edge subscribers merge CRDT delta (e.g., JSON Patch + vector clocks).
- Local cache: LRU (1MB/node) + invalidation on salt/activation change.
- Sync Latency: <1s propagation (Kafka geo-replication).
- Conflict Resolution: Last-write-wins on timestamps; fan-out retries.
- Data Residency: Config shards by geo (e.g., EU-only experiments in eu-west-1).
Control Plane --> Kafka (Multi-Region) --> Edge Fleet (Merge CRDT)
| |
S3 Backup Local Cache (Redis)
4. Auditing (Compliance + Debug)
- Immutable Logs: Every decision → Kafka → Iceberg (schema: timestamp, user_hash, exp_id, variant, geo, latency).
- Anonymized: SHA256(userId), no PII.
- Retention: 90 days hot, 7y cold (regulatory).
- Metrics:
| Metric | Description | Alert Threshold |
|---|
| assignment_balance | %A vs %B per stratum | ±0.5% |
| p99_latency | End-to-end decision | >50ms |
| consent_deny_rate | Regulatory blocks | >1% |
| cache_miss_rate | Sync health | >0.1% |
- Query Interface: SQL on Iceberg (Trino) for analysis:
SELECT variant, COUNT(*) FROM audits WHERE exp_id='abc' GROUP BY geo;.
- Real-time: Prometheus + Grafana dashboards.
5. Rollback (Safety Mechanisms)
- Versioned Configs: Each experiment has
version + shadowMode flag.
- Shadow Rollback: Serve new variant in header only (no user impact), monitor metrics 1h.
- Phased Rollout: Ramp % via
aPercentage (5% → 100%).
- Rollback Flow:
- API:
POST /experiments/{id}/rollback?toVersion=5.
- Pub/Sub blast: Invalidate caches + publish prior CRDT.
- Circuit Breaker: If error_rate >5%, auto-revert to
defaultVariant.
- Audit Delta: Log rollback impact queryable by version.
- Emergency Kill: Global Redis key
EXP_{id}_KILL_SWITCH=true (propagates <100ms).
Rollback Trigger --> Pub/Sub Invalidation --> Edge Reverts to Version N
|
Audit "ROLLBACK_{version}"
Performance & SLOs
| Guarantee | Target | Mechanism |
|---|
| Latency P99 | <50ms | Edge-only decisions |
| Fairness Deviation | ±0.1% | Hash + strata sampling |
| Uptime | 99.99% | Multi-POP failover |
| Compliance | 100% consent | Pre-gate tree leaf |
| Sync Lag | <1s | CRDT + geo-replication |
Implementation Notes
- Open-Source Base: Build on GrowthBook or PostHog + custom edge layer.
- Cost: ~$0.01/1M decisions (edge compute).
- Testing: Chaos engineering (inject cache fails, geo-blocks).
This design deploys production-ready at global scale. Questions?