Skip to content

Design an A/B Testing and Experimentation Platform

Advanced 91 min read Part 17 of 18

Run thousands of trustworthy A/B tests at once: configs, hash-based assignment, exposure logs, metric pipelines, sequential statistics and guardrails.

The Problem#

A product team believes a new checkout button will raise purchases. A search team has a new ranking model. A growth team wants to try a shorter sign-up form. Each team could ship its change and watch the dashboards, but dashboards move for many reasons at once: a holiday, a marketing campaign, a competitor's outage, a bug in another team's release. You cannot tell which movement your change caused.

A controlled experiment (an A/B test) answers the question cleanly. Split users at random into two groups. Group A (the control) gets the current product. Group B (the treatment) gets the change. Because the split is random, the two groups are alike in every way except the change, so a difference in their behaviour that is too large to be chance was caused by the change. This is the same logic as a clinical drug trial, applied to software, and run continuously.

One experiment is easy. The hard problem is a platform that lets a whole company run thousands of experiments at the same time, on the same users, and trust every result. Public numbers show the scale:

  • LinkedIn wrote in 2020 that its platform, T-REX, serves up to 41,000 A/B tests simultaneously on a population of over 700 million members.
  • Uber wrote that over 1,000 experiments run on its platform at any given time, across rider, driver, Uber Eats and Freight apps.
  • Diane Tang and colleagues described Google's overlapping experiment infrastructure in the KDD 2010 paper "Overlapping Experiment Infrastructure: More, Better, Faster Experimentation". It let Google run roughly an order of magnitude more experiments than before, with many experiments overlapping on every search request.
  • Ron Kohavi and colleagues at Microsoft reported that only about one third of the ideas they tested improved the metric they were designed to improve. Without experiments, the other two thirds would have shipped on opinion.

Our task is to design that platform. The hard parts are:

  1. Configuration. Thousands of people create, start, ramp, pause and stop experiments every day. A mistake can break the product for millions of users or silently invalidate a month of data. Configuration must be validated, versioned, auditable and pushed to every server and app within minutes.
  2. Assignment. Every request needs to know, for each running experiment, which group this user is in. The answer must be random (so groups are comparable), deterministic (the same user always gets the same group, on every server, without a database lookup) and independent between experiments. This is done by hashing, and the details of the hashing decide whether results can be trusted.
  3. Interactions. With thousands of experiments, a user is in dozens at once. Some experiments can safely overlap. Others change the same pixel or the same ranking parameter and must exclude each other.
  4. Exposure logging. Analysis must include exactly the users who could have been affected. Logging "user X saw variant B of experiment E" at the right moment, at billions of events a day, without overwhelming the event pipeline, is its own design problem.
  5. A metrics pipeline. Hundreds of billions of product events a day (clicks, purchases, crashes, latencies) must be joined with exposures and turned into per-user metrics for every experiment, every day, including events that arrive late or out of order.
  6. Statistics. Is a 0.4% lift real? How many users are needed to detect it? What if the team looks at results every hour and stops when they look good? What if 200 metrics are checked at once? A platform must give answers that remain correct when used by people with no statistics training.
  7. Guardrails. An experiment that raises clicks but crashes the app, slows the page or hurts revenue must be caught quickly, ideally within minutes and automatically.
  8. Feature flags. Experiments are delivered through the same mechanism that turns features on and off. The platform must integrate with flags, gradual rollouts and kill switches, without becoming a tangle of stale configuration.

An analogy. Think of a large farm that tests new fertilisers. The farm is divided into thousands of small plots. A plot's treatment is decided by a lottery drawn from the plot's number, so nobody can steer the best fertiliser to the sunniest plots, and the same plot always gets the same treatment when someone checks. Several studies run at once on different crops and different nutrients, and a careful planner makes sure two studies that both change nitrogen never share a plot. Field workers write down which plots actually received fertiliser, because some bags never get spread. At harvest, every plot is weighed, and a statistician compares the treated and untreated plots, knowing that a single good plot proves nothing. If a fertiliser starts killing plants, a watcher notices in days, not at harvest, and stops it. The design questions are the farm's questions:

  • How do you assign plots fairly, repeatably and independently for many studies at once?
  • Which studies may share a plot, and which must not?
  • How do you record what each plot actually received?
  • How do you weigh thousands of plots every day, including late deliveries?
  • How do you decide a difference is real, and how soon may you look?
  • How do you stop a harmful study before harvest?

Background: a few terms used in this design#

  • Variant (arm, group). One version of the product in an experiment. The control is usually the current product; each treatment is a change. An A/B test has two variants; an A/B/n test has more.
  • Randomisation unit. The thing that is randomly assigned: usually a user id, sometimes a device id, a cookie, a session, a page view, or a whole city or market. All analysis depends on this choice.
  • Assignment (bucketing). Deciding which variant a unit gets. Bucketing means mapping each unit to one of a fixed number of buckets (for example 10,000) with a hash, then giving bucket ranges to variants.
  • Exposure (trigger). The moment a unit actually encounters the part of the product that differs between variants. A user can be assigned to an experiment on the checkout page and never reach checkout; that user is assigned but not exposed.
  • Metric. A number computed from events that measures behaviour, such as purchases per user, click-through rate, sessions per user or page load time.
  • OEC (overall evaluation criterion). The single metric, or small set of metrics, that the organisation agrees defines success. Kohavi's papers use the term; a common choice is a measure of long-term user value such as sessions per user, not a short-term number such as clicks.
  • Guardrail metric. A metric that must not get worse, even if the experiment is not trying to move it: crash rate, latency, errors, revenue, unsubscribes.
  • Treatment effect (lift, delta). The difference in a metric between treatment and control, often as a percentage of control.
  • Statistical significance and p-value. The p-value is the probability of seeing a difference at least this large if the change truly had no effect. A result is called significant if the p-value is below a chosen threshold α, usually 0.05.
  • Confidence interval. A range that, under repeated experiments, contains the true effect a stated fraction of the time (95% for the usual interval).
  • Type I and Type II errors. A Type I error (false positive) declares an effect that is not there. A Type II error (false negative) misses a real effect. Power is the probability of detecting a real effect of a given size, that is 1 − the Type II error rate.
  • MDE (minimum detectable effect). The smallest effect an experiment has a reasonable chance (usually 80%) of detecting at its planned size.
  • Feature flag (feature toggle). A runtime switch that decides which code path runs. An experiment is, mechanically, a feature flag whose value depends on a random assignment.
  • SRM (sample ratio mismatch). When the observed split of users between variants differs significantly from the configured split, for example 50.4% versus 49.6% on millions of users. It is a strong sign that something is broken.
  • Holdout. A group of users kept out of new features or experiments for a long period, to measure the combined long-term effect of many launches.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Who runs experiments: a few data scientists, or every engineering team?Self-service needs guardrails, validation and automated analysisEvery product team, about 5,000 engineers, product managers and analysts, mostly without statistics training
How many experiments run at once?Drives the assignment model, config size and analysis loadAbout 2,000 running at any time, growing towards 10,000; about 15,000 started per year
What scale of traffic?Sizes assignment, exposure and metrics pipelinesAbout 300 million daily active users, about 50 billion server requests a day, about 200 billion product events a day
Which surfaces: backend services, web, mobile apps, emails, ML models?Each needs an SDK or an integration, with different latency and offline behaviourAll of them: server SDKs, web and mobile SDKs, plus batch jobs that pick email or notification variants
What is the randomisation unit?Decides hashing input, identity stitching and analysisLogged-in user id by default; device or anonymous id for logged-out traffic; session or market as options
How fast must config changes take effect?Drives the push architectureUnder 1 minute for a kill switch; under 5 minutes for starting or ramping an experiment
How fresh must results be?Batch versus streaming analysisGuardrail alerts within about 15 minutes; full scorecards daily, with intraday updates for key metrics
Can teams look at results while the experiment runs?Peeking inflates false positives unless the statistics allow itYes; the platform must give results that remain valid under continuous monitoring
Who defines metrics?A metric catalog avoids every team computing revenue differentlyA central catalog of certified metrics, plus team-owned custom metrics defined in SQL
Must experiments be able to exclude each other?Interaction controlYes: overlapping by default, with mutually exclusive groups (layers) where teams ask for them
Is the platform also the feature-flag and rollout system?Integration scopeYes: flags, gradual rollouts, kill switches and experiments share one configuration and evaluation system
Are multi-armed bandits and causal inference without randomisation in scope?Scope controlBandits and observational methods are mentioned as variants; the core is randomised A/B/n tests

Requirements#

Functional requirements#

  1. Configure experiments. Create an experiment with a hypothesis, variants and their parameter values, targeting rules, traffic allocation, randomisation unit, primary and guardrail metrics, and a planned duration. Validate it, get approval when required, start it, ramp its traffic, pause it and stop it. Keep a full version history.
  2. Assign deterministically. Given a unit id and an experiment, every SDK and service returns the same variant, without a network call on the request path, and independently of other experiments unless they are configured to exclude each other.
  3. Manage interactions. Support overlapping experiments, mutually exclusive experiments, and long-running holdouts.
  4. Serve flags and rollouts. Evaluate feature flags with targeting rules, percentage rollouts and kill switches through the same rules engine as experiments.
  5. Log exposures. Record when a unit is exposed to an experiment variant, with enough context to deduplicate and analyse it, including counterfactual exposure for control users.
  6. Compute metrics. Turn product events into per-unit metrics for every running experiment, daily and intraday, handling late and out-of-order events.
  7. Analyse results. Produce a scorecard per experiment: effect, confidence interval and p-value for every metric, segment breakdowns, power and sample-size estimates, variance reduction, and corrections for continuous monitoring and multiple metrics.
  8. Protect users. Run data-quality checks (sample ratio mismatch, A/A checks, telemetry loss) and monitor guardrail metrics in near real time, alerting owners and automatically stopping experiments that cause severe harm.

Non-functional requirements#

  • Assignment latency: in-process evaluation in well under a millisecond (typically a few microseconds per flag); no remote call on the request path.
  • Config propagation: kill switches in under 1 minute, other changes in under 5 minutes, to every server and to apps on their next config fetch.
  • Availability: the request path must never depend on the platform being up. If the config service is down, SDKs keep serving the last known configuration; if that is missing, the code's compiled-in defaults (the control experience).
  • Correctness of assignment: the observed split of users must match the configured split within chance, for every experiment; violations are detected automatically.
  • Ingestion: about 2.3 million product events per second on average and about 7 million at peak, without loss; about 300,000 exposure events per second before deduplication.
  • Freshness: guardrail metrics within about 15 minutes of events; daily scorecards by mid-morning in the experiment owner's time zone.
  • Trustworthiness: the false positive rate must stay at the advertised α even when users peek; every number in a scorecard must be reproducible from stored data and a versioned metric definition.
  • Scale of analysis: thousands of experiments × hundreds of metrics × dozens of segments, recomputed daily within a few hours of compute.
  • Auditability and privacy: every configuration change is logged with who and why; experiment data follows the same retention and deletion rules as the product's event data.

Capacity Estimation#

All numbers below are assumptions of a realistic order for a large consumer company, chosen to match the clarifying questions. A day has 86,400 seconds, so 1 billion events a day is about 11,600 per second. See Back-of-the-Envelope Estimation.

Assignment (flag and experiment evaluations).

  • About 50 billion server requests a day ÷ 86,400 ≈ 580,000 requests per second on average, and about 1.7 million at a daily peak of three times the average.
  • Assume each request evaluates about 20 flags or experiments. That is about 1 trillion evaluations a day, or about 11.6 million per second on average and 35 million at peak.
  • One local evaluation costs a hash of a short string (about 50 to 200 nanoseconds for MurmurHash3 or FNV) plus a few rule checks, about 1 to 5 microseconds in total. At 2 microseconds, 11.6 million evaluations a second use about 23 CPU cores in total, spread over the whole fleet. That is negligible.
  • If instead every evaluation were a network call to an assignment service, that service would handle 11.6 million calls a second and add about 0.5 to 1 millisecond (one same-data-centre round trip) to every call. This single estimate decides the architecture: assignment must be computed locally, inside the SDK, from configuration pushed to it.

Configuration size and distribution.

  • About 2,000 running experiments at about 2 KB of rules each is about 4 MB. About 50,000 feature flags at about 500 bytes each is about 25 MB. The full ruleset is about 30 MB uncompressed.
  • That is fine for a server but too large and too revealing for a mobile app or a browser. So configuration is scoped: a server SDK downloads only the flags of its project (typically 100 KB to 2 MB), and a client SDK either downloads a small scoped ruleset or receives already-evaluated values for its user.
  • Server fleet: assume 100,000 service instances, each polling for changes every 30 seconds: about 3,300 config requests per second, almost all answered "not modified" from a CDN or a cache. A streaming connection (server-sent events) can replace polling for low-latency kill switches.
  • Clients: 300 million daily active users × about 4 app launches or page loads that fetch config = 1.2 billion fetches a day, about 14,000 per second on average and about 40,000 at peak. If the server evaluates per user and returns about 5 KB of assigned values, that is about 70 MB/s of response traffic at average load.

Exposure events.

  • Assume each daily user is exposed to about 30 experiments a day (the platform runs 2,000, but most are on specific surfaces or targeted segments).
  • SDKs deduplicate exposures in memory, but a user touches many server processes and several devices and sessions. Assume about 3 raw exposure events per (user, experiment) per day: 300 million × 30 × 3 ≈ 27 billion a day, about 310,000 per second on average, roughly 1 million per second at peak.
  • At about 120 bytes per event (unit id, experiment id, variant id, config version, time, surface, a few dimensions), that is about 3.2 TB a day raw, about 0.5 TB compressed in a columnar format.
  • After deduplication the platform keeps one row per (unit, experiment): the first exposure time and variant. With 2,000 running experiments and an average of 10 million exposed units each, that is about 20 billion rows, about 40 bytes each, about 800 GB.

Product events (the raw material for metrics).

  • About 200 billion events a day (page views, clicks, searches, purchases, crashes, latency samples): about 2.3 million per second on average and 7 million at peak.
  • At about 200 bytes each, that is about 40 TB a day raw, about 460 MB/s on average and 1.4 GB/s at peak. In compressed columnar files (Parquet or ORC) this is roughly 5 to 8 TB a day.
  • This is the same order of ingestion as a large metrics monitoring system, where hundreds of thousands of servers each send about a hundred measurements every ten seconds (several million points per second, about 1 GB/s). The same techniques apply: a durable log as a buffer, partitioning, batching, and pre-aggregation as early as possible.

