The user wants a design for a "global AB experiment router."
The key requirements are:
- Balancing conflicting goals: Latency (must be fast), Fairness (users distributed evenly, consistent experience), and Regulatory Constraints (GDPR, data residency).
- Components: Decision Tree (routing logic), Data Sync (consistency across regions), Auditing (compliance and debugging), and Rollback (safety).
1. Deconstructing the Problem:
- Context: A global company runs A/B tests. When a user makes a request (e.g., opens an app or website), the system must decide which experiment variant (A or B) to show them.
- Constraints:
- Latency: The routing decision happens on the critical path. It needs to be sub-millisecond or very low single-digit milliseconds.
- Fairness: We need statistical significance. Bucketing must be deterministic (same user gets same variant) and balanced (50/50 split, or whatever the weights are).
- Regulatory: EU data needs to stay in EU (GDPR) or be handled specifically. China data needs to stay in China, etc. This impacts where the decision is made and where the logs go.
2. Architectural Approach:
- Centralized vs. Decentralized:
- Centralized: One global endpoint. Good for consistency, bad for latency (if user is in Sydney and server is in Virginia).
- Decentralized (Edge/Regional): Decision logic lives close to the user (CDN edge or regional microservices). Good for latency, harder to sync data.
- Decision: Hybrid. Configuration is global (Control Plane), execution is local (Data Plane).
3. Component Design Details:
-
A. The Decision Tree (The "Brain"):
- How to route? User ID hashing is standard.
- How to handle rules? "If user_country = 'US' and app_version > 10.0 -> Show Experiment X".
- Regulatory Logic: This needs to be part of the tree. "If user_region = 'EU', do not log PII to US analytics."
- Implementation: MurmurHash3 for bucketing (fast, uniform). JSON logic or specific Rule Engine format.
-
B. Data Sync (The "Pipes"):
- Configs are created by data scientists/product managers in a UI. This is the "Source of Truth" (SQL DB).
- These configs need to get to the Edge (the router).
- Mechanism: Pub/Sub (Kafka/Kinesis) -> Propagate to regional clusters (Redis/SQLite/Lua scripts at Edge).
- Latency vs. Consistency: Strong consistency isn't strictly required (it's okay if an experiment starts 2 seconds later in Asia than US). Eventual consistency is the play here.
-
C. Auditing (The "Records"):
- Need to know why a user got Variant B.
- Regulatory constraint: EU data must be logged in EU.
- Mechanism: Asynchronous events. Don't block the user request to write the log. Fire a message to a regional Kafka topic -> Regional Data Lake.
-
D. Rollback (The "Safety Net"):
- If an experiment crashes the app or kills conversion, kill it fast.
- Mechanism: "Kill Switch".
- Implementation: Feature flags. If the router detects high error rates (circuit breaker) OR receives a "Kill" signal from config sync, it falls back to "Control" (Variant A).
4. Drafting the Solution Structure:
I will structure the response into logical sections:
- High-Level Architecture: The "Hybrid Edge-Core" model.
- The Router Logic (Decision Tree & Fairness): Hashing, bucketing, regulatory checks.
- Data Synchronization Strategy: CRDTs, propagation, cold starts.
- Auditing & Compliance: Regional data silos, PII handling.
- Rollback & Safety: Circuit breakers, shadow traffic.
5. Refining the Content (Self-Correction during drafting):
- Initial thought: Use a database lookup for every user to check their group.
- Correction: Too slow. Must use deterministic hashing on User ID. No DB lookup for the decision itself.
- Regulatory check: How do we handle a user we don't know the location of yet? Use IP geolocation at the edge (CDN headers) or default to "Safe Mode" (no experiments).
- Fairness: What if the user ID changes (anonymous to logged in)? Need a stable identifier strategy (Device ID + User ID mapping).
6. Detailed Code/Logic Example:
I'll provide a pseudocode or Python snippet for the Router logic to make it concrete.
- Input: UserContext (ID, Region, Device).
- Process: Check Registry -> Match Eligibility -> Hash -> Assign Variant.
7. Addressing the "Balancing" aspect explicitly:
- Latency: Solved by Edge processing (no network roundtrip to origin).
- Fairness: Solved by Consistent Hashing.
- Regulatory: Solved by Regional Silos and Logic Gates.
8. Final Polish:
Make the tone professional, architectural, and focused on system design. Use standard industry terms (Control Plane, Data Plane, CRDT, CAP theorem trade-offs).
(Self-Correction on Auditing): Make sure to emphasize asynchronous logging. If we wait for the audit log to write, latency spikes.
(Self-Correction on Rollback): How fast is "instant"? We need a push mechanism (WebSocket/Push notification to edge servers) rather than polling.
9. Structure of the final output:
- Architecture Overview (The Control Plane vs. Data Plane).
- Component 1: The Router (Latency & Fairness) - The hashing logic.
- Component 2: Regulatory Constraints (Compliance) - The Geo-fencing.
- Component 3: Data Sync (Consistency) - Getting config to the edge.
- Component 4: Auditing (Traceability) - Regional logging.
- Component 5: Rollback (Safety) - Kill switches.
- Summary Table (Trade-offs).
Let's write this out.
Designing a global Experimentation Router requires a specific architecture that separates the Control Plane (configuration) from the Data Plane (execution).
Here is a comprehensive design for a system that balances low latency (sub-10ms), statistical fairness, and strict regulatory compliance (GDPR/CCPA/PIPL).
1. High-Level Architecture: Hybrid Edge-Core Model
To achieve global low latency, we cannot rely on a centralized database for every request. We adopt a Control Plane / Data Plane separation.
- Control Plane (Centralized Cloud - e.g., AWS us-east-1):
- The "Source of Truth" where data scientists define experiments, variants, and targeting rules.
- Manages the "Master Config" and pushes updates to the Edge.
- Data Plane (The Router - Edge/Regional):
- Deployed globally (e.g., via Fastly Compute@Edge, Cloudflare Workers, or Kubernetes pods in multiple regions).
- Holds a read-only replica of the experiment configuration.
- Performs the routing logic locally against the configuration in memory (RAM).
2. The Router Logic: Latency & Fairness
The core routing algorithm must be purely computational (CPU-bound) with zero network I/O (no database calls) to ensure speed. We use Deterministic Hashing for fairness.
The Algorithm (Decision Tree)
The router processes the request in a specific sequence to ensure "Fairness" (unbiased sampling) and "Latency" (O(1) complexity).
- Input Validation: Receive
User ID, Device ID, and Context (Geo, Browser, etc.).
- Regulatory Gate (The Compliance Filter):
- Check: Is the user in a restricted region (e.g., EU)?
- Check: Is the user opted out of tracking (GPC header / Consent Banner)?
- Action: If restricted, bypass all experimentation logic and serve the Control (default) variant immediately. This satisfies "Regulatory Constraints."
- Targeting (The Filter):
- Iterate through active experiments.
- Check: Does
User.Context match Experiment.Targeting? (e.g., Is user on iOS? Is user in the US?).
- Fail: If no match, exclude from experiment.
- Bucketing (The Fairness Mechanism):
- For matched experiments, calculate the bucket.
- Formula:
Hash(ExperimentSalt + UserID) % 10000
- Why: MurmurHash or SipHash is extremely fast and distributes users uniformly (Uniform Distribution ensures Fairness).
- Assignment: If the result is 0–1000 (10%), assign Variant A. If 1001–2000, assign Variant B.
- Sticky Consistency:
- The result is deterministic. The user will always get the same variant without needing to store state, provided the config hasn't changed.
Pseudocode
def route_request(user_id, user_context, experiments_config):
decision_log = []
for exp in experiments_config:
# 1. Regulatory Check
if user_context.region in exp.excluded_regions:
continue # Skip experiment for this user
# 2. Targeting Check (Decision Tree)
if not matches_targeting(exp.targeting_tree, user_context):
continue
# 3. Bucketing (Fairness)
# Using fractional bucketing for traffic allocation
hash_val = murmurhash3(exp.salt + user_id) % 10000
if hash_val < (exp.traffic_alloc * 10000):
variant = get_variant(exp, hash_val)
return variant.id, decision_log
return "CONTROL", decision_log
3. Data Sync: Consistency vs. Latency
We need to update the global router instantly without causing cache stampedes or thundering herds.
- Mechanism: Atomic Snapshot Swapping.
- Protocol:
- Control Plane writes a new JSON config to a Global Object Store (S3) and creates a manifest file with a version number (e.g.,
v1.0.45).
- Edge Routers poll this manifest every 10 seconds (or use a WebSocket push).
- If a new version is detected, the Edge Router downloads the JSON in the background.
- Once validated (checksum), it atomically swaps the pointer in RAM to the new object.
- Conflict Resolution: If an Edge node fails to download, it keeps serving the old config (Graceful Degradation) rather than failing open.
4. Auditing & Regulatory Compliance
Regulations (GDPR/CCPA) require strict auditing of decision-making logic.
A. The "Impression Log" (Asynchronous)
To maintain latency, we do not write to the database during the request. Instead, we fire an asynchronous event (Fire-and-Forget) to a distributed log (Kafka/Kinesis).
- Payload:
{
"timestamp": "2023-10-27T10:00:00Z",
"user_id": "hashed_id_123", // PII protected
"experiment_id": "exp_99",
"variant_id": "var_b",
"regulation_flag": "GDPR_APPLICABLE",
"config_version": "v1.0.44"
}
B. Regional Silos (Data Residency)
For strict jurisdictions like China (PIPL) or Germany:
- The Router logic remains global, but the Audit Log sinks and User Storage are regional.
- The router tags the audit event. A routing layer sends the audit event to the EU Kafka cluster if
user_region == EU.
5. Rollback Strategy
Experiments can go wrong (crash bugs, revenue drops). Rollback must be immediate.
Level 1: The "Global Kill Switch"
A separate, highly available, low-latency configuration (e.g., Redis Global or Edge Key-Value Store) containing experiment_id: status.
- If
status == KILLED, the Router bypasses bucketing and serves CONTROL.
- This propagation happens in < 1 second globally.
Level 2: Automated Guardrails (Circuit Breakers)
The router emits metrics (exp_99_variant_A_conversion, exp_99_variant_A_error_rate).
- An anomaly detection system (e.g., Prophet or simple threshold alerting) monitors these streams.
- If error rate > 1%, the system automatically updates the
Global Kill Switch config.
Level 3: Shadow Traffic (Safe Rollout)
When deploying a risky routing algorithm:
- Run Shadow Mode: The router calculates the new variant but does not serve it to the user. It logs what would have happened.
- Compare the Shadow logs against production to verify math/logic before going live.
Summary of Trade-offs
| Feature | Design Choice | Benefit | Cost |
|---|
| Latency | Compute at Edge (No DB reads) | < 5ms response time | Config updates have slight delay (polling lag) |
| Fairness | MurmurHash Bucketing | Mathematically uniform distribution | Hard to move specific users between variants manually |
| Compliance | Pre-routing Filter | Guaranteed no illegal data processing | Reduces total addressable market for the experiment |
| Rollback | Global Kill Switch | Instant disable | Requires external monitoring system to trigger it |