Real-time A/B test monitor with late arrival tolerance
System DesignModel answerLast updated
Build a stream processor that detects traffic imbalances across experiment variants in real time, handling duplicate events and delayed data.
You're building a real-time monitor for A/B experiments that processes two event streams:
- Assignments:
(experiment_id, user_id, variant, timestamp)— when a user enters an experiment - Pageviews:
(user_id, timestamp)— user activity events
Your system must:
- Ensure each user counts once per experiment — handle duplicates and replay without double-counting
- Track variant populations efficiently — maintain running totals per variant without storing individual events, supporting arrivals up to 24 hours late
- Alert on imbalances every minute — compute a chi-square test against the expected traffic split (e.g., 50/50 or 33/33/33), raising an alert when
p < 0.0001and the largest variant share deviates by ≥0.3 percentage points from target - Filter automated traffic — exclude users generating more than N assignments per minute
- Scale horizontally — describe how to partition work across multiple workers
- Enable offline validation — explain how you'd test the detector against historical data without biasing results
Provide:
- Data structures and state management approach
- Pseudocode for the core logic
- Time and space complexity
- Partitioning strategy
- Validation methodology
Assume millions of concurrent experiments and billions of events per day.
Hints
Hint 1
Each layer has different memory constraints: deduplication scales with unique keys, aggregation stays constant per experiment, evaluation runs only on changed experiments
Hint 2
Late events should update the time bucket matching their event timestamp, not their arrival time — this requires a sliding window of buckets
Hint 3
When a user exceeds the rate limit, you can subtract their prior contributions instead of waiting to decide whether to count them
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines streaming state management, statistical testing, and distributed systems design. The solution uses three processing stages, each with different state requirements.
Architecture
Stage 1: Admission Control (per-user state)
Maintain a deduplication map keyed by (experiment_id, user_id) with TTL of max_lateness + window_size (e.g., 25 hours). Each entry stores (variant, bucket_index, timestamp).
For rate limiting, track assignments per user per minute. When a user crosses the threshold N:
- Subtract their previous contributions using the stored
(variant, bucket_index) - Mark them as excluded for the lateness window
- This "retraction" approach avoids buffering events speculatively
Stage 2: Time-Bucketed Aggregation (per-experiment state)
Each experiment maintains a ring buffer of B buckets (e.g., B = 25 for hourly buckets over 25 hours). Each bucket holds a counter per variant. Memory is O(B × V) per experiment, independent of traffic volume.
When an assignment arrives:
- Map its event timestamp to a bucket:
bucket = (event_ts // bucket_duration) % B - Increment
counts[experiment_id][bucket][variant] - Mark the experiment as "dirty" for this evaluation period
Late events land in the bucket corresponding to their original event time, not arrival time. Events older than the watermark (current_time - max_lateness) are dropped and logged.
Stage 3: Statistical Evaluation (per-minute)
For each dirty experiment, sum counts across all buckets in the evaluation window. Compute the chi-square goodness-of-fit statistic with Yates' continuity correction:
χ² = Σ_variants (max(|observed - expected| - 0.5, 0))² / expected
Alert if both conditions hold:
p-value < 0.0001(statistically significant)max_variant |observed_fraction - target_fraction| ≥ 0.003(practically meaningful)
The dual threshold prevents alerting on trivial imbalances that are statistically detectable at scale but operationally insignificant.
Pseudocode
class ExperimentMonitor:
def __init__(self, bucket_duration=3600, max_lateness=86400, rate_limit=100):
self.dedup = {} # (exp_id, user_id) → (variant, bucket_idx, ts)
self.excluded = {} # user_id → expiry_ts
self.user_rate = {} # (user_id, minute) → count
self.buckets = {} # exp_id → [B buckets × V variants]
self.dirty = set() # experiments modified this period
self.watermark = 0
self.bucket_duration = bucket_duration
self.max_lateness = max_lateness
self.rate_limit = rate_limit
def process_assignment(self, exp_id, user_id, variant, ts):
# Update watermark
self.watermark = max(self.watermark, ts - self.max_lateness)
# Drop if too late
if ts < self.watermark:
return
# Deduplication
key = (exp_id, user_id)
if key in self.dedup:
return # Already counted
# Rate limiting
minute_key = (user_id, ts // 60)
self.user_rate[minute_key] = self.user_rate.get(minute_key, 0) + 1
if self.user_rate[minute_key] > self.rate_limit:
# Retract previous contributions from this user
if key in self.dedup:
prev_variant, prev_bucket, _ = self.dedup[key]
self.buckets[exp_id][prev_bucket][prev_variant] -= 1
self.dedup[key] = None
self.excluded[user_id] = ts + self.max_lateness
return
if user_id in self.excluded and ts < self.excluded[user_id]:
return
# Record and count
bucket_idx = (ts // self.bucket_duration) % num_buckets
self.dedup[key] = (variant, bucket_idx, ts)
if exp_id not in self.buckets:
self.buckets[exp_id] = init_buckets()
self.buckets[exp_id][bucket_idx][variant] += 1
self.dirty.add(exp_id)
def evaluate(self, current_time):
for exp_id in self.dirty:
# Sum across window
totals = aggregate_window(self.buckets[exp_id])
# Skip if sample too small
if sum(totals.values()) < 1000:
continue
# Chi-square with Yates correction
target_split = get_target(exp_id)
chi2, p_value = compute_chi2_yates(totals, target_split)
# Effect size check
max_deviation = max_share_deviation(totals, target_split)
if p_value < 0.0001 and max_deviation >= 0.003:
alert(exp_id, totals, p_value, max_deviation)
self.dirty.clear()
Complexity
Time:
- Per assignment: O(1) amortized (retraction is O(N) but happens at most once per user-minute)
- Per evaluation cycle: O(D × B × V) where D = dirty experiments, B = buckets, V = variants
- Optimize to O(D × V) by maintaining running window sums
Space:
- Aggregation: O(E × B × V) — E experiments, constant per experiment
- Deduplication: O(K) — K unique
(experiment_id, user_id)pairs within TTL window - Rate tracking: O(U) — U active user-minutes
The deduplication state dominates at scale but has a natural TTL bound.
Sharding Strategy
Phase 1 — User-keyed partitioning:
- Partition both streams by
hash(user_id) % num_workers - Each worker handles deduplication, rate limiting, and bucketing independently
- Workers emit delta records:
(exp_id, bucket_idx, variant, count_delta, worker_id, sequence_num)
Phase 2 — Experiment-keyed aggregation:
- Repartition deltas by
hash(exp_id) % num_aggregators - Aggregators merge deltas (deduping on
(worker_id, sequence_num)), maintain the full ring buffer per experiment, and run statistical tests - Since addition is commutative, merge order doesn't affect correctness
Checkpointing:
- Snapshot state with input offsets for exactly-once semantics on restart
- Use per-partition watermarks with idle timeout to avoid one slow partition stalling progress
Validation Approach
Offline validation against historical data requires care to avoid "oracle leakage":
-
Replay with jitter: Add random delays (0–24 hours) to historical events to simulate realistic late arrivals, ensuring the detector encounters the same ordering challenges as production
-
Inject synthetic anomalies: Randomly select 5% of experiments and introduce known imbalances (e.g., shift 10% of traffic from variant A to B for 1 hour). The detector should flag these with high recall.
-
Shadow mode first: Run the detector alongside the current system, comparing alerts. Investigate all divergences before cutover.
-
Metrics coverage: Track false positive rate on balanced experiments, detection latency for injected anomalies, and state size growth.
-
A/A test bootstrap: For experiments with no real effect, the detector should alert at the configured alpha rate (0.01% for p < 0.0001). Validate this empirically.
Edge Cases
- Small samples: Skip tests when total count < minimum threshold or any expected cell count < 5 (chi-square assumption)
- Missing variants: A variant with zero observations still has expected count > 0; include it in the test
- Unknown variants: Alert separately on variants not in the target config (indicates instrumentation bug)
- Clock skew: Clamp future timestamps to
wall_clock + small_epsilonto prevent watermark jumps - Configuration changes: Version experiment configs; reset state on target split changes
Code Complexity
The chi-square p-value computation requires a numerically stable implementation of the incomplete gamma function. Use established libraries (scipy.stats.chi2) or a carefully tested approximation.
This design achieves O(1) memory per experiment for aggregation, bounded state for deduplication via TTL, and linear scalability through two-stage partitioning. The statistical thresholds balance sensitivity (catching real issues) with specificity (avoiding noise at scale).