Metric computation (the daily batch).

  • Step 1 turns raw events into a per-unit, per-day metrics table: 300 million users × about 300 metrics, stored sparsely (most users have zero for most metrics). About 50 non-zero values per user at 8 bytes each is about 120 GB a day.
  • Step 2 joins that table with exposures. Each day, about 300 million active users × 30 experiments = 9 billion (unit, experiment, day) rows. With about 50 metrics per experiment, that is about 450 billion metric values to aggregate per day, or up to about 2.7 trillion if every experiment used all 300 metrics.
  • A vectorised columnar engine aggregates roughly 10 to 100 million values per second per core, depending on the work. At 10 million, 2.7 trillion values is about 270,000 core-seconds, or 75 core-hours. Shuffles and joins multiply this several times. Something like 500 to 1,000 core-hours a day, or about 1,000 cores for under an hour, is a realistic budget. That is a modest Spark or warehouse job.
  • Step 3 writes sufficient statistics (counts, sums and sums of squares; defined in deep dive 6) per (experiment, variant, metric, segment, day). With 2,000 experiments × 3 variants × 300 metrics × 30 segments, that is about 54 million rows a day at about 64 bytes, about 3.5 GB a day. The scorecard reads only this small table.

Near-real-time guardrails.

  • Assume about 20 guardrail metrics (crash rate, error rate, latency, revenue, sign-ups) monitored for every running experiment, in 5-minute windows: 2,000 × 3 variants × 20 metrics = 120,000 time series, each updated every 5 minutes. This is small for a stream processor.
  • The stream processor must know which experiments each event's user is in. Keeping the current exposures of active users in keyed state takes about 300 million users × 30 experiments × 8 bytes ≈ 72 GB, spread across the stream cluster.

Summary.

QuantityValue
Flag and experiment evaluations~11.6 million per second, in-process, a few µs each
Config payload~30 MB total; scoped payloads of 100 KB to 2 MB
Config fetches~3,300/s from servers, ~14,000/s from clients
Exposure events~310,000/s raw, ~3.2 TB/day; ~20 billion deduplicated rows
Product events~2.3 million/s average, ~7 million/s peak, ~40 TB/day raw
Daily metric computation~500 to 1,000 core-hours
Scorecard statistics~54 million rows/day, ~3.5 GB/day
Guardrail series~120,000, updated every 5 minutes

The takeaway: the request path is cheap if and only if assignment is local, and the heavy cost is in the data pipeline that turns events into per-unit metrics. The statistics themselves run on tiny summary tables.

Core Entities#

  • Experiment. Key, owner team, hypothesis, status (draft, running, stopped, decided, archived), randomisation unit, layer or exclusion group, targeting rule, metrics (primary, secondary, guardrails), planned duration, analysis method (fixed horizon or sequential), and decision.
  • ExperimentPhase (version). One immutable configuration of an experiment between two changes: variant weights, coverage, targeting, hash salt and start and end times. Ramping from 5% to 50% creates a new phase. Analysis always knows which phase each exposure came from.
  • Variant. Key ("control", "treatment_a"), weight, and the parameter values or flag values it sets.
  • Layer (universe, namespace). A group of experiments that are mutually exclusive with each other. A unit is in at most one experiment per layer. A layer owns a hash salt and a set of buckets.
  • Allocation. Which bucket ranges of a layer belong to which experiment, and which buckets within an experiment belong to which variant.
  • FeatureFlag (parameter, property). Key, type, default value, and an ordered list of rules: targeting, forced values, percentage rollouts, and experiment rules.
  • Segment (audience). A reusable targeting condition: country, platform, app version, employee, beta testers, a saved list of ids.
  • Holdout. A set of units excluded from all experiments and launches in a domain for a long period, with its own salt and percentage.
  • ExposureEvent. Unit id, unit type, experiment key, phase, variant, config version, timestamp, SDK and surface. Deduplicated into a FirstExposure row per (unit, experiment).
  • ProductEvent. Any event that metrics are built from: unit ids, event name, timestamp (event time and arrival time), properties.
  • MetricDefinition. Name, owner, type (mean, proportion, ratio, quantile), the event-level SQL or expression, aggregation, direction (higher is better or worse), and for guardrails the tolerated degradation. Versioned.
  • ResultSnapshot (scorecard). For one experiment, as of one data date: per variant and metric, the sufficient statistics, effect, interval, p-value, method, data completeness and warnings.
  • Alert and Decision. A guardrail or data-quality alert with its evidence, and the final ship, iterate or abandon decision with its rationale.

API Design#

The platform has a control plane (people and automation managing experiments), a delivery plane (SDKs getting configuration and evaluating it) and a data plane (exposures, events and results).

Control plane (REST, authenticated, audited)
POST  /v1/experiments                        create draft (hypothesis, unit, variants, metrics)
PUT   /v1/experiments/{key}/draft            edit draft; returns validation warnings
POST  /v1/experiments/{key}:start            {phase: {coverage: 0.05, weights: [0.5,0.5]}}
POST  /v1/experiments/{key}:ramp             {coverage: 0.5}   -> new phase
POST  /v1/experiments/{key}:stop             {reason, decision: "ship|abandon|iterate"}
GET   /v1/experiments/{key}/results?as_of=2026-12-04&segment=platform:ios
GET   /v1/power?metric=purchases_per_user&mde=0.01&audience=seg-123
 
Delivery plane (read-mostly, cacheable)
GET   /v1/sdk/{sdk_key}/rules              ETag; 304 Not Modified when unchanged
GET   /v1/sdk/{sdk_key}/stream             server-sent events: new ruleset version
POST  /v1/evaluate                         {unit: {id, type, attributes}} -> values (thin clients)
 
Data plane
POST  /v1/exposures      batched: [{unit, exp, phase, variant, cfg_ver, ts}, ...]
POST  /v1/events         batched product events (or through the existing event pipeline)
 
SDK interface (in-process, no network on the call)
variant  = xp.getVariant("checkout_button_v2", user)       // logs exposure
value    = xp.getValue("search.rerank.alpha", user, 0.3)  // parameter with default
enabled  = xp.isOn("new_onboarding", user)

Design notes:

  • Evaluation never blocks on the network. getVariant reads an in-memory ruleset. A background thread refreshes it. If the SDK has no ruleset at all (cold start with the config service down), it returns the default value written in the code, which is the control experience.
  • Every call that reads a variant logs an exposure. Logging happens at the point of use, not at assignment, so that analysis includes only units that reached the changed code (deep dive 5). The SDK deduplicates in memory and sends batches asynchronously.
  • Parameters, not just variant names. Variants set typed parameter values (search.rerank.alpha = 0.5). Code reads parameters, not experiment names, so an experiment can be restarted, re-randomised or replaced without a code change. Spotify describes this shift from flags named after experiments to typed "properties".
  • Config is versioned. Every ruleset has a monotonically increasing version. Exposures carry the version, so analysis can detect units that were evaluated with stale configuration.
  • Results are as-of a date. Scorecards are snapshots computed for a data date, with a completeness indicator, because late events change yesterday's numbers.
  • Thin clients may use remote evaluation. For mobile apps and browsers, POST /v1/evaluate returns values for one user. This hides the rules (and other experiments) from the client and keeps payloads small, at the cost of one call per app launch, which is cached on the device.
  • Control-plane writes are idempotent and audited. :start and :ramp take a client request id and record who made the change and why, because a ramp done twice or by mistake can damage both users and data.

High-Level Design#

We build the design one requirement at a time, starting from the simplest version that works, then assemble the pieces. The overall shape is a loop: configure, assign, expose, measure, analyse, decide.

1) Let a team configure an experiment safely#

The simplest version is a table of experiments and a web form. Asha, a product engineer, creates checkout_button_v2: unit = user id, two variants with weights 50/50, coverage 10% of eligible users, target = web users in three countries, primary metric = purchases per user, guardrails = page load time, errors, revenue per user. The Experiment Service stores this in a relational database (PostgreSQL is a natural fit: small, highly relational data with strong consistency needs and an audit trail).

Before the experiment may start, the service validates it, an idea described in the Google paper as automated checks before any data push. It checks:

  • Syntax and types: every parameter value matches the parameter's declared type; weights sum to 1.
  • Conflicts: no other running experiment in the same layer changes the same parameters for overlapping traffic.
  • Traffic availability: the layer has enough free buckets for the requested coverage.
  • A real control: there is a control variant, with the same targeting and the same randomisation as the treatments.
  • Metrics and power: a primary metric is chosen, and the planned duration gives enough power for the stated MDE (deep dive 8).
  • Risk: experiments on sensitive surfaces (payments, sign-up, legal text) need an approval from a second person.

A started experiment changes only through new phases: a ramp from 10% to 50% creates a new immutable phase rather than editing the old one. The lifecycle and its states are in deep dive 1.

2) Assign users to variants deterministically, with no network call#

The naive approach is to flip a coin per request and store the result in a database keyed by user. That fails twice: the coin gives the same user different variants on different requests unless every request does a database lookup, and the lookup would be on the critical path of every request (11.6 million evaluations a second, from the capacity section).

The standard solution is a hash. For each experiment, compute

bucket = hash(salt + ":" + unit_id) mod 10,000

and give bucket ranges to variants: buckets 0 to 4,999 to control and 5,000 to 9,999 to treatment, for a 50/50 split. A good hash function spreads ids uniformly and unpredictably over the buckets, so the split is random. The same unit id always gives the same bucket, on every server, in every language, with no storage at all. A salt that is different for every experiment (or layer) makes the bucket of a user in one experiment independent of their bucket in another. Deep dive 2 covers hash choice, salts, coverage and ramps, sticky assignment and identity.

3) Deliver configuration to every SDK within minutes#

The SDKs need the rules. The Config Compiler turns the database state into a ruleset snapshot: a compact JSON or Protocol Buffers document with every flag, its rules, every running experiment's targeting, salts and bucket ranges, and a version number. A new snapshot is built whenever anything changes, typically within seconds.

Snapshots are scoped per project and environment and published to object storage behind a CDN (immutable files named by version, plus a small "latest version" pointer). Server SDKs poll the pointer every 30 seconds, or keep a streaming connection that announces new versions; either way they download only when the version changes. Kill switches use the streaming path to reach servers in seconds. Client SDKs fetch on app launch and in the background.

The key property is that the delivery plane is off the request path and can fail without harm. If the CDN or the config service is down, every SDK keeps its last snapshot in memory and on local disk. If an SDK has never received a snapshot, it uses the defaults compiled into the code. LinkedIn wrote that its redesign brought experiment deployment latency down to under 5 minutes, compared with hours when a test needed a service config change and a deploy, which is the target our design meets with a margin.

4) Let many experiments run at once#

If every experiment needed its own slice of users, 2,000 experiments would leave each about 0.05% of traffic, far too little to detect small effects. So experiments must overlap: one user is in many experiments at once. Overlap is safe when experiments change unrelated things (the checkout button and the search ranker), because random, independent assignment spreads one experiment's effect evenly over the other's variants.

Overlap is not safe when two experiments change the same thing, such as two experiments that both set the colour of the same button, or both change the same ranking weight. For these the platform offers layers: each layer has its own salt and its own set of buckets, and within a layer each bucket belongs to at most one experiment. Experiments in the same layer are mutually exclusive; experiments in different layers overlap independently. This is the core idea of the Google design (layers and domains), Spotify's domains and exclusivity, and GrowthBook's namespaces. Deep dive 3 covers it in depth, including holdouts and how to reuse buckets without bias.

5) Record who was exposed#

Assignment is a pure function, so in principle we could compute who was in which variant afterwards, offline, from the user ids. That is not enough, for two reasons. First, a user assigned to the checkout experiment who never reached checkout could not be affected, and including them adds noise that hides the effect (dilution). Second, what the SDK actually did may differ from what the rules say: an old app version that ignores the parameter, a stale config, a crash before the page rendered.

So the SDK logs an exposure event at the moment code reads the variant: unit id, experiment, phase, variant, config version, time. It deduplicates in memory (one event per unit, experiment and variant per process per hour, say) and sends batches to an Exposure Collector, which writes them to a partitioned log (Apache Kafka is the common choice; see Apache Kafka in Practice). For the control group the SDK logs exactly the same event at exactly the same point, even though nothing visible changes. This counterfactual logging keeps the two groups comparable. Deep dive 5 covers what to log and when, triggered analysis, and the volume problem.

6) Turn events into metrics for every experiment#

Product events (clicks, purchases, crashes) already flow through the company's event pipeline. The metrics pipeline has three stages:

  1. Ingest and land: events and exposures stream through Kafka into a data lake in columnar files, partitioned by event date and hour, keeping both the event time and the arrival time.
  2. Per-unit metrics: a daily batch job computes, for every unit and day, the value of every metric in the metric catalog (purchases, revenue, sessions, latency samples), using versioned SQL definitions.
  3. Experiment aggregation: the job joins per-unit metrics with first-exposure rows, keeps each unit's data from its first exposure onwards, and reduces it to sufficient statistics per experiment, variant, metric and segment: count, sum, sum of squares, and a few cross products.

A streaming path computes the same thing for a small set of guardrail metrics every few minutes. Both paths must handle events that arrive late or out of order (mobile devices that were offline, retried uploads, delayed batches). Deep dive 6 covers all of this.

7) Analyse results with trustworthy statistics#

The Statistics Engine reads the sufficient statistics and computes, for each metric, the difference between treatment and control, its confidence interval and its p-value. For a mean metric that is Welch's t-test; for a ratio metric such as click-through rate per page view it uses the delta method; for skewed metrics it caps outliers; it applies CUPED variance reduction using each unit's pre-experiment behaviour; it applies sequential testing so that results stay valid when people look every day; and it controls false discoveries across many metrics. Deep dives 7 to 10 explain each method and why it is needed.

The output is a scorecard: a table of metrics with effects and intervals, colour-coded, with data-quality checks (sample ratio mismatch first) at the top, so that a broken experiment is flagged before anyone reads its results.

8) Watch guardrails in near real time and stop harmful experiments#

A bad experiment can do a lot of harm before a daily scorecard notices. The Guardrail Monitor reads the streaming guardrail statistics every few minutes and runs a sequential test for each (experiment, guardrail metric) pair: is the treatment's crash rate, error rate or latency worse than control by more than the tolerated margin? Uber described this pattern: periodic treatment-versus-control comparisons of business metrics during the experiment, using a sequential test so that checking often does not create false alarms, with alerts or automatic pausing on a significant degradation.

