SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Deployment Strategies Overview
  • CI/CD Pipelines
  • Rolling Deployments
  • Blue-Green Deployments
  • Canary Releases
  • Feature Flags
  • A/B Testing Infrastructure
  • Schema Migrations
  • Rollbacks and Immutable Infrastructure
  • Multi-Region and Active-Active
  • Infrastructure as Code (Terraform)
  • Auto-Scaling Policies
  • Zero-Downtime Deployment
  • Chaos Engineering
  • Shadow Traffic and Dark Launches
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Deployment Patterns

A/B Testing Infrastructure

Show different versions to different users and measure which one wins.

⏱ 14 min readAdvancedHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A/B testing means showing two versions of something (A and B) to different groups of real users, and measuring which version gets a better result. The infrastructure is the machinery that makes this fair, repeatable and safe.

  • Users are split into groups by a hash of their id, so the same user always sees the same version.
  • Every user action is logged as an event and linked to the group the user was in.
  • A statistics step then asks: is the difference real, or just luck?

02Concept: What is it?

Imagine you changed the colour of the "Buy" button. Sales went up the next week. Was it the button? Maybe it was payday, or a sale, or just a lucky week. You cannot know. An A/B test removes this doubt: during the same days, half of the users see the old button (A, the control) and half see the new one (B, the variant). Everything else is equal, so a difference in results can be blamed on the button.

To run this at scale you need more than an if statement. You need a way to assign users to groups, a way to serve the right version, a way to record what each user did, and a way to analyse the results correctly.

The parts of an A/B testing system
🙋Userid = 4821
→↓request
🎲Assignmenthash(exp + id)
→↓A or B
🖥️Appshows the version
→↓events
🧾Event loguser, group, action
→↓batch
📊Analysisis it real?
Assignment and logging must be solid. If a user is placed in different groups on different visits, the whole result is spoiled.
🧠Why a hash, and not a coin flip?
A coin flip on each request would show the same user A today and B tomorrow. Hashing experiment name + user id gives a number from 0 to 1 that never changes for that user. If the number is below 0.5 the user is in B. No database lookup is needed, and every server agrees.

03Real-Life Example

🍵Two Menus in One Restaurant
A restaurant wants to know if a new menu design makes people order more dessert. The owner does not change the menu for one week and compare it with last week, because the weather and the holidays are different. Instead, on the same evenings, tables with an odd number get the new menu and even tables get the old one. At the end the owner counts dessert orders per table type. One more rule: a table keeps its menu for the whole evening. If a family got the new menu for the starter and the old one for dessert, nobody could tell what caused what.
Restaurant
A/B testing system
Odd or even table number
Hash of the user id decides the group
Old menu
Version A, the control
New menu
Version B, the variant
The same evenings for both
Both groups run at the same time
Counting dessert orders
The success metric (conversion)
A table keeps its menu all evening
Sticky assignment, the same user always gets the same version
A week with only 10 tables
A sample that is too small to trust
One user, from first visit to result
👀Exposureuser sees A or B
→↓
🖱️Actionclicks, buys, leaves
→↓
🧾Eventlogged with the group
→↓
🧮Countedper group

04Why Do We Need It?

🔬Cause, not guesses
Only a fair split run at the same time lets you say that the change caused the result.
🛡️Safe to try
A bad idea reaches only a small share of users, and you stop it quickly.
💰Avoid costly mistakes
Opinions are often wrong. Data stops the team from shipping a change that hurts revenue.
🧠Learn about users
Even a failed test teaches you what users do not care about.
🔁Many tests at once
A platform lets many teams run different experiments without stepping on each other.
📏One shared method
Everyone uses the same checks for sample size and significance, so results can be trusted.
Do not ask "did the number go up?". Ask "is the difference bigger than what luck alone would give?". The infrastructure exists to answer that fairly.

05Where Do We Use It?

🛒E-commerce
Button text, page layout, price display, the checkout steps.
📺Streaming and media
Thumbnails, recommendations, the order of rows on the home screen.
📱Mobile apps
Onboarding flows, notification wording, sign-up screens.
🔎Search and ranking
A new ranking model is shown to a slice of queries and compared with the old one.
📣Email and marketing
Subject lines and send times.
⚙️Backend changes
A faster cache or a new algorithm, to prove that it does not hurt the user experience.

06Types / Parts / How It Works

The building blocks

