Architecting an Enterprise Experimentation and Feature Flag Platform
System DesignModel answerLast updated
Design a distributed, highly available A/B testing infrastructure capable of sub-millisecond variant evaluation, scale-proof event ingestion, and statistically sound automated analysis.
Scenario
Modern online platforms rely heavily on data-driven product decisions. Teams across product design, machine learning, financial risk, and growth continuously deploy experiments to evaluate user interface updates, pricing models, search ranking algorithms, and risk evaluation logic.
You are tasked with designing an enterprise-grade experimentation platform. The platform must safely route user traffic to target variations, log treatment exposures without introducing unacceptable latency or resource contention, and process conversion data to derive statistically robust insights.
Requirements
Core Capabilities
- Experiment Administration & Target Distribution: Support flexible targeted rollouts based on user attributes (e.g., location, device type, risk category), distinct traffic splits (e.g., 90/10, 50/50), and mutually exclusive experiment groupings (layers) to allow parallel tests without cross-experiment interaction bias.
- Deterministic Variant Routing: Given an entity identifier (such as
user_idordevice_id) and contextual attributes, compute the exact variant assignment deterministically. Assignments must remain consistent across sessions and user touchpoints. - Exposure & Data Ingestion Pipeline: Capture exact moments of exposure (when a user actually experiences a variant) and join these exposure logs with downstream transactional and telemetry events (e.g., checkout attempt, subscription renewal, default rate).
- Statistical Analytics & Guardrails: Calculate conversion metrics, sample ratio mismatch (SRM) indicators, confidence intervals, p-values, and automated guardrail alerts.
System Constraints & Scale Targets
- Evaluation Latency: In-process flag routing must complete within < 1 ms at p99, and central RPC evaluations must take < 10 ms at p99. Flag evaluation must never disrupt or block core transactional flows.
- High Availability & Fault Tolerance: The evaluation pathway requires 99.999% availability (five-nines). System failures or network partitions must fail gracefully to default control options.
- Scale:
- 50,000 evaluation queries per second (QPS) standard load, peaking at 150,000 QPS.
- 500 million incoming exposure and business telemetry events logged per day (~250 GB/day uncompressed data footprint).
- Support hundreds of simultaneously running experiments across various front-end applications, native mobile apps, and back-end microservices.
Scope of Design
- System Architecture Breakdown: Clarify the distinction and responsibilities across Control Plane (experiment creation & rule distribution), Data Plane (in-process SDK evaluation & centralized edge fallback), and Analytics/Data Plane (telemetry processing & statistical analysis).
- Deterministic Bucketing Algorithm: Define how entities map to variants deterministically using uniform hashing mechanisms (e.g., salted Murmur3), rule predicate trees, and layered multi-experiment allocations.
- Event Stream Pipeline & Attribution: Show how exposure logs and downstream business events are captured, buffered, deduplicated, and linked for multi-window attribution.
- Data Modeling & Storage Strategy: Outline schema design and technology choices across relational metadata stores, streaming brokers, analytical data lakes, and OLAP querying engines.
- System Trade-offs & Edge Cases: Evaluate key design choices: Client/Embedded SDK vs. Remote Service Evaluation, push vs. pull config updates, and managing sticky variant integrity during traffic ramp-ups.
Hints
Hint 1
Avoid remote HTTP calls on the critical evaluation path; embedded local state and client-side deterministic hashing provide near-zero latency.
Hint 2
Use layer-based hashing (two-stage hashing) to maintain mutual exclusivity across simultaneous tests while preserving statistical independence across separate layers.
Hint 3
Strictly log exposures when the treatment is actually rendered/experienced by the user rather than when the feature flag configuration is evaluated.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & System Scale
Scale Specifications
- Evaluation Throughput: Average 50,000 QPS, peaking at 150,000 QPS.
- Telemetry Volume: 500 million events per day ($\approx$ 5,800 events/sec average, 20,000 events/sec peak).
- Payload Footprint: $\approx 500 \text{ bytes per raw event} \implies \sim 250 \text{ GB/day raw data}$.
- Evaluation Speed: In-process SDK evaluation target $< 1\text{ ms}$ (p99). Remote gateway evaluation $< 10\text{ ms}$ (p99).
- Availability Target: 99.999% (less than 5.26 minutes of cumulative downtime per year for variant evaluation).
2. Overall High-Level Architecture
The platform separates responsibilities into three distinct operational planes: Control Plane, Data Plane, and Analytics Plane.
+-------------------------------+
| Experiment Admin Console UI |
+---------------+---------------+
|
v
+---------------+---------------+
| Control Plane API (RDBMS) |
+---------------+---------------+
| Config Sync / CDN
v
+--------------------------------+--------------------------------+
| |
v v
+-------------------------------+ +-------------------------------+
| Embedded SDK (In-Memory Data) | | Central Evaluation Gateway |
+---------------+---------------+ +---------------+---------------+
| Local Hash Evaluation | Hash Evaluation
+------------------------------+----------------------+
| Exposure Telemetry
v
+---------------+---------------+
| Exposure Collector / Kafka |
+---------------+---------------+
|
v
+---------------+---------------+
| Stream Engine (Flink Dedup) |
+---------------+---------------+
|
+----------------------+----------------------+
| Stream Path | Batch Path
v v
+-------------------------------+ +-------------------------------+
| Real-Time OLAP (ClickHouse) | | Data Lake (S3 / Parquet) |
+---------------+---------------+ +---------------+---------------+
| |
+----------------------+----------------------+
|
v
+--------------+----------------+
| Automated Stats Engine (Spark)|
+-------------------------------+
A. Control Plane (Experiment Management & Distribution)
- Experiment Management Service: REST/gRPC service backed by transactional storage (PostgreSQL) storing experiment metadata, targeted audiences, variant proportions, and layer definitions.
- Configuration Publisher: Converts active experiment rules into compiled, optimized JSON/Protobuf snapshots. Published artifacts are deployed to a CDN (e.g., Cloudflare/CloudFront) and pushed via WebSocket/SSE channels to consumers.
B. Data Plane (Evaluation Path)
- Embedded Evaluation SDKs: Libraries integrated into backend microservices, web clients, and mobile apps. Evaluation runs in-process in $\approx 100\ \mu\text{s}$ using locally cached rule sets.
- Centralized Evaluation Gateway: High-throughput, stateless service (written in Rust or Go) serving clients unable to run full embedded SDKs (e.g., edge workers, legacy microservices).
C. Analytics Plane (Ingestion, Processing & Statistics)
- Exposure Collector: High-throughput HTTP API ingestion nodes taking batch telemetry payloads from SDKs and pushing them into Apache Kafka / AWS Kinesis.
- Stream Processing (Apache Flink): Consumes exposure streams, deduplicates multiple events within sliding time windows, checks for Sample Ratio Mismatch (SRM) anomalies, and raises immediate guardrail alerts.
- Batch Processing (Apache Spark): Conducts daily/hourly joins between exposure logs and downstream business transactions (e.g., payment success, risk defaults), computing confidence intervals, p-values, and CUPED variance reduction metrics.
- Analytical Storage: Aggregated metrics land in a real-time OLAP system (ClickHouse or Apache Pinot) for low-latency dashboarding.
3. Bucketing Logic & Rule Evaluation
Deterministic Hashing
Assignments must be completely deterministic and stateless. No network request or central cache lookup (e.g., Redis) is performed during flag evaluation.
We use salted MurmurHash3 (32-bit output) mapped uniformly over a fixed ring range $[0, 9999]$ ($10,000$ discrete buckets, providing $0.01%$ granularity).
$$\text{bucket} = \text{Murmur3_32}(\text{salt} + \text{":"} + \text{entity_id}) \pmod{10000}$$
import mmh3
def evaluate_variant(entity_id: str, experiment_salt: str, variants: list) -> str:
"""
variants: list of tuples [('control', 5000), ('treatment', 5000)]
representing bucket ranges totaling 10000.
"""
key = f"{experiment_salt}:{entity_id}"
bucket = mmh3.hash(key, signed=False) % 10000
cumulative_bucket = 0
for variant_name, bucket_count in variants:
cumulative_bucket += bucket_count
if bucket < cumulative_bucket:
return variant_name
return "control" # Fallback variant
Mutually Exclusive Experiments via Layers
To run multiple experiments concurrently on the same user base without cross-contamination:
- Domain Allocation (Layering): Define a top-level domain layer (e.g.,
checkout_flow_layer). - Stage 1 (Layer Bucketing): Hash the entity against the layer's unique salt to map the user to a bucket range within the layer.
$$\text{layer_bucket} = \text{Murmur3_32}(\text{layer_salt} + \text{":"} + \text{entity_id}) \pmod{10000}$$
- Experiment 101 occupies layer buckets $[0, 4999]$ (50% traffic).
- Experiment 102 occupies layer buckets $[5000, 9999]$ (50% traffic).
- Stage 2 (Variant Assignment): If the user lands inside Experiment 101's bucket range, evaluate their specific variant using the experiment's unique salt: $$\text{variant_bucket} = \text{Murmur3_32}(\text{exp101_salt} + \text{":"} + \text{entity_id}) \pmod{10000}$$
If two experiments belong to independent layers (e.g., ui_theme_layer vs. pricing_engine_layer), different salt values ensure that assignments are statistically orthogonal.
Targeting Rule Trees
Targeting conditions (e.g., country == 'US' AND device_type IN ('iOS', 'Android') AND user_tier != 'VIP') are formatted as Abstract Syntax Trees (ASTs). When compiled into memory by the SDK, context evaluation runs in sub-microseconds prior to executing the hashing step.
4. Ingestion Pipeline & Event Attribution
Exposure vs. Flag Evaluation
Evaluating a flag logic check must not automatically generate an exposure record. An exposure record is emitted only when the user actually encounters the assigned variation. This prevents dilution bias and artificial Sample Ratio Mismatches.
Exposure Event Schema
{
"event_id": "a8f9c12e-15b2-4d51-bdf1-3b320d745e12",
"experiment_id": "exp_checkout_v2",
"variant_id": "treatment_b",
"entity_id": "usr_99812401",
"config_version": 14,
"client_timestamp": 1708941200123,
"server_timestamp": 1708941200185,
"context": {
"platform": "ios",
"app_version": "4.12.0",
"country": "US"
}
}
Ingestion Flow & Deduplication
- SDK Asynchronous Buffer: SDK collects exposure logs into an in-memory queue, dispatching them to the collector endpoint in background batches (every 5 seconds or 100 events).
- Kafka Partitioning Strategy: Exposures land in Kafka, partitioned by
entity_id. - Flink Deduplication Engine: Uses a 24-hour state window to retain only the first exposure per
(experiment_id, entity_id)pair, dropping redundant exposure logs before analytics processing.
+---------------+ +--------------------+ +-------------------+ +------------------+
| In-Memory SDK | --> | Telemetry Gateway | --> | Kafka Topic | --> | Flink Windowing |
| Buffer Queue | | (Stateless HTTP) | | (Keyed by User) | | (First Exposure) |
+---------------+ +--------------------+ +-------------------+ +------------------+
|
v
+------------------+
| S3 Parquet Lake |
+------------------+
5. System Data Models
RDBMS Schema (Control Plane - Postgres)
CREATE TABLE experiments (
experiment_id VARCHAR(64) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
layer_id VARCHAR(64) NOT NULL,
layer_bucket_start INT NOT NULL, -- Range 0-9999
layer_bucket_end INT NOT NULL,
salt VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL, -- DRAFT, RUNNING, PAUSED, CONCLUDED
targeting_rules JSONB DEFAULT '{}'::jsonb,
variants JSONB NOT NULL, -- [{"id": "control", "weight": 5000}, ...]
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE experiment_config_snapshots (
version SERIAL PRIMARY KEY,
published_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
payload JSONB NOT NULL,
checksum VARCHAR(64) NOT NULL
);
Data Lake Parquet Schema (Analytics - S3)
-- Partitioned by date: s3://telemetry-lake/exposures/dt=2024-02-26/
CREATE TABLE exposures (
event_id STRING,
experiment_id STRING,
variant_id STRING,
entity_id STRING,
config_version INT,
exposed_at TIMESTAMP
) USING PARQUET
PARTITIONED BY (dt STRING);
6. Analytical Engine & Statistical Computations
Sample Ratio Mismatch (SRM) Verification
To detect bias caused by improper variant assignment, network dropouts, or selective rendering failures, a Pearson's Chi-Square ($\chi^2$) Goodness-of-Fit test compares observed user counts against expected allocations.
$$\chi^2 = \sum_{i=1}^{k} \frac{(O_i - E_i)^2}{E_i}$$
- If calculated $p\text{-value} < 0.001$, an SRM alert fires immediately via Flink, flagging the experiment as contaminated.
Variance Reduction via CUPED
To lower variance and speed up experiment convergence, apply CUPED (Controlled-experiment Using Pre-Experiment Data).
Let $Y$ be the target metric post-exposure, and $X$ be the same metric measured prior to experiment start:
$$\hat{Y}_{\text{CUPED}} = Y - \theta (X - E[X]) \quad \text{where} \quad \theta = \frac{\text{Cov}(Y, X)}{\text{Var}(X)}$$
This transformation removes pre-existing variance, reducing the required sample size by up to 50%.
7. Reliability, Edge Cases & System Trade-Offs
Distributed Fallback Strategy
If the network partitions or central infrastructure fails:
- Level 1: Read compiled configurations cached in memory.
- Level 2: Fall back to the locally saved snapshot on disk.
- Level 3: Fall back to hardcoded in-code defaults (typically assigned to
control).
Under no circumstances does an evaluation failure block application execution or HTTP response delivery.
Ramp-Up Variant Stability
When expanding an experiment's traffic share (e.g., ramping from 10% to 50%), variant assignments for existing users must remain consistent.
- Incorrect Method: Modifying target variant weights directly inside an existing salt space shifts hash boundaries and flips existing users between treatment and control.
- Correct Method: Keep the original relative split within the active bucket range, expanding the layer bucket boundaries $[0, 999]$ out to $[0, 4999]$ while maintaining the exact same experiment salt.
Initial (10% Traffic): [ Exp 101 (0 - 999) ] | Unassigned (1000 - 9999)
Ramp Up (50% Traffic): [ Exp 101 (0 - 4999) ] | Unassigned (5000 - 9999)
Users mapped to $0–999$ maintain their exact variant assignment because the experiment salt remains untouched.
Embedded SDK vs. Remote Central Gateway
| Operational Metric | Embedded Client SDK | Central Evaluation Gateway |
|---|---|---|
| p99 Latency | $< 0.1\text{ ms}$ (Local CPU execution) | $2\text{--}10\text{ ms}$ (Network RPC hop) |
| Network Overhead | Low (Periodic background snapshot poll) | High (Per-evaluation network request) |
| Rule Integrity | Requires rule synchronization to all nodes | Centralized, instantly consistent |
| Language Support | Needs SDK implementation per stack | Generic HTTP/gRPC interface |
| Memory Footprint | Holds compiled config rules in memory | Minimal client-side footprint |
8. Summary Operational Verification Walkthrough
- A Product Manager configures a new experiment in the UI, assigning a 50/50 split across 20% of traffic within
layer_checkout. - The Control Plane writes the updated definition to PostgreSQL, generates a new snapshot payload, and uploads it to the CDN.
- Embedded application SDKs fetch the snapshot update within seconds.
- When a user lands on the checkout page, the SDK evaluates the condition tree locally, hashes
Murmur3("checkout_salt:user_1234") % 10000, maps the user totreatment, and returns control within $100\ \mu\text{s}$. - As the UI component renders, the SDK asynchronously enqueues an exposure log payload.
- The exposure telemetry pipeline processes the event, joining it with downstream purchase logs in Apache Spark to update analytical dashboards and compute $p$-values automatically.