When the evidence of harm is strong, the monitor calls the Experiment Service to stop the experiment (set its coverage to 0, which sends everyone to the control experience) and pages the owner. Because stopping is just a config change, it reaches servers in seconds through the streaming path. Deep dive 11 covers guardrails, data-quality checks and the auto-stop policy.

9) Unify experiments with feature flags and rollouts#

An experiment is mechanically a feature flag whose value depends on a random bucket. Rather than run two systems, the platform has one rules engine: each flag has a default value and an ordered list of rules (force a value for employees, run an experiment for 10% of web users, roll out to 30% of everyone). When an experiment ends with "ship", the treatment becomes a 100% rollout rule, and later the flag is removed from the code. Deep dive 4 covers evaluation order, kill switches, rollouts with guardrails and flag debt.

The full high-level design#

ComponentResponsibilityTechnology choices
Experiment UI and APICreate, validate, start, ramp, stop; read scorecardsWeb app plus REST API; SSO; audit log
Experiment ServiceSource of truth for experiments, flags, layers, phasesStateless service over PostgreSQL
Validation and power checksConflicts, traffic availability, control present, sample sizePart of the Experiment Service; queries historical metric variance
Config CompilerBuild versioned, scoped ruleset snapshots on every changeEvent-driven job; output JSON or Protocol Buffers
Snapshot storage and CDNServe snapshots to SDKs; survive control-plane outagesS3 or GCS plus a CDN; ETags; immutable versioned files
Streaming notifierPush "new version" to servers for fast kill switchesServer-sent events or gRPC streams behind a load balancer
Remote evaluation serviceEvaluate for thin clients; hide rules; small payloadsStateless service running the same SDK; cached per user on device
Server and client SDKsLocal evaluation by hashing; exposure logging; fallbacksOne spec, many languages, shared conformance tests
CollectorsReceive batched exposures and events; validate; forwardStateless HTTP endpoints writing to Kafka
KafkaDurable buffer, replay, fan-out to batch and streamPartitioned by unit id; several days of retention
Data lakeLong-term raw events and exposuresParquet or ORC on object storage; Iceberg, Delta or Hive tables
Daily metric jobsPer-unit metrics, exposure join, sufficient statisticsSpark, or SQL in BigQuery, Snowflake or Presto/Trino
Stream processorGuardrail statistics every few minutesApache Flink with keyed state (Apache Flink and Stream Processing)
Sufficient statistics storeSmall summary tables for fast scorecardsPostgreSQL, or an OLAP store (ClickHouse, Druid, Pinot) for slicing
Statistics engineTests, intervals, CUPED, sequential, multiple testing, SRMPython or JVM service with a well-tested statistics library
Guardrail monitorSequential tests on streaming guardrails; auto-stopScheduled service; calls the Experiment Service API

Key Flows#

Flow 1: Create, validate and start an experiment#

Asha creates the draft, the platform checks it, a reviewer approves it, and the start becomes a new ruleset version that reaches every SDK.

The important details:

  • Idempotency. The start carries a client request id. A retried click does not create two phases. See Idempotency and Safe Retries.
  • Allocation is a transaction. Taking buckets 0 to 499 of the checkout layer and marking the experiment as running happen in one database transaction, so two experiments can never be given the same buckets.
  • Atomic swap. The SDK builds the new ruleset beside the old one and replaces a single pointer. A request never sees half of version 18451 and half of 18452.
  • Start time is the phase start. Analysis uses the phase start time from the database, not the time the SDK received the config, and drops exposures stamped with older config versions after a grace period.

Flow 2: A request is assigned, exposed and logged#

Kai opens the checkout page. The checkout service evaluates the flag checkout.button_style, which has an experiment rule.

The request is never slowed by logging: the SDK returns the value first and logs in a background thread with a bounded queue. If the queue fills (the collector is down), the SDK drops the oldest exposures and counts the drops in its own metric. The drop count matters: if treatment exposures are dropped more often than control exposures (for example, because the treatment page is heavier and the browser is closed before the batch is sent), the result is a sample ratio mismatch, which deep dive 12 explains.

Flow 3: The daily analysis#

Every night, after the previous day's events have mostly landed, the pipeline computes metrics and scorecards.

Two runs per day matter here. The first run for date D happens once the data is about 95% complete, so owners have results by mid-morning. A second run the next day recomputes date D with the late events (mobile devices that came back online, delayed partner feeds). The scorecard shows the completeness of each day so that nobody reads a partial number as final.

Flow 4: A guardrail breach stops an experiment#

Sam's experiment ranker_v7 makes search slower for some queries. The guardrail monitor catches it within 20 minutes of the ramp to 50%.

The design choices that make this safe:

  • Stopping is the safest action. Stopping sends everyone to the control experience, which is the product that ran before the experiment. It cannot make things worse than they were before the experiment started. Auto-stop is never "ship the treatment".
  • Two-window confirmation for automatic actions. A single window can be distorted by a deploy or a short outage. Alerts fire on one window; automatic stops need the evidence to hold in two consecutive windows, or to be extremely strong in one.
  • The policy belongs to the experiment. Each guardrail has a severity: "alert only", "alert and pause ramping", or "auto-stop". Payments and crash guardrails usually auto-stop; softer metrics only alert.

Data Model#

The control plane is relational, small and strongly consistent. The data plane is columnar, huge and append-only. They link through experiment keys, phase ids and config versions.

CREATE TABLE experiment_phase (
  phase_id       BIGSERIAL PRIMARY KEY,
  exp_key        TEXT NOT NULL REFERENCES experiment(exp_key),
  phase_no       INT  NOT NULL,
  coverage       NUMERIC(5,4) NOT NULL CHECK (coverage BETWEEN 0 AND 1),
  weights        JSONB NOT NULL,          -- {"control":0.5,"treatment":0.5}
  targeting      JSONB NOT NULL,          -- compiled condition tree
  variant_salt   TEXT NOT NULL,           -- new salt per re-randomisation
  started_at     TIMESTAMPTZ NOT NULL,
  ended_at       TIMESTAMPTZ,
  created_by     TEXT NOT NULL,
  change_reason  TEXT NOT NULL,
  UNIQUE (exp_key, phase_no)
);
 
CREATE TABLE layer_allocation (
  layer_id     TEXT NOT NULL REFERENCES layer(layer_id),
  bucket_start INT  NOT NULL,             -- inclusive
  bucket_end   INT  NOT NULL,             -- exclusive
  exp_key      TEXT REFERENCES experiment(exp_key),  -- NULL = free
  EXCLUDE USING gist (layer_id WITH =,
    int4range(bucket_start, bucket_end) WITH &&)
);
 
-- Data plane (lake table, partitioned by exposure date)
-- first_exposure(unit_id, unit_type, exp_key, phase_id, variant_key,
--                first_seen_ts, cfg_version, platform, country)
-- metric_daily(unit_id, date, metric_id, value)            sparse
-- exp_stats(exp_key, phase_id, variant_key, metric_id, segment, date,
--           n, sum_x, sum_x2, sum_y, sum_y2, sum_xy)       sufficient stats

Notes on the model:

  • The exclusion constraint on layer_allocation makes the database itself refuse overlapping bucket ranges in a layer. That is the strongest guarantee of mutual exclusion: no application bug can allocate bucket 300 twice.
  • Phases are immutable. Every change that alters who is in the experiment, or which variant they get, creates a new phase. Analysis can then decide which phases to pool (deep dive 12 shows why pooling across weight changes can be wrong).
  • The salt lives on the phase. Re-randomising (restarting with fresh assignment) means a new salt, which is how carryover from a previous run is broken (deep dive 3).
  • First exposure is the analysis anchor. For each unit and experiment, keep the first time and variant seen. A unit that later shows a different variant (a data or identity problem) is flagged, not silently counted twice.
  • The sufficient statistics table is tiny compared with the raw data, and contains everything the statistics engine needs: sums for the metric (x), for the pre-period covariate (y), and their cross product for CUPED.
  • Storage choices. PostgreSQL for the control plane (PostgreSQL in Practice); Parquet tables in object storage for exposures, events and per-unit metrics; a small OLAP store or PostgreSQL for the sufficient statistics.

An experiment moves through a small number of states. Making the states explicit lets the platform enforce rules such as "a running experiment cannot change its metrics without a new phase" and "a decided experiment must eventually clean up its flag".

Deep Dives#

1. Experiment configuration and lifecycle#

What an experiment really is. An experiment record holds three kinds of information that change at different speeds:

  • The question: a hypothesis ("a green button raises purchases per user by at least 1%"), the randomisation unit, the primary metric, the guardrails and the decision rule. This should be fixed before the start. Changing the primary metric after looking at the data is a classic way to find false wins, because some metric will always look good by chance.
  • The treatment: variants and their parameter values. This must not change during a phase. If the treatment changes, it is a different experiment and needs a new phase or a new experiment, otherwise the analysis mixes two treatments.
  • The traffic: coverage, weights and targeting. This changes during ramps, each time as a new phase.

Validation before start. Configuration mistakes are the most common cause of bad experiments, so the platform checks as much as it can automatically, and refuses to start an experiment that fails a hard check:

CheckExample failure it catchesHard or soft
Parameter types and rangesA string where a number is expected; a timeout of 0Hard
Conflicting parametersTwo running experiments in different layers both set search.rerank.alpha for overlapping usersHard
Bucket availabilityThe layer has only 3% free but the experiment asks for 10%Hard
Control present and comparableTreatment targeted to iOS, control to all platformsHard
Metric and unit compatibilityMetric "revenue per user" on a session-randomised experimentSoft (warn)
Power80% power needs 38 days at 5% coverage, the plan says 14Soft (warn)
ApprovalPayments surface requires a second reviewerHard
Collision with a freezeHoliday code freeze, or a large launch in the same areaSoft

The Google paper describes the same approach: configuration is data that is pushed separately from binaries, so it changes much more often than code, and that is only safe with automated checks before each push. Spotify lists "property collisions" (two experiments setting the same property for the same users) among the checks it performs before and during an experiment.

Data push separate from code push. In the code, the engineer writes something like style = xp.getValue("checkout.button_style", user, "blue") and ships it with the default. From then on, experiments that set checkout.button_style can be created, ramped and stopped with no deploy. The code path for "green" must already exist in the binary, of course; the experiment only chooses between paths that exist. This separation is what turns a weekly release train into hundreds of experiment changes a day.

Ramping. A new experiment starts small (1% or 5%) and grows as confidence grows. The reason is simple: many bad experiments are plain bugs, and bugs show up immediately. Kohavi's 2014 paper reminds readers that a small JavaScript error can make checkout impossible. At 1% coverage such a bug touches 1% of users for the minutes it takes a guardrail to fire; at 50% it touches half of them. So ramp only after the automated checks at the current stage pass. A common ramp plan:

StageTrafficPurposeTypical length
InternalEmployees only (forced variant)Does it work at all?1 to 3 days
Canary1% of target usersCatches crashes, errors, big latency changesHours to 1 day
Measurement10% to 50% (balanced, usually 50/50 of the coverage)Main analysis, full power1 to 4 weeks
Launch100% via rollout ruleShip the winnerPermanent until code cleanup

LinkedIn's T-REX models this directly: a "test" is the long-lived object a team works with, and each ramp step (5%, 25%, 50%, 100%) creates an immutable "experiment" inside it. That gives the analysis one clean, unchanging population per step. Our phases are the same idea.

Re-randomisation. If a phase had a bug, the platform should not simply fix it and continue with the same assignment. The users in the buggy treatment have already been affected, and that carryover can last weeks (deep dive 3 has numbers). Restarting with a new salt gives a fresh, independent assignment. The UI should make "restart with new randomisation" the default action after a bug fix.

Ending. An experiment ends with a decision: ship, iterate (run a new version) or abandon. The decision is recorded with its reasoning, because a searchable record of past experiments ("what did we learn about checkout?") is one of the most valuable things a platform produces. Shipping turns the winning variant into a 100% rollout rule on the flag, and creates a cleanup task to delete the flag from the code (deep dive 4).

2. Deterministic assignment by hashing#

The three requirements. The KDD 2019 paper by Fabijan and colleagues on sample ratio mismatch lists three requirements for an assignment mechanism. Each one has broken in practice.

  1. Equal probability per variant (according to the weights). Every unit must have exactly the configured chance of each variant.
  2. Consistency. A unit must get the same variant every time, on every server and device that uses the same id, for the whole phase.
  3. Independence across experiments. A unit's variant in one experiment must not predict its variant in another, unless the two are deliberately linked (layers, holdouts).

The hash. Assignment computes h = H(salt, unit_id), reduces it to a bucket, and looks up the bucket's variant. What matters about H:

  • Uniformity. Every output bucket must be equally likely. Most decent non-cryptographic hashes pass this for typical id formats.
  • Avalanche. Changing one character of the input changes about half of the output bits. Without this, similar ids (u-1000, u-1001) get similar buckets, and if ids are allocated in order (for example, sign-up order), the variants would correlate with account age.
  • Independence between salts. H("exp1", id) and H("exp2", id) must behave like independent random numbers.
  • Portability and speed. Every SDK in every language must compute exactly the same value. That rules out language-specific string hashes such as Java's String.hashCode, which differs across languages and has poor avalanche.

Common choices are MurmurHash3 (fast, good mixing, widely available), FNV-1a (very simple, fast, but weaker mixing on short inputs) and MD5 or SHA-1 truncated (slower, about 0.3 to 1 microsecond for a short string, but very well mixed and available everywhere). Speed rarely matters at a few microseconds per evaluation; mixing quality and portability matter more.

A real lesson from GrowthBook's SDK specification. The GrowthBook SDK spec documents two hashing versions. Version 1 computed fnv32a(value + seed) mod 1000. The spec states plainly that this original version had a flaw that caused bias when experiments ran in parallel. Version 2 hashes twice, n = fnv32a(fnv32a(seed + value) + ""), then takes bucket = (n mod 10000) / 10000. Hashing the output again mixes the bits better, so one user's buckets in different experiments behave independently, and the larger modulus gives finer granularity. Version 1 is kept only so that existing experiments keep their assignments. Two lessons follow: choose the hash carefully at the start, because changing it re-randomises everyone, and version the hashing algorithm in the config so old experiments keep the old algorithm while new ones use the new one.

Buckets and ranges. Using 10,000 buckets gives a resolution of 0.01%. For an experiment with coverage c and weights w₁, w₂, …, the platform gives each variant a contiguous range. GrowthBook's getBucketRanges does this: with coverage 0.5 and weights 0.5/0.5, control gets the range from 0 up to 0.25 and treatment the range from 0.5 up to 0.75 (each end excluded). Each variant's range starts at its cumulative weight and has length coverage × weight. The useful property: raising the coverage only extends each range, so a user who was in treatment at 50% coverage stays in treatment at 100%. Users never switch variants during a ramp; new users are only added.