PartJobGood to know
Assignment serviceDecide the group for a user and an experimentHash (experiment name + user id). Same input gives the same group, with no storage.
Config / experiment registryStore which experiments are live, the traffic split and the targeting rulesChanges should take effect without a deploy, like a feature flag.
Exposure loggingRecord that the user really saw the versionLog at the moment of display. Counting users who were assigned but never saw it dilutes the result.
Event pipelineCollect clicks, purchases and other actionsEvents carry the user id, so they can be joined with the group.
Metrics layerTurn events into numbers: conversion, revenue per user, latencyDefine each metric once, so every team measures it the same way.
Stats engineCompare the groups and report confidenceMust handle sample size, p-values or Bayesian results, and the checks below.

Checks that keep a test honest

CheckWhat it catches
Sample ratio mismatch (SRM)You asked for a 50/50 split but got 52/48. This usually means a bug in assignment or logging, and the result cannot be trusted.
A/A testTwo identical versions. A healthy system shows “no difference” about 95 times in 100.
Guardrail metricsThings that must not get worse (page speed, errors, unsubscribes) even if the main metric improves.
Sample size planDecide before you start how many users you need, and do not stop sooner.
Mutual exclusion / layersStop two tests that touch the same screen from mixing their effects.
Layers: many tests, no collisions
Layer: checkout page
Test 1: button colourusers 0 to 50%
Test 2: payment orderusers 50 to 100%
Layer: search ranking
Test 3: new rankerall users, own hash
Same layer: never together Other layer: independent
Tests in the same layer never overlap for a user. Tests in different layers use different hashes, so groups are independent.
VisualizerA fixed experiment: bucketing, evidence and the danger of peekingLeave the true lift at 0% (A and B are the same) and drag the users slider through Run 1. Early on, the test may say B wins. Then raise the lift and see how many users you need.
Which experiment run?
First 30 users: each box is one user, placed by a hash of (experiment + user id). Cyan = A (current), purple = B (new). Reload the page and every user lands in the same group.
B
A
A
A
A
B
A
B
A
B
B
B
A
A
B
A
A
A
B
A
B
A
B
A
B
A
B
B
B
A
Evidence at each checkpoint (bar height = |z|, how far apart A and B look). Red bars cross the line, so a tool would call them "significant". The white outline is where you are looking now.
p = 0.05 line
250 users5,00010,000
Group A
9.9%
4,930 users
Group B
9.8%
5,070 users
Measured lift
-1.4%
true lift 0%
p-value
0.820
below 0.05 = significant
Looks that said winner
1
of 40 checkpoints so far
No significant difference (p = 0.82). That is the right answer, because the true lift is 0%. Try moving the users slider back to see if a quick look would have fooled you.

A simplified model with fixed hashes and no random numbers. A converts at 10.0%. Group sizes follow the traffic split, so they are not exactly equal. The users needed use the rule of thumb n = 16 × p × (1 − p) / difference², for about 80% power at 5% significance. Illustrative numbers, not a real product.

07How to Use It / Steps / Implementation

Running a good experiment

  1. 1
    Write a hypothesis
    “Changing the button text to ‘Get started’ will raise sign-ups.” Pick ONE main metric before you begin.
  2. 2
    Pick guardrail metrics
    Choose what must not get worse: speed, error rate, refunds. A win that breaks these is not a win.
  3. 3
    Plan the sample size
    From your current rate, the smallest lift that matters, 5% significance and about 80% power, work out how many users per group you need. Then decide the run time, in whole weeks, so that every weekday is covered.
  4. 4
    Assign with a hash
    bucket = hash(experiment name + user id) mod 10000. Use a different name for each experiment, so groups from different tests are independent.
  5. 5
    Log the exposure
    Record the group at the moment the user sees the version. Include the experiment name, the group and a timestamp.
  6. 6
    Check the setup first
    After the first day look for a sample ratio mismatch, broken logging or a big drop in a guardrail metric. Do NOT look for winners yet.
  7. 7
    Wait, then analyse once
    Reach the planned sample size, then read the result. If you need to look earlier, use a method built for it (sequential testing) and not a plain p-value.
  8. 8
    Decide and clean up
    Ship the winner to everyone, remove the losing code and the flag, and write down what you learned.
⚠️Peeking is the most common mistake
A p-value is only valid if you look once, at the planned size. If you check every day and stop the first time it shows "significant", the real chance of a false winner is far above 5%. The visualizer above shows this: with no real difference, some moments still cross the line.
💡Run it for whole weeks
People behave differently on a Monday and on a Saturday. A test that runs for 3 days sees only part of the cycle.

08Key Terms to Know

