Build an experimentation system for product launches
Statistics & ExperimentsModel answerLast updated
Design a platform that randomly assigns users to variants, logs their behavior, computes metrics, and determines statistical significance.
You're tasked with building an experimentation platform that enables product teams to test changes before launching them to all users.
The system must handle the full lifecycle:
- Creating tests with multiple variants and allocation rules
- Assigning users to variants consistently
- Recording when users see each variant
- Tracking outcome events (clicks, purchases, engagement)
- Computing metrics and determining whether differences are statistically significant
- Protecting against bad launches with automatic guardrails
Your organization has roughly 1 billion daily active users. Product teams run around 1,000 tests at any given time, and a typical user participates in 20–50 overlapping tests simultaneously.
Assignment must happen with sub-millisecond latency, even if backend services are temporarily unavailable. The event pipeline processes around 100 billion events daily. Metric reports should be available within hours, while safety guardrails need to run every 15 minutes.
Describe your design, covering:
- How you assign users to variants deterministically and at scale
- The architecture for logging exposures and outcome events
- How you compute metrics and statistical significance
- Mechanisms to avoid bias and ensure valid results
- How you handle rollouts, overlapping tests, and safety guardrails
Hints
Hint 1
Think about how to keep assignment logic fast and deterministic using hashing rather than remote calls
Hint 2
Consider what happens when you analyze data at a different granularity than you randomized (e.g., randomize per user but measure per pageview)
Hint 3
Exposure logging matters: if you only log when the new feature renders, you introduce selection bias
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Experimentation Platform Design
Approach
The core challenge is balancing statistical validity with scale. Many platforms can route traffic and collect logs, but producing trustworthy results requires careful attention to assignment consistency, logging discipline, and how metrics are computed. The design treats reproducibility and correctness as first-class requirements.
Requirements Clarification
Functional scope:
- Define tests specifying variants, traffic split, targeting rules, randomization unit, success metrics, and safety thresholds
- Assign units deterministically with minimal latency
- Capture exposure events (when a user could see the variant) and outcome events
- Calculate treatment effects, confidence intervals, and significance tests
- Support gradual ramps and concurrent tests without interference
- Halt tests automatically when guardrails breach
Scale parameters:
- 1B daily active users
- ~1,000 active tests, each user in 20–50 tests
- 100B events/day total; exposure logs around 10–50B/day
- Assignment latency target: <1ms p99, in-process
- Metric freshness: daily batch within a few hours; guardrails every 15 minutes
High-Level Architecture
┌─────────────┐
│ Config UI │──> Experiment definitions, versioned
└──────┬──────┘
│
▼
┌─────────────────┐ ┌──────────────┐
│ Config Service │────────>│ CDN/Cache │
│ (versioned DB) │ └──────┬───────┘
└─────────────────┘ │
│ SDK polls config
▼
┌─────────────────┐
│ Assignment SDK │ (client/server)
│ (local hash) │
└────────┬────────┘
│
┌──────────────────┴──────────────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Exposure Log│ │ Event Log │
└──────┬──────┘ └──────┬──────┘
│ │
└──────────────┬──────────────────────┘
▼
┌─────────────┐
│ Kafka │
└──────┬──────┘
│
┌──────────────┴──────────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Batch ETL │ │ Streaming │
│ (Spark) │ │ Guardrails │
│ Daily agg │ │ (Flink) │
└──────┬──────┘ └──────┬──────┘
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Metrics DB │ │ Alerting │
└──────┬──────┘ └─────────────┘
│
▼
┌─────────────┐
│ Scorecard │
│ Service │
└─────────────┘
Core Components
1. Assignment Logic
Use deterministic hashing rather than centralized assignment:
bucket = hash(layer_salt || unit_id) mod 10000
- Hash function: MurmurHash3 or FarmHash (fast, well-distributed)
- Each test owns a bucket range, e.g., buckets 0–499 for a 5% allocation
- Variants split those buckets proportionally
- Layers enable overlapping tests: each layer uses a distinct salt, making assignments statistically independent across layers. Tests within a layer are mutually exclusive (own disjoint bucket ranges).
The SDK embeds this logic, caches config locally, and refreshes every 60 seconds. Because assignment is a pure function, it works offline and produces identical results everywhere.
Example:
- Layer "homepage", salt="homepage_v3"
- Test A owns buckets 0–999 (10%), split 50/50 between control and treatment
- Test B owns buckets 1000–1999 (10%), split into three variants
2. Randomization Unit & Consistency
Choose the unit carefully:
- user_id for logged-in features: consistent across sessions and devices
- device_id/cookie for logged-out experiences (but note cookie churn inflates sample size)
- session or pageview only when the variant has no persistent effect
Critical rule: the analysis unit must match or be coarser than the randomization unit. If you randomize by user but analyze clicks per pageview, observations aren't independent. Use clustered standard errors or the delta method to correct for this.
When users log in mid-session, maintain consistency by resolving identity: assign on the most stable ID available and propagate that assignment forward.
3. Exposure Logging
Log an exposure when the variant could have influenced what the user experiences, not at assignment time.
Trigger-based logging:
def render_homepage(user_id):
variant = get_assignment(user_id, "homepage_redesign")
log_exposure(user_id, "homepage_redesign", variant) # log in both arms
if variant == "new_design":
return render_new()
else:
return render_old()
Logging only in the treatment arm introduces selection bias. Logging at assignment time (before the user ever sees the page) dilutes measured effects because you count users who never experienced the change.
Schema: (unit_id, experiment_id, variant, config_version, timestamp, context)
Deduplicate on (unit_id, experiment_id, config_version) to count first exposure only.
4. Event Pipeline
All events flow into Kafka, partitioned by unit_id for efficient joins:
- Exposure events
- Outcome events (clicks, conversions, revenue, latency)
Write to a data lake (Parquet on S3/GCS) partitioned by date and experiment for efficient scans.
5. Metric Computation (Batch)
Daily Spark job:
- Join exposures to events on
unit_id, filtering events to those occurring after first exposure - Aggregate per unit: compute each user's total clicks, revenue, session count, etc.
- Aggregate per variant: compute sufficient statistics (count, sum, sum of squares) for each metric
- Statistical test: two-sample t-test (Welch's, unequal variance) on per-unit means
For ratio metrics like CTR = clicks/impressions, use the delta method for variance:
Var(X/Y) ≈ (μ_x/μ_y)² · [Var(X)/μ_x² + Var(Y)/μ_y² - 2·Cov(X,Y)/(μ_x·μ_y)]
Variance reduction (CUPED): regress out pre-experiment covariates. If you have the same metric measured before the test:
Y_adjusted = Y - θ(X_pre - mean(X_pre))
where θ = Cov(Y, X_pre) / Var(X_pre)
This typically reduces variance by 30–50%, shortening experiments significantly.
Store results as (experiment_id, variant, metric, date, n, mean, variance, confidence_interval).
6. Streaming Guardrails
Flink job runs on 15-minute windows:
- Sample Ratio Mismatch (SRM): chi-square test on observed vs. expected allocation. If p < 0.001, something is broken in assignment or logging.
- Guardrail metrics: crash rate, latency p99, revenue per user. If any crosses a threshold (e.g., +10% crashes), trigger an alert and optionally auto-disable by setting allocation to 0%.
7. Incremental Rollout
Ramp monotonically: 1% → 5% → 20% → 50% → 100%.
Expand bucket ranges, never reshuffle. If a user is in treatment at 5%, they stay in treatment at 20%. This avoids introducing time-varying confounds.
Never change the layer salt mid-test. If you must change allocation, either:
- Analyze only the stable period, or
- Use period-weighted estimators
Gate each ramp increase on guardrails passing.
8. Bias Avoidance
Carryover: When reusing buckets after a test ends, change the salt. Otherwise, lingering effects from the previous test contaminate the new one.
Novelty effects: Run for at least one full week (ideally two) to let novelty wear off. Plot the effect over time to detect decay.
Network interference: In two-sided marketplaces or social products, one user's treatment can affect another. Mitigate with:
- Geo-based or cluster randomization
- Switchback (time-based) designs
Outliers: Winsorize heavy-tailed metrics (cap at 99th percentile) or use log-transforms.
9. Overlapping Tests
Use layering: tests in different layers run independently. Tests in the same layer are mutually exclusive. A user in "homepage layer" test A and "checkout layer" test B sees both treatments, but the layer salts ensure the assignments are uncorrelated.
Reserve a small universal holdout (1% of users) excluded from all tests. Compare this group to the overall population quarterly to measure cumulative impact.
API Example
# Define test
create_experiment(
name="checkout_button_color",
layer="checkout",
unit="user_id",
variants=[
{"name": "control", "weight": 50},
{"name": "green", "weight": 50}
],
metrics=["conversion_rate", "revenue_per_user"],
guardrails=["crash_rate < 0.01", "latency_p99 < 500ms"],
duration_days=14
)
# Assignment (client/server SDK)
assignment = get_assignment(user_id, context)
# => {"checkout": ("checkout_button_color", "green", {})}
# Results
scorecard = get_scorecard("checkout_button_color")
# => {
# "conversion_rate": {
# "control": {"mean": 0.05, "n": 1000000},
# "green": {"mean": 0.052, "n": 1000000, "lift": "+4%", "ci": "[+2%, +6%]", "p": 0.001}
# }
# }
Complexity & Scale
- Assignment latency: O(1) hash, <1ms
- Storage: ~10–50B exposure rows/day × 30 days ≈ 1–2TB in Parquet (compressed)
- Batch processing: Spark job over 1 day of data completes in 1–2 hours on a modest cluster
- Streaming: Flink processes 100B events/day ≈ 1M events/sec, manageable with horizontal scaling
Common Mistakes
- Logging assignment instead of exposure → dilutes effect
- Logging only in treatment → selection bias
- Changing salt mid-test → time-varying allocation confounds results
- Analyzing at finer grain than randomized → inflated significance
- Ignoring carryover → previous test effects leak in
- Running too short → novelty effects dominate
This design produces statistically valid, reproducible results at scale by embedding correctness into each component: deterministic assignment, trigger-based logging, proper aggregation, and continuous diagnostics.