That property breaks if the weights change. Moving from 50/50 to 80/20 shifts the boundary, and some users move from one variant to the other. That is why weight changes are a new phase, and usually a re-randomisation.

Two-level hashing in a layer. With layers, one hash decides which experiment in the layer owns the unit, and a second, independent hash decides the variant within it:

// Shared spec: every SDK implements exactly this.
function bucket(salt: string, unitId: string): number {
  const h = murmur3_32(salt + ":" + unitId);   // 32-bit unsigned
  return h % 10000;                             // 0..9999
}
 
function assign(exp: Experiment, layer: Layer, unit: Unit): string | null {
  const id = unit.ids[exp.unitType];            // user id, device id, ...
  if (!id || !matches(exp.targeting, unit.attrs)) return null;
  const lb = bucket(layer.salt, id);            // which experiment owns it
  if (!exp.layerRanges.some(r => lb >= r.start && lb < r.end)) return null;
  const vb = bucket(exp.phase.salt, id);        // which variant
  for (const v of exp.phase.variantRanges) {
    if (vb >= v.start && vb < v.end) return v.key;
  }
  return null;                                  // outside coverage
}

The second hash must use a different salt from the layer hash. If it reused the layer hash, the experiment owning buckets 0 to 999 would see only variant buckets 0 to 999, and with a 50/50 range split at 5,000 everyone would land in control.

The salt collision problem. If two experiments accidentally share a salt (both use the default seed, or the salt is the experiment name and someone reuses a name), their assignments are identical: everyone in treatment for one is in treatment for the other, and the effects are confounded. The SRM paper makes this point with the birthday paradox: with only 365 possible seeds, 23 experiments already have about a 50% chance that two share a seed. The fix is to draw salts from a large space (a random 64-bit value or a UUID generated at phase creation) and to have the platform, not the user, choose them.

Sticky bucketing. Pure hashing is consistent only as long as the inputs do not change. Three things break it: weight changes, a new salt, and changes to targeting attributes (a user who moves country). For experiments where switching variants would harm users or the analysis, the SDK can store the assignment: GrowthBook calls this sticky bucketing, saving the assigned variant per (attribute, experiment) in a cookie, local storage or a server-side store and reusing it before hashing. The cost is storage and a lookup, plus complexity when a sticky assignment must be forcibly reset. A common default: sticky on clients for UI experiments, pure hashing on servers.

Identity. The unit id is the input, so identity problems become assignment problems:

  • Logged-out users have only a device or cookie id. When they log in, their user id differs, so they may change variant. Options: randomise sign-up flows by device id; randomise logged-in experiences by user id; and keep a mapping table to analyse "device then user" journeys.
  • Multiple devices. User-id randomisation keeps a user consistent across phone and laptop; device-id randomisation does not.
  • Cookie churn. Browsers clear cookies, so the same person can appear as several units in a cookie-randomised experiment. This dilutes effects and inflates the unit count, but does not bias the comparison as long as churn is the same in both variants. If the treatment itself causes more cookie churn (say, a new login flow that resets cookies), it biases the comparison and usually shows up as an SRM.