TermMeaning in easy words
Control (A)The current version that everything is compared against
Variant (B)The new version you are testing
BucketingPlacing each user in a group, usually by hashing the user id
Sticky assignmentThe same user always gets the same version
ExposureThe moment a user actually sees a version
Conversion rateThe share of users who did the wanted action, such as buying
LiftHow much better B is than A, as a percentage
p-valueHow surprising the result would be if there were really no difference. Below 0.05 is the usual line for “significant”
Statistical powerThe chance of spotting a real effect. About 80% is common
Sample ratio mismatch (SRM)Group sizes differ from the planned split, a warning that something is broken
Guardrail metricA metric that must not get worse, even if the main one improves

09Pros, Cons and Trade-offs

✅ Pros
  • Shows cause and effect with real users
  • Limits the damage of a bad idea
  • Ends opinion fights with data
  • Same method for every team
  • Works for UI, models and backend changes
⚠️ Cons
  • Needs a lot of traffic to see small effects
  • Takes weeks, so it slows decisions
  • Easy to misread (peeking, many metrics)
  • Needs solid logging and a stats engine
  • Short-term gains may hide long-term harm

Trade-offs

ChoiceWe gainWe lose
Small traffic share for BLow risk if B is badA longer test to reach the sample size
Large traffic share for BA faster answerMore users see a possibly bad version
Stop early at a good resultQuick decisionMany false winners, and exaggerated effects
Many metricsA fuller pictureMore chances for a lucky “significant” one by chance
Build it yourselfFits your data and rulesA lot of work to get the statistics right
Buy a platformTested statistics and a UICost, and your data goes to another system

10Common Problems and Mistakes

Common mistakes

  1. Peeking and stopping early. The most common cause of false winners.
  2. No sample size plan. The test runs "until it looks good".
  3. Too many metrics. If you check 20 metrics, about one will look significant by luck alone.
  4. Ignoring sample ratio mismatch. A 50/50 test that is really 53/47 has a bug, and the numbers cannot be trusted.
  5. Counting users who never saw B. Assigned is not the same as exposed.
  6. Changing the test while it runs. Moving the traffic split or fixing a bug mid-test mixes two different experiments.
  7. Overlapping tests. Two tests on the same page without layers mix their effects.

Things to watch

🆕Novelty effect
Users click a new thing just because it is new. The lift fades after a week or two.
🔗Network effects
In social products, users in A and B talk to each other. The groups are not independent.
🍪Identity
If a user is not logged in, a new cookie means a new user. The same person can end up in both groups.
🤖Bots
Bot traffic adds noise and can hide a real effect.

11Real-World Examples

🧰Experiment platforms
Large product companies build internal platforms with assignment, layers, metrics and a stats engine.
🧪Third-party tools
Services such as Optimizely, LaunchDarkly, Statsig and GrowthBook offer this as a product.
🚩Feature flag link
Most platforms build on feature flags: the flag decides the version, and the experiment decides who gets which.
🤖Model rollouts
A new recommendation or ranking model is often tested on a share of traffic before it replaces the old one.
📈Always-on A/A tests
Some teams run permanent A/A tests to check that the system itself is healthy.
🧯Safety first
Guardrail metrics can stop a test automatically if errors or latency rise.
📝Note
Platforms and their features change over time. Check each product's docs before you rely on a feature.
Mini case: testing a new checkout button
👥100,000 usersover 2 weeks
→↓hash
🅰️A: 50,00010.0% buy
🅱️B: 50,00010.6% buy
→↓stats
✅+6% liftp below 0.05, guardrails fine
Illustrative numbers.

12Related Topics to Read Next

Feature Flags→

The switch that decides which version a user sees.

Canary Releases→

Similar traffic splitting, but for safety instead of measuring.

Consistent Hashing→

Another use of hashing to place things in a stable way.

Metrics and Instrumentation→

Where the numbers behind each experiment come from.

Batch vs Stream Processing→

How the event data is processed into results.

Deployment Strategies Overview→

Where experiments fit among the ways to release changes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: show A and B to different users at the same time, then compare results.
  • ✔Assign: hash(experiment + user id). Stable, no storage, same on every server.
  • ✔Log: record exposure and events with the group.
  • ✔Before: one main metric, guardrails, and a planned sample size.
  • ✔Check: sample ratio mismatch first, winners last.
  • ✔Do not: peek and stop early, test many metrics, or change a running test.
  • ✔Run: whole weeks, then analyse once.
  • ✔One line: “Split fairly, measure honestly, and decide once.”
← Previous
Feature Flags
Next →
Schema Migrations