Choosing the unit of randomisation. The unit must be at least as coarse as the unit of analysis and the unit of interference. Randomising by page view and analysing per user breaks independence (one user's page views are correlated), so the variance formula must account for it with the delta method (deep dive 7). Randomising by user when users affect each other (a marketplace, a social feed) needs cluster or switchback designs (deep dive 12).

3. Layers, domains and interactions#

Why overlap is usually fine. Suppose experiment E1 tests the button colour and E2 tests the search ranker, with independent assignment. Half of E1's treatment users are in E2's treatment and half are in its control, exactly as for E1's control. So E2 adds the same noise to both groups of E1 and does not bias E1's comparison. Even if E2 has a large effect, it cancels out in E1's difference. The only cost is a little extra variance.

When overlap is not fine: interactions. Two experiments interact when the effect of one depends on the other. The classic example: E1 changes the button text colour to blue, E2 changes the button background to blue. Each is fine alone; together the text is invisible. Interactions are rare between unrelated areas, but real between experiments that touch the same component, the same parameter, or the same scarce resource (two experiments both adding a banner to the same slot).

Google's model. The Tang 2010 paper describes three nested ideas:

  • A layer is a set of parameters, such as "the UI parameters of the top ads". A request is in at most one experiment per layer, so experiments in a layer never overlap. Experiments in different layers overlap.
  • A domain is a slice of traffic with its own set of layers. A domain can be "non-overlapping" (one experiment can change any parameter) or contain many layers. Domains can nest, so the configuration is a tree.
  • A launch layer sits in the default domain and holds features that are on their way to being launched, so they can be tested on everything without conflicting with experiments.

Assignment walks the tree: at each domain, hash with that domain's function to pick a sub-domain or layer; in each layer, hash with that layer's function to pick at most one experiment. The paper's formula for the bucket is mod = f(cookie, layer) % 1000, with the layer id as part of the hash so that layers are independent. It also describes diversion types, the ways traffic is sent into an experiment. Random per query is a coin flip for every query, so one user's queries pop in and out of a visible change. Cookie mods are the common case. User-id mods work like cookie mods but use the signed-in user id. Cookie-day mods combine the cookie with the day, so the set of cookies in the experiment changes daily. The experiment's unit decides which type to use.

The infrastructure was first deployed in March 2007. The paper reports that it enabled nearly an order of magnitude more experiments, more launches and more people running experiments, helped by tools, automated checks and experimenter education that came with it.

Spotify's model. Spotify's 2020 posts describe domains (areas of the product, such as the home screen) in which experiments can be made exclusive to each other, so a user is in at most one of a set of experiments that could interfere. Exclusivity plus holdbacks makes allocation hard when teams start and stop experiments whenever they like. Spotify's answer is the "salt machine": users are hashed into buckets with HASH(user_id, SALT) mod buckets, using a tree of salts, and freed space can be reshuffled with a new salt without stopping running experiments.

The post works an example worth repeating in our own words. Eight buckets, all allocated. Two experiments end and free half the buckets. A new experiment E4 needs 25% of users. Taking the freed buckets directly would give E4 exactly the users of an experiment that just ended (100% overlap, so carryover bias). Instead, hash the free users again with a new salt into eight new buckets. Each new bucket now holds only half as many users as an original bucket (the free half of traffic spread over eight), so E4 needs four of them, not two, to reach 25%. Spotify calls this over-allocation the compensation factor: here 1 ÷ 0.5 = 2. The factor changes as experiments start and end, and the post says that, in their experience, new experiments should not start when it exceeds 5, because so much space is wasted. The lesson for our design: fresh randomisation of freed traffic avoids carryover, but exclusivity costs traffic, so it should be the exception, not the default.

GrowthBook's model. GrowthBook calls the same idea a namespace. Each namespace has an id. A unit's namespace position is hash("__" + namespace_id, unit_id), and an experiment in that namespace claims a half-open range from start (included) to end (excluded). Two experiments with non-overlapping ranges in the same namespace can never share a unit. This is mathematically the same as a layer.

Bucket reuse and carryover. When an experiment in a layer ends, its buckets become free. If the next experiment takes exactly those buckets, its users are not a fresh random sample: they were just exposed to the previous treatment. Kohavi's 2012 paper on puzzling outcomes reports that carryover effects lasted weeks and even up to three months in Bing experiments: users who had a bad experience used the product less long afterwards, and an A/A test on the reused buckets showed a significant difference. Three defences:

  • Re-salt the variant hash per experiment, so the previous treatment and control users are mixed evenly into the new experiment's variants. This removes bias in the comparison (both variants inherit the same mix). The new experiment's absolute level may still be shifted, which matters for some decisions.
  • Run a retrospective A/A test. Kohavi's paper describes computing the metric for the new variants over the pre-experiment period. If they already differ (they use a p-value threshold such as 0.2, much looser than 0.05, to be cautious), re-hash with a new seed and check again.
  • Leave buckets fallow. Do not reallocate freed buckets for a cooling-off period. This costs traffic.

Holdouts. A holdout is a long-lived slice of users (often 1% to 5%) that does not receive new launches in an area for a quarter or a year. Comparing the holdout with everyone else measures the combined, long-term effect of all the launches in that period, which can differ from the sum of the individual experiment results: some wins fade (novelty), some interact, and some were false positives. Spotify describes quarterly holdbacks per area. Uber describes a universal holdout. In the rules engine, a holdout is a highest-priority rule that, for the held-out users, skips every experiment and rollout in its scope and returns the defaults. GrowthBook implements holdouts with a "passthrough" mechanism: units outside the holdout pass through to the following rules.

Detecting interactions. Even with layers, some interactions slip through. With independent assignment, the platform can test for them directly: for every pair of experiments that overlap on enough users, fit the metric with the two treatment indicators and their product, and test the product term. With 2,000 experiments that is millions of pairs, so restrict it to pairs on the same surface or with shared parameters, and correct for multiple tests (deep dive 10). Practitioners at large platforms commonly report that strong interactions between unrelated experiments are rare, which is why overlap is the usual default; the interaction check is there to catch the exceptions.

4. Feature-flag integration#

One rules engine. Flags come in a few kinds. The Wikipedia page on feature toggles names release toggles (hide unfinished code until it is ready, then remove the toggle) and business toggles (kept long term because they serve a different purpose), and describes toggles used as operational controls, such as a kill switch that turns a feature off during an incident. Add experiment toggles (A/B tests) and permission toggles (beta users, paid tiers). They differ in lifetime and in how often they change, but each one evaluates a rule for this unit and returns a value. One engine and one SDK serve them all, with the flag's type recorded so lifetimes can be enforced.

Rule evaluation order. For each flag, the SDK walks an ordered list of rules and stops at the first that applies. The GrowthBook SDK spec is a good public example of a complete order. For an experiment rule, the spec's checks are roughly:

  1. A query-string override (for QA, if enabled in the environment).
  2. A forced variation set in code or by an internal tool.
  3. Is the experiment active? If not, return the default.
  4. Get the hash attribute (user id), or a fallback attribute (device id) when the primary is missing. No id means no experiment.
  5. If sticky bucketing is enabled, look up a saved assignment.
  6. Filters and namespace: is the unit in this experiment's namespace range and filters?
  7. Targeting condition: do the unit's attributes match?
  8. Compute the bucket and choose the variation; if the bucket is outside every range, not in the experiment.
  9. If QA mode is on, return the variation without tracking.
  10. Fire the tracking callback (the exposure log), deduplicated per (hash attribute, value, experiment key, variation) so repeated calls do not flood the pipeline.

For feature flags, the rules are of three kinds: force (a fixed value for a condition, such as employees), rollout (a value for a percentage of units, by hash), and experiment (as above). A typical list for checkout.button_style:

OrderRuleApplies toResult
1Holdout (passthrough for others)2% checkout holdoutDefault "blue", stop
2ForceEmployees"green" (dogfooding)
3Experiment E1Web, 3 countries, 10% coverageHash decides "blue" or "green"
4Rollout30% of iOS users"green"
5DefaultEveryone else"blue"

Kill switches. An ops toggle such as payments.new_processor.enabled must turn off in seconds, everywhere. The flag's kill path is the same as an auto-stop: a config change, compiled, pushed through the streaming notifier. Two extra rules apply. The kill state must win over every other rule (it is rule 0). And the code must handle the "off" path even when the config service is unreachable, which means the compiled-in default for a risky flag should be the safe value.

Rollouts with guardrails. After an experiment says "ship", rolling out to 100% is not risk-free: the experiment ran at 50% for two weeks, and the full rollout may hit capacity limits, or interact with something new. Spotify describes rollouts as a product feature: a gradual ramp where the platform compares rolled-out and not-yet-rolled-out users on guardrails and recommends "continue", "abort" or "wait". The statistics are the same as for experiments, applied to a ramp. Rollouts should use sequential tests (deep dive 9), because they are watched continuously by design.

Flag debt. Every flag adds a branch to the code. Ten thousand stale flags make the code hard to reason about, slow down evaluation, and enlarge the config payload. The Wikipedia page on feature toggles calls this "toggle debt". Practical defences:

  • Every flag has an owner, a type and an expected lifetime. Release and experiment flags get an expiry date.
  • The platform reports flags that have served one value to 100% of traffic for 30 days, and opens a cleanup ticket.
  • Static analysis finds flag keys in the code that no longer exist in the config (and the reverse).
  • A decided experiment cannot be archived until its flag is gone.

Thin clients and remote evaluation. A mobile app cannot download the 30 MB ruleset, and it must not see other teams' experiments or targeting rules (they may reveal unreleased features or business logic). So client SDKs usually call POST /v1/evaluate on launch, receive the values for this user, and cache them. Three consequences:

  • Exposure logging still happens on the client, at the point of use, not when the server evaluated. The server returns values; the client logs exposure when it renders the screen.
  • Values apply at a stable point. Spotify describes the "Config Assigned" and "Config Applied" pair: the app fetches new values in the background but applies them on the next launch, so a screen does not change in front of the user. Exposure is when the value is applied.
  • Offline behaviour. The app uses cached values; if it has none, it uses its defaults. Analysis must accept that a mobile user can be exposed hours after assignment.

LinkedIn's T-REX reports the payoff of local evaluation: with the evaluation library running in-process, 98% to 99% of evaluations are served from local memory; a backend cache serves more than 93% of the rest, so less than 0.2% of evaluations reach storage and less than 2% need a network call at all.

5. Exposure logging and triggering#

Assignment versus exposure. Assignment is computed whenever code asks for the variant. Exposure means that the unit actually encountered the difference. Ideally the code asks for the variant only at the moment it uses it, so that the two coincide. In practice, code often evaluates flags early (in middleware, at app start, or when building a page that has many sections), and many evaluated users never see the changed part.

Why it matters: dilution. Suppose an experiment changes the checkout page and 10 million users are assigned to it, but only 1 million reach checkout. If the change raises checkout conversion by 2%, the average effect over all 10 million assigned users is about 0.2%, and the variance comes from all 10 million. The test statistic is roughly the effect divided by its standard error. Diluting by a factor of 10 divides the effect by 10, and the standard error falls by only about √10 ≈ 3.2 (it is also inflated by the noise of the 9 million unaffected users). So the dilution costs roughly a factor of 3 in z-score, or about a factor of 10 in the sample needed. Triggered analysis, analysing only units that reached the changed code, is the single biggest power improvement in many experiments.

Triggering must be symmetric. The key rule: the condition for logging exposure must be the same in control and treatment, and must not depend on the treatment. For a checkout button test, log exposure when the checkout page renders, in both variants. Do not log "when the green button is shown", because control never shows it. This is counterfactual logging: control units record "I would have seen the treatment here". The Google paper describes this approach, with the experiment's code computing and logging what the treatment would have done even for control, and Kohavi's papers stress that triggered analysis is valid only when the trigger is computed identically for both groups.

Some triggers need more than the page view. A ranking experiment may change results only for some queries. The most powerful trigger is "the treatment's results would differ from control's for this query", which requires computing both rankings for every query in both groups, and logging whether they differ. That doubles the ranking cost for the triggered experiments, which is why it is used selectively, for experiments where power matters most.

When to log, in practice.

  • Server SDK: the exposure callback fires inside getVariant. Engineers are told to call it at the point of use, not in middleware.
  • Client SDK with remote evaluation: the server's evaluation is an assignment, not an exposure. The client logs exposure when it renders the screen. Spotify's design is the clearest public description: the Config Assigned event says which values the user fetched, the Config Applied event says the app actually started using them, and exposure is assembled from both. Because values change only on app relaunch, the exposure time is the relaunch.
  • Emails and notifications: exposure is the send time (or the open time for content changes inside the email, if the open is tracked identically in both variants).
  • ML models: exposure is the first time the model's output was used for this unit.

Deduplication and volume. Naive logging creates an event per evaluation. With 1 trillion evaluations a day, that would be several hundred terabytes a day, an order of magnitude more than all product events. Spotify's post gives a real example of the problem: its previous system, ABBA, produced exposure-related events that made up about 25% of Spotify's total event volume, partly because flags mapped one to one with experiments. Defences:

  • In-process deduplication: an LRU set of (unit, experiment, variant) recently logged; a hit skips logging. GrowthBook's spec deduplicates its tracking callback on (hash attribute, value, experiment key, variation). With a 1-hour expiry, our estimate fell to about 3 events per (user, experiment) per day.
  • First-exposure tables: downstream, keep only the first exposure per (unit, experiment, phase). The raw stream can be kept for a short time for debugging.
  • Sampling is not allowed. Unlike logs and traces, exposures must not be sampled per event. If an exposure is dropped, that unit is missing from the analysis; if drops are uneven between variants, the result is biased. Losses must be measured (SDKs count drops) and kept below a threshold.

The first-exposure join. The analysis join keeps a unit's metrics from its first exposure onwards. This matters: events before exposure could not be caused by the experiment, and including them dilutes the effect (or, if exposure correlates with activity, biases it). For daily metrics, the convention is to include the full day of first exposure (simpler, slightly diluted) or to compute the metric from the exposure timestamp (exact, more expensive). The platform should do one consistently.

Exposure data quality. Exposure is where many SRMs come from (deep dive 12). Two checks run on every experiment every day: the variant ratio of first exposures against the configured weights (chi-square SRM test), and the share of exposures with a config version older than the phase start (a high share means SDKs are not refreshing).

6. The metrics pipeline#

The shape of the data. Three data sets meet in the pipeline:

DataVolumeShapeUpdate pattern
Product events~200 billion a day, ~40 TB rawWide, many event types, many propertiesAppend-only, late arrivals for days
Exposures~27 billion raw, ~20 billion first-exposure rowsNarrowAppend-only, late arrivals
Metric definitionsHundreds to thousandsSQL or expressions, versionedChanges weekly

Ingestion at millions of events per second. Events arrive through collectors into Kafka at 2.3 million per second on average and 7 million at peak, about 1.4 GB/s. The same principles as any high-volume telemetry pipeline apply (see Pub/Sub and Event Streaming and Batch vs Stream Processing):

  • Batch at the edge. SDKs and collectors batch hundreds of events per request; per-event requests at this rate would need tens of times more collector capacity.
  • Partition by unit id. All events of a unit land in the same Kafka partition. That keeps the stream processor's per-unit state local and makes the per-unit aggregation a local operation.
  • Buffer and replay. Kafka retains several days, so a broken downstream job can be fixed and replayed without loss.
  • Land in columnar files. A loader writes Parquet files, partitioned by event date and hour, into a table format that supports atomic commits (Apache Iceberg, Delta Lake or Hudi). Atomic commits matter because the daily job must see either all of an hour's files or none.

Late and out-of-order data. A phone in airplane mode uploads yesterday's events this morning. A partner feed arrives once a day. A retry delivers a batch twice. The pipeline uses three ideas:

  • Event time, not arrival time. Metrics are computed on when the event happened. Each event also keeps its arrival time, so completeness can be measured.
  • Completeness thresholds. For each data date, the pipeline tracks the fraction of expected data that has arrived (estimated from the historical arrival curve). The first scorecard run waits until about 95%; a second run a day later recomputes with the late tail. The scorecard shows completeness, so nobody reads an incomplete day as final.
  • Idempotent writes. Events carry an id; the loader or the per-unit job drops duplicates. Recomputing a day replaces its partition rather than adding to it.

Late data can bias, not only delay. If the treatment makes the app upload events more slowly (a heavier screen, a changed batching policy), the treatment's day looks worse until the late data arrives. That is why the first run's results are marked provisional and why "events per unit" broken down by arrival delay is a useful diagnostic.

Step 1: per-unit metrics. The daily job turns events into one row per (unit, day, metric). Each metric in the catalog is a small, versioned definition, for example:

metric: purchases_per_user
version: 4
owner: commerce-analytics
type: mean                  # mean | proportion | ratio | quantile
unit: user_id
numerator:
  event: purchase_completed
  aggregation: count
  filter: "is_test_order = false"
cap: { method: percentile, value: 0.999 }    # winsorize heavy users
direction: increase_is_good
guardrail: { margin_pct: -0.5, severity: alert }

Defining metrics once, centrally, avoids the common failure where three teams compute "revenue" three ways and get three answers. Uber describes a catalog of over 1,000 metrics; Spotify describes a Metrics Catalog as part of its platform. The catalog lets the job compute many metrics from one scan of the events, grouping definitions by source table.

Step 2: join with exposures. For each experiment, join per-unit metrics with first exposure on (unit id), keeping days on or after the first exposure date and inside the phase window. The join is large (billions of rows on both sides) but both sides can be partitioned by unit id, so it is a co-partitioned join with no extra shuffle when the tables are bucketed the same way. Computing all experiments in one pass, rather than one job per experiment, is the key efficiency: the per-unit table is scanned once and exploded by the unit's experiments.

Step 3: sufficient statistics. The statistics engine does not need per-unit rows. For a mean metric it needs, per variant: the count n, the sum Σx and the sum of squares Σx². From these:

  • mean x̄ = Σx ÷ n
  • variance s² = (Σx² − n·x̄²) ÷ (n − 1)

For CUPED it also needs the pre-period covariate y per unit: Σy, Σy² and Σxy. For a ratio metric (clicks ÷ page views, per user) it needs the sums and squares of numerator and denominator and their cross product. These are additive: the statistics for 14 days are the sums of the daily statistics for units that are counted per day, and segments can be combined if they do not overlap. (For per-user metrics over the whole experiment, the platform aggregates per unit over the window first, then sums, because a user's 14-day total is not the sum of daily per-user statistics when computing squares.) That additivity is what lets a scorecard over 30 segments and 300 metrics load in under a second.

Cardinality. Segments multiply the output: 30 segments × 300 metrics × 2,000 experiments × 3 variants is 54 million rows a day, which is fine. But someone will ask for "breakdown by app version" (thousands of values) or "by city" (tens of thousands). Unbounded dimensions explode the table and, worse, produce thousands of segment tests, most of them noise (deep dive 10). Rules: a fixed list of pre-computed segment dimensions with bounded cardinality (platform, country group, new or existing user, app version bucket), and ad hoc breakdowns computed on demand from the per-unit table, with a warning about multiple testing.

Queries over weeks. A scorecard covers the experiment's whole duration, which may be weeks. Cumulative statistics for a window are built from per-unit window aggregates. To avoid rescanning 30 days every night, keep a running per-unit aggregate per experiment that each day's job updates incrementally, and recompute from scratch only when a metric definition changes. This is the same trade-off as roll-ups in a time-series database: pre-aggregate for the common query, keep the raw data for the rare one.

Compute and storage choices. Spark on a lake, or a cloud warehouse (BigQuery, Snowflake), or Presto/Trino over Iceberg, all work; the choice usually follows the company's existing data platform (Data Pipelines, Warehouses and Lakes). The sufficient statistics go into PostgreSQL or an OLAP store such as ClickHouse or Apache Pinot when analysts need interactive slicing.

7. Significance testing: means, proportions, ratios and quantiles#

The basic comparison. For a metric that is a per-unit mean (purchases per user), the estimated effect is Δ = x̄_T − x̄_C. Its standard error, without assuming equal variances, is

SE = √(s_T² ÷ n_T + s_C² ÷ n_C)

and the test statistic is t = Δ ÷ SE. This is Welch's t-test, which Wikipedia's A/B testing page calls the most commonly used test for comparing means. With hundreds of thousands of units per variant, t is effectively a standard normal z, so the 95% confidence interval is Δ ± 1.96 × SE, and the result is significant at α = 0.05 when |t| > 1.96.

A worked example. Asha's checkout test, day 14:

VariantUsers (n)Mean purchases per userStandard deviation
Control1,000,0000.2000.80
Treatment1,000,0000.2030.81

Δ = 0.003, a relative lift of 1.5%. SE = √(0.64 ÷ 10⁶ + 0.656 ÷ 10⁶) = √(1.296 × 10⁻⁶) ≈ 0.00114. t = 0.003 ÷ 0.00114 ≈ 2.63, two-sided p ≈ 0.009. The 95% interval is 0.003 ± 0.00223, that is [0.0008, 0.0052], or a relative lift of 0.4% to 2.6%. Significant, with a wide interval, which is honest: the true lift could be small.

Proportions. For a conversion metric (did the user buy, yes or no), x̄ is the conversion rate p and s² = p(1 − p). The same formula applies (a two-proportion z-test). For small counts the platform can fall back to Fisher's exact test, which Wikipedia lists for small samples, but at platform scale the normal approximation is almost always fine.

Ratio metrics and the delta method. Many metrics are ratios whose denominator is not the randomisation unit: click-through rate = clicks ÷ page views, with users randomised. Treating each page view as an independent observation is wrong, because one user's page views are correlated (a heavy clicker clicks on many of them). The variance would be underestimated and false positives would multiply.

The correct approach treats the metric as R = (Σ clicks) ÷ (Σ views) with sums over users, and uses the delta method, a first-order Taylor expansion, to get its variance. With per-user numerator Y and denominator X, means μ_Y and μ_X, and n users:

Var(R) ≈ (1 ÷ (n·μ_X²)) × (σ_Y² − 2R·σ_XY + R²·σ_X²)

Every term comes from the sufficient statistics: Σx, Σy, Σx², Σy², Σxy per variant. Uber lists the delta method among its standard methods; it is the workhorse of large platforms because it is cheap and exact enough at scale. The bootstrap gives the same answer more slowly.

Quantile metrics. Latency guardrails are usually percentiles (p95 page load time). A quantile has no simple sufficient statistic, and the per-request latencies are clustered by user. Options:

  • Bootstrap: resample users with replacement, recompute the quantile each time, use the spread of the results. Accurate but expensive: 1,000 resamples × billions of requests is prohibitive. A Poisson bootstrap (each unit gets a Poisson(1) weight per replicate, computed by hashing the unit id) can be run in one pass with 100 to 200 replicates.
  • Per-user summaries: compare the mean of each user's p95, or the share of requests slower than 1 second (a proportion, which is easy).
  • Sketches: store a mergeable quantile sketch (t-digest, KLL) per variant and segment, plus bootstrap replicates as separate sketches. See Probabilistic Data Structures for Big Data.

Uber's description lists bootstrap and Mann-Whitney (a rank test, which compares distributions rather than means) among its methods, alongside Welch's t-test as the default.

Heavy tails and capping. Revenue per user is extremely skewed: most users spend nothing, a few spend thousands. That causes two problems. The variance is huge, so power is low. And the normal approximation behind the t-test needs a larger sample than usual. Kohavi's 2014 paper gives a rule of thumb: the sample needed for the normal approximation to be reasonable is about 355 × s², where s is the metric's skewness. The paper's Bing revenue-per-user metric had a skewness of 18.2, so it needed about 114,000 users. Capping it at $10 per user per week (setting larger values to $10, also called winsorising) dropped the skewness from about 18 to 5.3. With the same sample, the capped metric could detect a change 30% smaller. By the same rule, 355 × 5.3² is only about 10,000 users. Capping changes the metric slightly, because it now measures capped revenue, but it makes the metric far more sensitive. Capping at the 99.9th percentile of control is a common default.

Choosing the OEC. Statistics cannot rescue the wrong metric. Kohavi's 2012 paper on puzzling outcomes tells the story of a Bing experiment where a bug in the treatment degraded search results. Queries per user rose by more than 10% and revenue per user by more than 30%, because users had to search more and clicked more ads. By those metrics the bug was a huge win. The lesson was that the OEC must reflect long-term user value: Bing's OEC moved towards sessions per user (users who find what they need come back more often, rather than searching more within a session). A good OEC is sensitive enough to move in a two-week experiment, and predictive of long-term outcomes.

8. Power, sample size, MDE and CUPED#

Power in one formula. For a two-sided test at α = 0.05 with 80% power, the number of units needed per variant to detect an absolute effect δ on a metric with standard deviation σ is approximately

n ≈ 2 × (z_0.975 + z_0.80)² × σ² ÷ δ² = 2 × (1.96 + 0.84)² × σ² ÷ δ² ≈ 16 σ² ÷ δ²

The factor 16 is a well-known rule of thumb. The Tang 2010 paper quotes it from Kohavi's earlier work as 16 (s ÷ θ)², where s is the standard deviation and θ the effect to detect, at 95% confidence and 80% power. The same paper notes that when the control is much larger than the treatment (a shared control), and with 90% power, the treatment needs only about 10.5 (s ÷ θ)², because the control's variance becomes negligible and (1.96 + 1.28)² ≈ 10.5.

Worked examples.

MetricBaselineσMDE (relative)δn per variant
Conversion rate5%√(0.05 × 0.95) ≈ 0.2182%0.00116 × 0.0475 ÷ 10⁻⁶ ≈ 760,000
Conversion rate5%0.2185%0.0025≈ 122,000
Revenue per user, raw$3.00$301%$0.0316 × 900 ÷ 0.0009 = 16 million
Revenue per user, capped$2.90$121%$0.029≈ 2.7 million
Capped revenue with CUPED (ρ = 0.7)$2.9012 × √0.51 ≈ $8.61%$0.029≈ 1.4 million

Two things jump out. Halving the MDE quadruples the sample. And heavy-tailed metrics need tens of millions of users unless they are capped and variance-reduced. If the checkout page sees 1 million users a day and the experiment covers 50% of them in two variants, each variant gains about 250,000 new users a day, so 760,000 takes about 3 days and 2.7 million about 11 days (in practice longer, because returning users are not new units).

The power calculator. The platform's GET /v1/power uses historical per-unit data for the metric and the audience to estimate σ, the expected number of units per day (with returning users counted once), and the resulting MDE for each possible duration. Showing "with 14 days at 20% coverage you can detect a lift of 1.8% or more" before the start prevents the most common failure in self-service experimentation: an underpowered test whose "no significant result" is misread as "no effect".

MDE and decision rules. A common rule: run at least one or two full weeks (to cover weekly cycles), and until the planned sample is reached. An experiment that is not significant at its planned size has not proven there is no effect; it has shown the effect is probably smaller than the MDE. The confidence interval says how much smaller.

CUPED: using the past to reduce noise. Much of the variance in a metric comes from differences between users that existed before the experiment: heavy users buy more in both variants. If we know each user's behaviour before the experiment, we can subtract the predictable part.

CUPED (Controlled-experiment Using Pre-Experiment Data), from Alex Deng, Ya Xu, Ron Kohavi and Toby Walker at WSDM 2013, does this with a simple adjustment. Let Y be the metric during the experiment and X the same metric (or another correlated one) for the same unit in a pre-period. Define

Y_cv = Y − θ (X − E[X]), with θ = cov(X, Y) ÷ var(X)

Because X was measured before the experiment, it is independent of the assignment, so E[X] is the same in both variants and the adjusted difference has the same expected value as the raw difference: the estimate is still unbiased. Its variance is

var(Y_cv) = var(Y) (1 − ρ²)

where ρ is the correlation between X and Y. With ρ = 0.7, variance falls by 49%, which halves the sample needed. The paper reports variance reductions of about 50% for some Bing metrics, and an example where a 250 millisecond slowdown experiment was detectable from the first day with CUPED.

Intuition through the analogy: compare plots by how much their yield changed relative to what each plot usually produces, not by raw yield. A naturally fertile plot no longer looks like a fertiliser win.

The practical rules, all from the paper's guidance:

  • Same θ for both variants, computed on the pooled data. Different θ per variant could introduce bias.
  • The covariate must not be affected by the treatment. Pre-experiment data is safe by construction. A covariate measured during the experiment is safe only if the treatment cannot change it (for example, the day of the week of first exposure), and dangerous otherwise.
  • The pre-period: one to two weeks is usually enough; longer periods add little correlation and lose new users.
  • Units without pre-period data (new users) get X = 0 plus an indicator, or a separate adjustment; they simply get less variance reduction.

CUPED from sufficient statistics. Everything needed is in the stats table: cov(X, Y) = (Σxy − n x̄ ȳ) ÷ (n − 1), var(X) from Σx and Σx², so θ is computed per experiment and metric without touching per-unit data. The adjusted means are ȳ_cv = ȳ − θ (x̄ − x̄_pooled), and the adjusted variance is var(Y) + θ² var(X) − 2θ cov(X, Y). This is why the data model stores sum_x, sum_y and sum_xy: CUPED becomes essentially free.

Beyond CUPED. Regression on several pre-period covariates generalises CUPED (it is linear regression adjustment); machine-learned predictions of each unit's metric can be used as X (often called CUPAC), with the same rule that the predictor must use only pre-experiment data. Stratification and post-stratification by segment are related ideas. Uber lists CUPED among its variance-reduction methods, alongside difference-in-differences for cases where pre-period trends matter.

9. Peeking and sequential testing#

The peeking problem. A fixed-horizon test (decide the sample size, collect it, test once) has a 5% false positive rate at α = 0.05. But a platform shows results every day, and people act on them. If Sam checks the p-value every day and stops the first time it drops below 0.05, the false positive rate is much higher than 5%, because under no effect the p-value wanders randomly, and over many looks it is likely to dip below 0.05 at least once. Ramesh Johari, Leo Pekelis and David Walsh, in "Always Valid Inference: Continuous Monitoring of A/B Tests" (arXiv 1512.04922; the method forms the core of the statistics behind the Optimizely platform), state that even with 10,000 samples, a size common in online tests, continuous monitoring can easily increase the Type I error fivefold.

The intuition, with the farm: if you weigh the plots every morning and announce a winner the first morning the scale looks favourable, you will eventually see a favourable morning by luck alone.

Telling users "do not peek" does not work on a self-service platform. The statistics must be valid under peeking. There are two families of solutions.

Group sequential tests (planned looks). From clinical trials: decide in advance to look K times (say, every week for 4 weeks), and spend the 5% Type I error across the looks. Wikipedia's sequential analysis page describes the classic designs:

  • Pocock uses the same threshold at every look, stricter than 1.96 (for 5 looks, about 2.41).
  • O'Brien-Fleming uses very strict thresholds early and close to 1.96 at the end, so the final analysis loses little power.
  • Alpha spending functions (Lan and DeMets) let the looks be unplanned in number and timing: a function says how much of α may have been spent by each fraction of the planned information.

Group sequential tests are efficient and well understood, but they need a planned maximum sample size and do not allow arbitrary continuous looks.

SPRT. Abraham Wald's sequential probability ratio test (1945) compares two simple hypotheses after every observation, using the log-likelihood ratio Λ = log of [likelihood under H1 ÷ likelihood under H0]. It stops for H1 when Λ ≥ b ≈ log((1 − β) ÷ α), stops for H0 when Λ ≤ a ≈ log(β ÷ (1 − α)), and continues otherwise. It is optimal for two point hypotheses, but A/B tests do not have a single alternative effect; the effect could be any size.

mSPRT and always-valid p-values. The mixture SPRT averages the likelihood ratio over a distribution H of possible effects:

Λ_n = ∫ [f_θ(data) ÷ f_θ₀(data)] dH(θ)

Under the null, Λ_n is a nonnegative martingale with mean 1, so by Ville's inequality the probability that it ever exceeds 1/α is at most α. That is the key property: reject the null the first time Λ_n ≥ 1/α, and the false positive rate stays at α no matter how often or when you look. Johari and colleagues define the always-valid p-value

p_n = min(p_(n−1), 1 ÷ Λ_n), with p_0 = 1

which never increases, can be checked at any time, and gives a valid test at any stopping time. The matching confidence sequence (intervals that cover the true effect at all times simultaneously with 95% probability) is the set of effects not rejected.

For approximately normal data with a normal mixing distribution N(θ₀, τ²), Λ has a closed form. Writing Δ for the observed difference and V = s_T² ÷ n_T + s_C² ÷ n_C for its variance:

Λ = √(V ÷ (V + τ²)) × exp( τ² Δ² ÷ (2 V (V + τ²)) )

So the decision depends on the usual z = Δ ÷ √V and on the ratio r = τ² ÷ V, which grows as data accumulate. A worked example at α = 0.05 (threshold 1/α = 20):

r = τ² ÷ VΛ as a function of zz needed to reject
10 (early)0.302 × exp(0.455 z²)about 3.04
100 (later)0.0995 × exp(0.495 z²)about 3.27
1,000 (much later)0.0316 × exp(0.4995 z²)about 3.61

Compared with 1.96 for one fixed look, the always-valid test needs a larger z at any given moment. That is the price of being allowed to look continuously. The benefit: a large real effect is detected early, and the test can stop as soon as the evidence is strong.

Choosing the mixing variance. τ² is a tuning parameter. Johari and colleagues show that it should match the typical size of real effects (the prior variance of effects seen on the platform), and that misjudging it by around an order of magnitude costs little; they report under about a 5% drop in performance. A platform can estimate it from past experiments, per metric.

Does it cost sample size? For effects of the size the test is tuned for, the mSPRT's expected sample size can be smaller than a fixed-horizon test's planned size, because large effects stop early. The paper's empirical study on 10,000 binary experiments from a commercial platform found that the ratio of the mSPRT's run length to the fixed-horizon sample size was below 1 with high probability. For tiny effects it can take longer. The paper says these two-stream always-valid p-values and intervals have run in a large commercial platform since January 2015.

What large platforms do. Uber's XP uses fixed-horizon tests for standard analyses and sequential tests (SPRT and mSPRT) for continuous monitoring of outage-type metrics, with variance estimated by jackknife or block bootstrap to account for correlated data within units. Spotify's post says that if you want to look at results before the end, you need sequential testing, and its platform offers it. The general pattern:

  • Primary decision metric: fixed horizon with a planned duration, or a group sequential design with planned weekly looks. Most power for the decision.
  • Guardrails and rollouts: always-valid tests, checked every few minutes. Validity under constant watching matters more than maximum power.
  • Display: always-valid intervals by default on the live scorecard, with a clear label, so that the number people react to is the safe one.

Effects found early are exaggerated. If an experiment stops as soon as the result crosses a threshold, the reported effect at that moment is biased upwards: it crossed partly because of a lucky fluctuation. Wikipedia's sequential analysis page notes this overestimation. Kohavi's 2012 paper adds a related observation from Bing: early "trends" that seem to grow or shrink over the first days are usually regression to the mean. In their example, on day 1 the estimate had about a 67% chance of being outside the interval that would hold at the end. Practical rule: when a test stops early, report the effect with a shrinkage correction or confirm it with a follow-up run, and do not extrapolate day-1 curves.

10. Multiple comparisons and false discoveries#

The problem. A scorecard with 300 metrics, 30 segments and two treatment variants contains 18,000 comparisons. At α = 0.05, with no real effects at all, about 900 would be "significant" by chance. Someone will find the segment "iOS users in Brazil on app version 8.2" where the treatment raised revenue by 9% (p = 0.003) and write a launch memo.

Bonferroni controls the family-wise error rate (the chance of even one false positive) by testing each of m hypotheses at α ÷ m. With m = 300 metrics, that is 0.00017, z ≈ 3.76. It is simple and safe but very conservative: real effects are missed.

Benjamini-Hochberg controls the false discovery rate (FDR), the expected fraction of declared discoveries that are false. Sort the m p-values p₍₁₎ ≤ p₍₂₎ ≤ … ≤ p₍ₘ₎. Find the largest k with p₍ₖ₎ ≤ (k ÷ m) × q, where q is the target FDR (say 0.05), and declare the first k discoveries. Example with m = 10 metrics and q = 0.05: thresholds are 0.005, 0.010, 0.015, …, 0.05. If the sorted p-values are 0.001, 0.004, 0.012, 0.03, 0.2, …, then p₍₃₎ = 0.012 ≤ 0.015, p₍₄₎ = 0.03 > 0.02, so the first three are declared. Uber lists BH among its corrections. Johari and colleagues show that BH works with always-valid p-values, so the two ideas combine: the live scorecard can control FDR across metrics while remaining valid under peeking.

The platform's policy.

  • Pre-register a small set of decision metrics: one primary (the OEC) and a few secondaries. These are tested at α (or with BH among themselves).
  • Guardrails are tested for harm with their own error budget (deep dive 11).
  • All other metrics and segments are exploratory: shown with BH-adjusted significance, collapsed by default, and labelled "for hypothesis generation".
  • Surprising segment effects require confirmation: a follow-up experiment targeted at the segment.

False positive risk: why most "wins" may be false. A p-value is not the probability that the result is false. The false positive risk (FPR) is the probability that a significant result is a false positive, which depends on how often ideas truly work. Kohavi's 2014 paper works the numbers with 80% power and α = 0.05:

  • If one third of ideas truly work (π = 1/3): true positives = 0.8 × 1/3 ≈ 0.267, false positives = 0.05 × 2/3 ≈ 0.033, so P(true | significant) ≈ 0.267 ÷ 0.300 ≈ 89%.
  • If only 1 in 500 ideas is a breakthrough of the claimed size (π = 1/500): true positives = 0.0016, false positives ≈ 0.0499, so P(true | significant) ≈ 3.1%.

The same paper uses Bing examples to make the point that big wins are rare: a 2013 set of experiments on font colours, a trivial CSS change, improved monetisation by over $10 million a year, and was replicated on 32 million users before anyone believed it. The authors estimate that perhaps one in 500 Bing experiments has that kind of high, replicable payoff. So when a result is surprisingly large, the prior says it is probably wrong.

Twyman's law. "Any figure that looks interesting or different is usually wrong." Kohavi's papers apply it to experiments: a result far outside what similar changes produce is far more likely to be a bug, a logging change or an SRM than a discovery. The 2014 paper gives the numbers: if past effects on sessions per user are roughly normal around 0 with a standard deviation of 0.25%, then a +2.0% result is eight standard deviations out, with a prior probability around 10⁻¹⁵. Check for bugs before you celebrate. The platform can apply this automatically: flag effects that are more than a few times larger than the 99th percentile of past effects on the same metric, and require a data-quality review before the result is shown as a win.

11. Guardrails and automated safety#

Superiority versus non-inferiority. The primary metric is tested for superiority: H0 says the effect is zero, H1 that it is positive, and the test needs an MDE. A guardrail asks a different question: "is it not worse by more than a tolerated margin m?" That is a non-inferiority test: H0 says the effect is at most −m (a meaningful harm), H1 that it is better than −m. Spotify's post describes this split explicitly: success metrics are tested with superiority tests and an MDE; guardrail metrics with non-inferiority tests and a non-inferiority margin.

Why it matters: with a superiority test, "no significant harm" in an underpowered experiment says nothing; the harm could be large and undetected. With a non-inferiority test, the treatment must actively show that any harm is smaller than the margin. A guardrail that cannot reach that conclusion is "inconclusive", which blocks a ship decision, not "passed".

Two speeds of guardrails.

SpeedMetricsMethodAction
MinutesCrash rate, error rate, p95 latency, payment failures, "time since last order" per variantStreaming stats, mSPRT for harm, every 5 minutesAuto-stop or page owner
DailyRevenue, retention, unsubscribes, support ticketsBatch stats, non-inferiority with marginBlock ship decision, alert

The streaming guardrail job. A Flink job (Apache Flink and Stream Processing) consumes the exposure and event streams, both partitioned by unit id:

  1. Keyed state of exposures: for each unit, the experiments and variants it has been exposed to (72 GB across the cluster in our estimate), with a time to live.
  2. Enrich each guardrail event (crash, error, latency sample, order) with the unit's variants.
  3. Aggregate per (experiment, variant, metric) in 5-minute event-time windows, with a watermark of a few minutes for late events. Emit n, Σx and Σx² per window.
  4. The guardrail monitor accumulates the windows since the phase start and runs the mSPRT for harm, plus BH across the guardrails of each experiment.

Per-unit independence matters here too: crash events cluster in users (one user crashes repeatedly). Treating events as independent underestimates the variance. Aggregating to per-unit counts within the window, or using a jackknife or block bootstrap variance as Uber describes, fixes this.

Detecting silence. Some failures do not change a rate; they stop the events. If the treatment breaks the "place order" button, the treatment simply produces no orders. A ratio-based test can be slow to react, especially at low traffic, because "no events" also means less data. A complementary check is time since the last event per variant: if control has produced an order every 2 seconds and treatment has not produced one for 60 seconds at a similar exposure rate, something is broken. The expected gap follows from the event rate (with Poisson arrivals at rate λ, a gap longer than t has probability exp(−λt)), so the alert threshold can be set for a chosen false alarm rate. This check catches total breakages in a minute or two, much faster than any rate comparison.

Why latency is a guardrail for everything. Kohavi's 2014 paper reports a Bing experiment that deliberately slowed some users' pages by 100 or 250 milliseconds for two weeks. It concluded that every 100 milliseconds of speedup improves revenue by 0.6%. Many experiments add a little latency (a new model, an extra call), so p95 and p99 latency are default guardrails on every experiment that touches a page.

The auto-stop policy.

  • Only stop, never ship. The automatic action is always "coverage 0, everyone gets control".
  • Severity levels per guardrail: alert, pause ramping, or auto-stop. Payment failures and crash rate auto-stop by default.
  • Confirmation: two consecutive windows, or one window with overwhelming evidence (for example Λ above 1,000 ÷ α).
  • Minimum sample: no decisions on fewer than a few hundred exposed units per variant, because the normal approximation fails.
  • Audit and notify: the stop creates a phase with the reason and the evidence, pages the owner, and posts to the team's channel.
  • Platform-wide circuit breaker: if guardrail data is missing (the stream job is down), new ramps above 10% are blocked until it recovers; running experiments continue.

Long-term holdouts as a guardrail. Each experiment is checked over 2 to 4 weeks, but the product changes all year. A quarterly holdout per area (Spotify's pattern, deep dive 3) measures whether the combined launches of the quarter actually improved long-term metrics. If the holdout shows smaller gains than the sum of individual wins, which is common, it is a sign of novelty effects, interactions or false positives.

12. Trust pitfalls: SRM, A/A tests, carryover, novelty, interference and Simpson's paradox#

Sample ratio mismatch. If an experiment is configured 50/50, the observed numbers of units should be close to 50/50, within chance. The test is a chi-square goodness-of-fit test. A real example from Fabijan and colleagues (KDD 2019): 821,588 users in one variant and 815,482 in the other, a 50.2/49.8 split. Expected under 50/50 is 818,535 each; χ² = 2 × 3,053² ÷ 818,535 ≈ 22.8, so p ≈ 2 × 10⁻⁶, less than 1 in 500,000. A split that looks almost perfect is, at this size, almost certainly broken.

The paper reports that about 6% of experiments at Microsoft had an SRM, and that an SRM usually means the results are untrustworthy: some kind of user was lost or added in one variant, so the groups are no longer comparable. The platform runs the SRM test on every experiment, every day, and hides the results of experiments with p < 0.0005 behind a warning until someone investigates.

The paper's taxonomy of causes, each with a real example:

SRM typeWhat goes wrongExample from the paper
AssignmentThe randomisation itself is wrongA bug gave control one bucket too few, so a 50/50 test ran as 49.9/50
ExecutionThe variant changes who gets loggedSkype: a configuration refresh mid-session changed behaviour so treatment logged about 30% fewer sessions
Log processingThe pipeline drops or adds units unevenlyMSN: a carousel change from 12 to 16 cards made the most engaged treatment users cross the bot threshold; once fixed, the result flipped and the feature shipped
AnalysisThe trigger condition depends on the treatmentTeams: a trigger condition that the new design affected; the fix used an event a few steps earlier
InterferenceSomething outside the experiment changes one groupUsers from a search engine campaign placed into one variant; debugging overrides used wrongly

The paper lists 25 specific causes and ten rules of thumb for diagnosis. Some that translate directly into platform features:

  • Look at segments and time: an SRM only in one browser or starting on one day points at a release or a logging change.
  • Check performance and engagement: a slower treatment loses fast-leaving users before the exposure fires.
  • Check frequency: an SRM in the count of events but not users points at logging; in users, at assignment or triggering.
  • Fix bot status at the first exposure. Booking.com determines whether a unit is a bot once, at its first exposure, so the treatment cannot change a unit's bot status later. That prevents the MSN-style flip.
  • Add a first telemetry signal that fires before any other product code runs, so the user's presence is recorded before the treatment can influence whether a log is sent. The paper recommends this, together with other data-quality metrics.

The three assignment requirements from deep dive 2 (equal probability, consistency, independence) are the first places to look.

A/A tests. An A/A test splits users into two groups that get the same experience. It should show a significant difference in about 5% of metrics, and p-values should be uniformly distributed between 0 and 1. Running many A/A tests (or simulating them by re-randomising historical data) checks the whole system: hashing, logging, the pipeline and the statistics. A platform should run a permanent A/A test in every layer, and run "virtual" A/A tests on historical data whenever a metric definition or variance method changes. Kohavi's 2012 paper uses A/A tests on reused buckets to detect carryover, and treats a failed A/A as a reason to re-randomise.

Carryover. As deep dive 3 explained, users who were in an earlier treatment can stay affected for weeks or months, which can bias experiments that reuse their buckets. Fresh salts per experiment and retrospective A/A checks on pre-period data are the defences.

Novelty and primacy effects. The Wikipedia page on the novelty effect describes the tendency of performance to improve when something new is introduced, simply because it is new. Users click a redesigned button because it is unfamiliar; the effect fades. The opposite, the primacy effect, is when experienced users resist change at first and the treatment looks worse than it will be once they adapt. Both show up as a treatment effect that trends over time for the same users. Diagnosis: plot the effect by days since first exposure (not calendar days), and compare new users (who have no habits) with existing users. Remedy: run longer, or decide on the later days' effect, or use a holdout to measure the long-term effect.

Interference and network effects. Standard analysis assumes a unit's outcome depends only on its own variant (the "stable unit treatment value assumption"). That fails when units interact:

  • Marketplaces: a treatment that makes riders book faster takes drivers from control riders, so treatment looks better and control looks worse than either would be at 100%. The A/B difference overstates the real effect.
  • Social products: a new sharing feature in treatment sends messages to control users, so control is partly treated.
  • Shared resources: two variants compete for the same ad budget or inventory.

Designs that handle interference randomise at a coarser unit:

  • Cluster randomisation: randomise whole groups that rarely interact with each other (cities, social-graph clusters). Fewer units, so less power, and the analysis must use cluster-level variance.
  • Switchback experiments: in a marketplace, randomise time slots within a region (this hour treatment, the next control), so that the whole market is in one variant at a time. Analysis must handle carryover between adjacent slots, usually by discarding a buffer at each switch.
  • Two-sided randomisation and budget splitting for ad systems: split each advertiser's budget so each variant has its own supply.

The platform supports these by making the randomisation unit a configurable attribute (city_id, region_hour) and by computing variance at the randomisation unit.

Simpson's paradox with ramps. Pooling data across phases with different weights can reverse the result. Example: on weekdays, treatment gets 10% of traffic; on the weekend, it is ramped to 50%. Weekend users convert at a lower rate. Suppose the treatment truly helps by the same relative amount each day:

PeriodControl usersControl conv.Treatment usersTreatment conv.
Weekdays (10%)900,0006.0%100,0006.3%
Weekend (50%)250,0003.0%250,0003.15%
Pooled1,150,0005.35%350,0004.05%

Treatment wins in both periods by 5%, but the pooled numbers say it loses by about 24%, because most of treatment's users came from the low-converting weekend. Wikipedia's Simpson's paradox page describes the general phenomenon. The platform avoids it by analysing each phase separately, or combining phases with weights per phase (a stratified estimate), never by naively pooling across weight changes. This is the main reason phases are immutable.

Lost telemetry. Kohavi's 2012 paper discusses click tracking with web beacons (tiny image requests sent when the user clicks). Waiting for the beacon slows the next page: until March 2010, several Microsoft sites waited up to 2 seconds, adding about 400 milliseconds on average to clicks. Not waiting loses clicks. So any treatment that changes page speed or navigation also changes how many beacons are lost, and click metrics can move because of telemetry rather than behaviour. The SRM paper makes the related point that a treatment which makes users more engaged (more events per user) is less likely to lose all of a user's events, so it can "recover" users in the logs. Defences: measure telemetry loss per variant (for example, compare client clicks with server-side logs of the same actions) and prefer server-side events for key metrics.

Bots. Bots are a large share of traffic on some surfaces, and they do not behave like users: huge activity, no purchases. If the treatment changes how many bots get through, or how bots are detected, the comparison breaks. Fix bot classification at first exposure, filter consistently, and monitor the bot share per variant like an SRM.

When a scorecard shows an SRM, the on-call analyst follows a short triage path. The platform can run most of it automatically:

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Config service or CDN outageSDKs cannot fetch new rules; experiments cannot start or stopSDKs keep the last snapshot in memory and on disk; compiled-in defaults; multi-region object storage; kill switches also pushed through a second channel
Bad config pushed (wrong weights, broken targeting)Millions of users get a broken or unintended experienceValidation before publish; staged rollout of the ruleset to a canary fleet; one-click revert to the previous version; per-version exposure counts
SDK inconsistency across languagesSame user gets different variants on web and server; SRMOne written spec with shared test vectors (unit id, salt, expected bucket) that every SDK runs in CI
Salt reuse or poor hashCorrelated assignments between experiments; biased splitsPlatform-generated random salts; hash version stored per phase; daily independence check between overlapping experiments
Exposure logging overloadEvent pipeline saturates; exposure lossIn-process dedup; batching; bounded queues with drop counters; first-exposure compaction downstream
Uneven exposure loss between variantsSRM and biased resultsPer-variant drop counters; first telemetry signal; SRM test on every experiment daily
Ingestion spike (7M events/s peak, bursts above)Kafka lag; late scorecards; guardrail blind spotsPartition headroom; autoscaling collectors; backpressure to SDK batches; guardrail job alerts on its own lag
Late and out-of-order eventsProvisional numbers move; treatment-specific delay biases early readsEvent-time processing; completeness thresholds; D+1 recompute; completeness shown on scorecards
Daily batch overrunsScorecards miss the morning; decisions delayedOne scan for all experiments; incremental per-unit aggregates; priority for primary metrics; spare compute quota
Segment cardinality explosionStats table blows up; thousands of spurious segment winsFixed bounded segment dimensions; on-demand breakdowns with FDR labels
Peeking and many metricsFalse wins shippedAlways-valid intervals on live views; pre-registered primary metric; BH on secondary metrics; Twyman flag on outsized effects
Guardrail job down or laggingHarmful experiments run unwatchedCircuit breaker blocks ramps above 10%; job lag is itself an alert; daily batch guardrails as a backstop

What Interviewers Expect#

Mid-level. Explain what an A/B test is and why randomisation gives causal answers. Propose hashing the user id with a per-experiment salt into buckets, and explain why that is deterministic and needs no database. Separate the config service from the SDKs, with SDKs caching config locally. Log exposures to Kafka and compute metrics in a daily batch job. Know the t-test, p-value and confidence interval, and that sample size grows with variance and shrinks with the square of the effect.

Senior. Size the system and conclude from the numbers that assignment must be local. Design layers for mutual exclusion and explain why overlap is safe for independent experiments. Explain exposure versus assignment, triggered analysis and counterfactual logging. Design the metrics pipeline with a metric catalog, first-exposure joins and sufficient statistics. Handle ratio metrics with the delta method, heavy tails with capping, and variance with CUPED. Explain SRM and why it invalidates results. Add streaming guardrails and auto-stop through the same config path. Integrate feature flags, rollouts and kill switches.

Staff and above. Treat trustworthiness as the product. Explain why peeking breaks fixed-horizon tests and offer mSPRT or alpha spending, with the trade-off in power. Explain false positive risk, FDR across metrics and segments, and Twyman's law, with numbers. Know the SRM taxonomy and how the platform detects each type. Discuss carryover and re-salting, novelty and primacy effects, interference in marketplaces and social products (cluster and switchback designs), Simpson's paradox across ramps, and long-term holdouts. Choose the OEC carefully, with the Bing example. Talk about organisational design: self-service with guardrails, a certified metric catalog, experiment review, a searchable record of past decisions, and flag-debt policy.

Deep Dive: sizing the platform tier by tierShow

SDK tier. About 11.6 million evaluations a second on average and 35 million at peak, spread over 100,000 service instances: about 116 a second per instance on average, a few hundred at peak. At 2 microseconds each, that is a fraction of 1% of one core per instance. Memory: a scoped ruleset of 100 KB to 2 MB, plus an exposure dedup cache of perhaps 100,000 entries at about 50 bytes each, 5 MB. The SDK is negligible in cost; its correctness is what matters.

Delivery tier. 3,300 server polls a second, almost all 304 Not Modified from a CDN, plus 14,000 client evaluations a second on average and 40,000 at peak. The remote evaluation service runs the same SDK: at a few hundred microseconds of CPU per request (20 flags plus JSON serialisation), 40,000 requests a second needs about 20 to 40 cores, so a fleet of 10 to 20 instances with headroom across regions. The streaming notifier holds 100,000 long-lived connections; at about 10,000 to 50,000 connections per instance, that is 5 to 10 instances.

Control plane. About 5,000 users of the platform, a few hundred writes an hour. PostgreSQL with a primary and replicas is ample. The Config Compiler rebuilds a scoped snapshot in about a second; at hundreds of changes an hour, it is idle most of the time.

Collectors and Kafka. About 2.6 million messages a second on average (events plus exposures) and roughly 8 million at peak, at about 1.4 to 1.6 GB/s peak. With replication factor 3, the brokers write about 4.5 GB/s at peak. At about 100 to 200 MB/s of sustained write per broker, that is 30 to 50 brokers, with partitions sized so that each consumer handles about 10 to 20 MB/s: about 1,000 to 2,000 partitions across the two topics. Three days of retention at about 45 TB a day raw (compressed perhaps 3 to 5 times) is about 30 to 45 TB per replica.

Data lake. Compressed events at 5 to 8 TB a day, exposures at 0.5 TB a day, per-unit metrics at about 120 GB a day. A year of events is 2 to 3 PB. Exposures and per-unit metrics are kept longer (for holdouts and meta-analysis); raw events follow the company's retention policy.

Batch compute. 500 to 1,000 core-hours a day for the experiment metrics, which is about 50 machines of 32 cores for 30 to 60 minutes, or the equivalent warehouse slots. The recompute of D−1 doubles it. Ad hoc deep dives (segment breakdowns, bootstrap quantiles) add perhaps as much again.

Stream tier. The guardrail job reads about 2.6 million messages a second on average, with 72 GB of keyed state. At about 50,000 to 100,000 events a second per Flink task slot for simple enrichment and window aggregation, that is about 30 to 60 slots at average load and two to three times that for peaks: a cluster of 20 to 40 machines, with state in RocksDB and checkpoints to object storage.

Statistics tier. 54 million sufficient-statistics rows a day, about 3.5 GB. Computing every scorecard is a few million small computations, minutes on a handful of machines. Interactive scorecards read a few thousand rows each and return in well under a second.

Deep Dive: the maths in one placeShow

Hash uniformity. With 10,000 buckets and n units, each bucket gets about n ÷ 10,000 units with standard deviation √(n ÷ 10,000). For a 50/50 split of n units, the treatment count has standard deviation √n ÷ 2. For n = 1 million, that is 500, or 0.05%. Seeing 50.2% (2,000 above expectation, four standard deviations) is already suspicious; the SRM test formalises this.

SRM chi-square. For k variants with observed counts O_i and expected E_i = n × w_i, χ² = Σ (O_i − E_i)² ÷ E_i, with k − 1 degrees of freedom. The platform uses a strict threshold (p < 0.0005) because it runs thousands of SRM tests a day and should not cry wolf.

Welch's t. t = (x̄_T − x̄_C) ÷ √(s_T² ÷ n_T + s_C² ÷ n_C). Interval: Δ ± 1.96 × SE. Relative interval: divide by x̄_C, with the delta method for the ratio when precision matters.

Delta method for ratios. For R = μ_Y ÷ μ_X estimated from n units: Var(R̂) ≈ (σ_Y² − 2R σ_XY + R² σ_X²) ÷ (n μ_X²).

Sample size. n per variant ≈ 2 (z_(1−α/2) + z_(1−β))² σ² ÷ δ², which is 16 σ² ÷ δ² at α = 0.05 and 80% power, and about 21 σ² ÷ δ² at 90% power.

CUPED. θ = cov(X, Y) ÷ var(X); Y_cv = Y − θ (X − x̄); Var(Y_cv) = Var(Y)(1 − ρ²). The sample needed falls by the same factor (1 − ρ²).

Normal-approximation sample floor. About 355 × skewness² units per variant before the sample mean is close enough to normal (Kohavi's rule of thumb, for |skewness| above 1).

False positive risk. P(true effect | significant) = (power × π) ÷ (power × π + α × (1 − π)), where π is the fraction of tested ideas that truly work.

Benjamini-Hochberg. Declare the k smallest p-values, where k is the largest index with p₍ₖ₎ ≤ k q ÷ m.

Wald's SPRT. Continue while a < log-likelihood ratio < b, with a ≈ log(β ÷ (1 − α)) and b ≈ log((1 − β) ÷ α). At α = 0.05 and β = 0.2: a ≈ −1.56, b ≈ 2.77.

mSPRT with a normal mixture. Λ = √(V ÷ (V + τ²)) × exp(τ² Δ² ÷ (2V(V + τ²))); reject when Λ ≥ 1/α; always-valid p_n = min(p_(n−1), 1 ÷ Λ_n).

Silence detection. With Poisson arrivals at rate λ, P(gap > t) = exp(−λt). If control produces orders at λ = 0.5 a second, a 60-second gap has probability exp(−30) ≈ 10⁻¹³: certain breakage.

Simpson's paradox. A pooled rate is a weighted average of segment rates, weighted by each variant's own mix of segments. When the mix differs between variants (because weights changed over time), the pooled comparison can reverse the segment comparisons.

Deep Dive: one request and one experiment, end to end with real numbersShow

09:00, Monday. Asha starts checkout_button_v2 in the checkout layer: 10% coverage, 50/50, target web in three countries. The Experiment Service validates it in about 200 ms (the power check reads historical variance: with 250,000 eligible users a day at 10% coverage, 14 days gives an MDE of about 2.2% on purchases per user). The allocation transaction takes layer buckets 0 to 999. The Config Compiler builds ruleset v18452 in 0.8 seconds and publishes it; the notifier tells 100,000 server SDKs. Within 10 seconds 99% of them run v18452; the rest pick it up on their next 30-second poll.

09:02. Kai, user u-42, opens checkout. Inside the checkout service, getValue("checkout.button_style", user):

  • Targeting: web, country DE: matches.
  • Layer hash: murmur3("layer-checkout-7f3a:u-42") mod 10,000 = 312, inside 0 to 999: in the experiment.
  • Variant hash: murmur3("exp-cbv2-p1-91c2:u-42") mod 10,000 = 7,731, inside the treatment range 5,000 to 9,999: treatment, value "green".
  • Total time: about 3 microseconds. Exposure queued, the dedup cache records (u-42, cbv2, treatment).

The page renders 4 ms later. Two seconds later the SDK sends a batch of 500 exposures (about 60 KB) to the collector, which produces them to the exposures topic. Kafka acknowledges after replication in about 10 ms.

09:07. The Flink guardrail job's first 5-minute window closes (after a 2-minute watermark). For cbv2: 1,900 exposed in control, 1,880 in treatment; error rate, p95 latency and payment failures are flat. The mSPRT likelihood ratios are near 1. Nothing happens.

Tuesday 07:30. Data for Monday is 96% complete. The daily job computes per-unit metrics for 300 million users, joins them with first exposures for 2,000 experiments, and writes 54 million statistics rows by 08:40. For cbv2: control 12,480 users, treatment 12,510; SRM p = 0.85 (fine). Purchases per user 0.201 versus 0.205, z = 0.8. The live scorecard shows the always-valid interval: [−4.1%, +8.0%], too wide for any decision. That is expected on day 1.

Day 14. 175,000 users per variant. CUPED with ρ = 0.6 cuts variance by 36%. The lift is +2.4%, with a fixed-horizon 95% interval of [+0.9%, +3.9%] and p = 0.002. Guardrails pass their non-inferiority tests: p95 latency +1 ms (margin 20 ms), revenue per user +1.8% (margin −0.5%). No segment surprise after BH. Asha's team decides "ship": a 100% rollout rule replaces the experiment rule, and the platform opens a ticket to delete the flag in 30 days.

Costs for this experiment. About 4 million exposure events over two weeks, about 500 MB raw. Its share of the daily batch is roughly 1/2,000 of the job, about 30 core-minutes a day. The scorecard reads about 3,000 statistics rows.

Deep Dive: running this in a 45-minute interviewShow
MinutesWhat to doWhat to say or draw
0 to 5ClarifyWho runs experiments, how many at once, traffic scale, surfaces, freshness, peeking, flags in scope
5 to 10EstimateEvaluations per second (11.6M), so assignment must be local; events per second (2.3M to 7M), so the data pipeline is the heavy part
10 to 20High-level designControl plane, config compiler and CDN, in-process SDK with hashing, exposure logging to Kafka, lake, daily metrics, stats engine, streaming guardrails
20 to 25Assignmenthash(salt, unit) mod 10,000; ranges; ramps that only extend ranges; layers for exclusivity; per-experiment salts
25 to 32Metrics and statisticsFirst-exposure join, sufficient statistics, Welch t, delta method, CUPED; draw the scorecard with SRM at the top
32 to 38TrustPeeking and mSPRT, multiple metrics and BH, SRM taxonomy, carryover, novelty, interference
38 to 43Safety and flagsGuardrails with auto-stop through the config path; rules engine order; kill switches; flag debt
43 to 45Wrap upBottlenecks, what you would build first, how it evolves

Twelve follow-up questions, with short answers.

  1. Why not store assignments in a database? 11.6 million lookups a second on the request path, plus a dependency that can take down the product. A hash gives the same answer with no storage.
  2. How do you ramp without moving users between variants? Increase coverage only; each variant's range grows from its fixed start. Changing weights needs a new phase.
  3. Two experiments change the same button. What do you do? Put both in the same layer so they are mutually exclusive.
  4. Why log exposure separately from assignment? To analyse only units that reached the change (power) and to catch execution problems (stale config, old app versions).
  5. What is counterfactual logging? Control logs an exposure at the same point the treatment would have differed, so both groups are triggered identically.
  6. How do you handle a ratio metric like CTR? Randomise by user, compute the ratio of sums, use the delta method for the variance.
  7. How do you reduce variance? Cap heavy-tailed metrics, use CUPED with pre-period data, use triggered analysis.
  8. The PM looks at results every day. Problem? Yes: false positives inflate. Use always-valid inference (mSPRT) or a planned group sequential design.
  9. Your experiment shows 50.3/49.7 on 4 million users. Do you trust it? No. That is an SRM with p far below 0.001; investigate before reading any metric.
  10. How do you catch a broken checkout in minutes? Streaming guardrails with sequential tests and a time-since-last-order check per variant, with auto-stop.
  11. A marketplace experiment shows +5% bookings. Trust it? Not without checking interference; use switchback or geo randomisation.
  12. How do you know all these wins add up? A long-term holdout per area, compared at the end of the quarter.
Deep Dive: variants of the same designShow

Client-only experimentation (small company). A hosted feature-flag product or an open-source SDK with local evaluation, exposures sent to the existing analytics warehouse, and SQL-based analysis. No stream tier; guardrails come from the existing monitoring system with per-variant tags. This covers most needs up to tens of experiments.

Warehouse-native platform. Rather than a separate pipeline, the platform runs its metric SQL directly in the company's warehouse (BigQuery, Snowflake, Databricks), reading the existing event tables. Fewer copies of data, and metrics match the company's other reports; the cost is warehouse compute and dependence on the warehouse's freshness.

Remote assignment service. For a few cases (complex eligibility that needs server-side data, or clients that cannot run an SDK), a central assignment service answers per request. It must be cached aggressively and must not sit on the critical path for high-volume calls. LinkedIn's T-REX combines both: local evaluation by default, with a backend that the reported hit rates keep almost entirely out of the path.

Multi-armed bandits. Instead of a fixed split, shift traffic towards better variants as data arrives (Thompson sampling, upper confidence bounds). Uber lists bandits among its methods. Bandits suit short-lived choices with a clear reward (which headline, which promotion) where exploration costs money. They are a poor fit when the goal is a precise, unbiased estimate of an effect, or when the reward is delayed.

Quasi-experiments. When randomisation is impossible (a city-wide price change, a legal change), use difference-in-differences or synthetic control: compare the treated region with a weighted combination of untreated regions, using pre-period trends. Uber lists both. The platform can host these analyses, with clear labels that they rest on stronger assumptions.

Interleaving for ranking. For search or recommendation rankers, interleave the results of two rankers in one list and see which ranker's items get clicked. It is far more sensitive than A/B tests for rankers, and is often used as a first filter before a full A/B test. See the recommendation system case study for ranking experiments.

Offline and email experiments. Batch jobs (email, notifications) call the same SDK with the unit id at send time and log exposure at send. Analysis is the same; the timing of exposure is the send time.

Deep Dive: how the design evolves, v1 to v3Show

v1: a few teams, tens of experiments. Flags in a config file with a hash function in a shared library. Exposures logged to the analytics warehouse. A data scientist analyses each experiment in a notebook. It works, but every analysis is hand-made, metrics differ between teams, and nobody checks for SRM. The 2009 version of LinkedIn's platform was similar: member id mod 1,000, with bucket ranges coordinated by email, which LinkedIn described as having O(test_count²) complexity, because every test owner had to coordinate with every other.

v2: self-service, hundreds of experiments. A central Experiment Service with validation; compiled, versioned config pushed to SDKs; layers for exclusivity; exposure logging with deduplication; a metric catalog; a daily pipeline producing sufficient statistics; automated scorecards with Welch t, delta method and capping. This is where most of the scale comes from. Google's 2010 paper describes this transition producing roughly an order of magnitude more experiments.

v3: trust at scale, thousands of experiments. SRM checks that hide results; A/A tests in every layer; CUPED by default; always-valid inference on live views; BH across metrics; streaming guardrails with auto-stop; holdouts per area; rollouts with guardrails; flag-debt automation. At this stage, the main risks are no longer throughput but subtle statistical and data-quality errors, multiplied by thousands of experiments and thousands of users of the platform who are not statisticians.

Later. Cluster and switchback designs for interference; bandits for short-lived choices; meta-analysis across past experiments (estimating the distribution of effects, which also tunes the mSPRT mixing variance and Twyman thresholds); long-term effect estimation from short experiments using surrogate metrics.

Key Takeaways#

  • Assignment is a pure function. Hash (salt, unit id) into 10,000 buckets inside the SDK. It is random, deterministic and independent across experiments, needs no storage, and keeps the platform off the request path.
  • Config is data, pushed and cached. Validate, version and compile rules; distribute through a CDN and a streaming channel; fall back to the last snapshot and then to compiled-in defaults.
  • Overlap by default, exclude by layer. Independent salts make overlapping experiments safe; layers make conflicting ones mutually exclusive; fresh salts break carryover.
  • Log exposure at the point of use, in both variants. Triggered, counterfactual exposure gives power and catches execution bugs; dedupe it, never sample it.
  • The pipeline is the heavy part. Millions of events a second become per-unit metrics, then tiny sufficient statistics, which make CUPED, the delta method and scorecards cheap.
  • Statistics must survive real users. Use always-valid inference for peeking, BH for many metrics, capping and CUPED for power, and non-inferiority for guardrails.
  • Check trust before results. SRM gates, A/A tests, Twyman's law and a well-chosen OEC protect the company from confident wrong decisions.
  • Safety is a config change. Streaming guardrails and silence checks stop harmful experiments in minutes by sending everyone back to control.
  • Flags, rollouts and experiments are one system. One rules engine, one SDK, with lifecycle rules that remove flags once decisions are made.