A/B Testing: The Applied Playbook

Day 11 built confidence intervals. Day 12 built hypothesis tests. A/B testing is where both of those tools actually come to life: the process companies use to make real product decisions through controlled experiments instead of gut feeling.

Before the experiment 1 Define the metrics 2 State H₀ and H₁ 3 Choose α and power 4 Size it from the MDE 5 Fix the duration During 6 Randomize and run no peeking After 7 Sanity checks first then the test 8 Ship, don't ship, or iterate Before the experiment 1 Define the metrics 2 State H₀ and H₁ 3 Choose α and power 4 Size it from the MDE 5 Fix the duration During 6 Randomize and run no peeking After 7 Sanity checks first then the test 8 Ship, don't ship, or iterate
The eight steps of an A/B test, which Part 3 walks through. Five of them happen before a single user sees the new experience, and that's where most experiments are won or lost.

The bridge from Days 11 and 12

Day 12 ended with a solid hypothesis testing framework. A/B testing is that same framework, plus a set of practical questions the theory alone never answers. How do you actually decide which users get control and which get treatment? How long do you let the experiment run? What do you do when the p-value changes every time it gets checked? What if one group ends up with more high-value users just by chance? How do you handle experiments where users can influence each other?

These are exactly the questions that separate someone who understands statistics from someone who can actually run an experiment people trust. This article covers both halves.

Five problems, five experiments

Five companies, five product decisions, five experiments.

As on Days 11 and 12, the company names make the setting concrete, but the scenarios are illustrations: the traffic, rates, results and business figures are invented for teaching, not any company's real numbers or methods. Where a real, documented experiment comes up later in the article, it's marked as a real case and the source is named.

Problem 1: Netflix, does continuous autoplay increase next-episode engagement?

Netflix is testing a continuous autoplay feature, the next episode starts automatically after a 10-second countdown instead of waiting for a manual click. The current next-episode click rate (people who voluntarily start the next episode within 5 minutes of finishing one) is 52%. Netflix's product team believes autoplay could push this to at least 57%, so 5 percentage points is the smallest lift worth acting on, and the experiment gets sized to catch a lift of that size.

The experiment: 4,000 users in control (old experience), 4,000 in treatment (autoplay on).

The question: "Is the lift in next-episode engagement real, and big enough to justify the UX change, given some users might find autoplay annoying?"

Problem 2: Uber, does a redesigned surge UI increase driver acceptance?

Uber's driver experience team redesigns the surge pricing notification screen, adding an estimated earnings preview and a small map of demand hotspots. The current driver acceptance rate on surge trips is 68%. The metric is measured per driver: over the test period, each driver accepts some share of the surge requests they're offered, so every driver contributes one number, their own acceptance rate. The team wants to catch any improvement of at least 3 percentage points.

The experiment: 3,500 drivers see the old surge screen (control), 3,500 see the new design (treatment).

The question: "Does knowing their projected earnings before accepting actually make drivers more likely to take surge trips?"

Problem 3: Swiggy, does a new ML restaurant ranking improve order completion?

Swiggy's data science team builds a new restaurant ranking algorithm that personalizes results based on a user's past orders, time of day, and current weather. The current order completion rate (users who actually place an order in a session) is 71%. This one runs as a one-tailed test, since the team only cares whether the new ranking is better, not just different: if it's worse or the same, the action is identical, keep the current ranking. The team wants to catch a lift of at least 3 percentage points.

The experiment: 5,000 users see the current ranking (control), 5,000 see the personalized ranking (treatment).

The question: "Does personalized ranking actually lead to more people completing an order?"

Problem 4: Spotify, does a redesigned onboarding flow improve 30-day retention?

Spotify's growth team redesigns the new-user onboarding flow, replacing a generic "tell us what you like" genre picker with a "play three songs and we'll tune to you" interactive experience. Current 30-day retention for new users is 38%. They want to catch a meaningful change in either direction here, since the new flow could just as easily confuse people, so this one's a two-tailed test. A change of 4 percentage points either way is the smallest one the team would act on.

The experiment: 6,000 new users go through the old onboarding (control), 6,000 go through the new one (treatment).

The question: "Does an interactive onboarding experience actually keep new users around longer?"

Problem 5: Google, does a new search result card design increase CTR?

Google's Search team redesigns the visual layout of one type of result card, a bolder title font, a cleaner URL display, a subtle favicon. The card currently gets clicked 3.1% of the times it's shown, that's its click-through rate (CTR). A rate this low fits a card that sits further down the results page, the first result on a page gets clicked far more often than that. Assume, for this illustration, that the card is shown about a billion times a day. At that scale, even 0.1 percentage points matters here.

The experiment: 80,000 users (identified by browser cookie) see the old card (control), 80,000 see the new card design (treatment). To keep the analysis simple, each user counts once: did they click the card the first time they saw it during the test?

The question: "Does the new card design actually increase CTR, and is that lift practically meaningful at Google's scale, or just a statistical artifact of a massive sample size?"

Part 1: What an A/B test actually is

An A/B test is a randomized controlled experiment. Take a population, users, trips, orders, sessions, split it randomly into two groups, show each group a different experience, and measure whether the difference in outcomes is real or just noise.

"A" is the control, the current experience, the status quo. "B" is the treatment, the change actually being tested.

The random part is the whole ballgame. Without it, a difference in outcomes can't actually be attributed to the change, it could just as easily be because the two groups happened to be different kinds of people to begin with.

Think of it like testing whether a new fertilizer makes plants grow taller. Put the new fertilizer on plants in the sunny corner of a greenhouse and the old one on plants in the shade, and any height difference could be the fertilizer, or it could just be the sunlight, the variables have gotten mixed up. The fix: randomly assign fertilizer A or B to each plant regardless of where it happens to sit. Now any consistent height difference has to come from the fertilizer. That's exactly why randomization sits at the heart of A/B testing.

Population users, drivers, sessions, orders hash(id) Control (A) current experience Treatment (B) the new thing Same clock, same world any difference left over must be the treatment Population users, drivers, sessions hash(id) Control (A) current experience Treatment (B) the new thing Same clock, same world any difference left over must be the treatment
A hash of each user's ID decides their group, so the split has nothing to do with who they are. Both groups then live through the exact same external world at the exact same time. That's what a before-after comparison can never offer, and it's the entire reason randomized, parallel experiments earn the name "gold standard."

Why not just compare before and after?

Before companies adopt real A/B testing, a common approach is comparing a metric before launching a feature to the same metric after. It sounds reasonable. It's actually deeply flawed.

Netflix's watch time in January versus February will differ because of new content releases, seasonal patterns, and app updates, not just whatever algorithm change happened to ship in between. The effect of a change can never be cleanly separated from everything else that changed at the same time. A controlled experiment run in parallel avoids this entirely, both groups live through the exact same external world at the exact same time.

Before vs after one line, feature ships on day 15 launch before avg after avg averages differ by 2.2 only 0.5 is the feature 1 7 14 21 28 A/B test two groups, same 28 days treatment control gap 0.5: the feature 1 7 14 21 28 day Before vs after one line, feature ships on day 15 launch before avg after avg averages differ by 2.2 only 0.5 is the feature 1 7 14 21 28 A/B test two groups, same 28 days treatment control gap 0.5: the feature 1 7 14 21 28 day
An illustration with made-up numbers. Left: a feature ships on day 15, and the metric is higher afterwards, but the metric was already climbing (a big release, a holiday, a marketing push), so the before-after gap mixes the feature's effect with everything else that changed. Right: the same weeks with a parallel control group. Both lines ride the same seasonal wave, and the gap between them is the feature's effect on its own.
Real case: the Bing headline that sat on a shelf

In 2012, a Microsoft employee working on Bing had an idea for changing the way the search engine displayed ad headlines. It was one idea among hundreds, it was judged low priority, and it sat untouched for more than six months. Then an engineer, figuring it would be cheap to try, launched a simple A/B test. Within hours the new headline variation was producing such abnormally high revenue that it triggered a "too good to be true" alert, the kind that usually signals a bug. It wasn't a bug. The change raised revenue by 12% without hurting the key user-experience metrics, which Ronny Kohavi and Stefan Thomke later reported in Harvard Business Review (2017) would come to more than $100 million a year in the United States alone.

The same article makes a less glamorous point that matters just as much: at Google and Bing, only about 10% to 20% of experiments generate positive results. Most ideas, even ones that sound great in a meeting, don't move the metric at all. Without controlled experiments, nobody can tell the rare big winner from the many duds, and in this case nobody would have known the idea at the bottom of the list was worth $100 million a year.

Part 2: The anatomy of an experiment

Before writing a single line of code, four structural decisions decide the quality of everything that follows.

1. The randomization unit

This is what actually gets randomly assigned, and it isn't always "a user."

ProductWhat gets assignedWhy
NetflixUser accountWatch behavior is account-level
UberDriver ID (for a driver-app change)Accept or decline decisions are made per driver
SwiggyUser account (device ID for logged-out users)Orders belong to an account, and someone using both a phone and a laptop should see one ranking
SpotifyUser IDListening patterns are per user
Google SearchBrowser cookie, or the account for signed-in usersOne person keeps seeing the same design on every search; randomizing each search separately would show them both

One rule matters more than the others: analyze the data at the level it was randomized, or use a method that properly accounts for the difference. Randomize by user, but then treat every click or every session as its own independent data point, and the many similar actions of one person get counted as separate pieces of evidence. That makes the standard error too small, and the result looks far more certain than it is. Go the other way, randomizing something finer than the person (each search or each session separately) while measuring a per-person outcome, and the same person can end up seeing both versions, which blurs the comparison and can confuse users. The quick check at the end of the article walks through the standard fix.

2. Control vs. treatment

Control (A): the existing experience, also called the baseline. Treatment (B): the new experience. The hypotheses from Day 12 sit on top of this pair: the null hypothesis says the treatment makes no difference, the two groups share the same true rate, and the alternate hypothesis says it does make a difference. Control is what the world looks like if the null hypothesis is true.

More than one treatment can run at once (A/B/C testing), but each extra variant shrinks the sample available to every group and adds a multiple testing problem on top. For most early-stage experiments, one treatment is plenty.

Real case: 24 versions of one sign-up page, Obama 2008

Many variants can work when there's enough traffic. In December 2007, Barack Obama's presidential campaign tested the splash page that asked visitors to sign up with their email address. Dan Siroker, the campaign's Director of Analytics (who later co-founded Optimizely), wrote up the experiment in 2010. The team tested 4 button labels against 6 pieces of media, three images and three videos, so 24 combinations, across 310,382 visitors, roughly 13,000 per combination.

The original page signed up 8.26% of visitors. The winning combination, a "Learn More" button with a family photo, signed up 11.6%, a 40.6% relative improvement. Every video did worse than every image, including a video the staff had favored and would probably have used without the test. Assuming that lift held for the rest of the campaign, Siroker estimated it brought in about 2.88 million extra email addresses and, at an average of $21 donated per email sign-up, roughly $60 million in extra donations. That last figure is a back-of-the-envelope extrapolation rather than a measured result, but the pattern is the real lesson: the confident guess (the favorite video) lost, and only the experiment showed it.

Notice what made this possible: 310,000 visitors spread over 24 cells still left about 13,000 per cell. With a few thousand visitors, the same design would have left each cell too small to detect anything but enormous differences.

3. The metrics

This is where most experiments actually fail, not in the analysis, in how the metric gets defined in the first place.

The primary metric is the one number that answers the question. Every A/B test needs exactly one, chosen before the experiment starts. Pick it after seeing the results and that's p-hacking. Guardrail metrics need to stay stable, they catch collateral damage. Secondary metrics just help explain what's happening, they don't get to decide anything.

CompanyPrimary metricGuardrail metricsSecondary metrics
NetflixNext-episode click rateUnsubscribe rate, complaintsSession length, ratings
UberDriver acceptance rateTrip cancellation rate, app crashesEarnings per trip, ratings
SwiggyOrder completion rateSession abandonment rateItems per order, avg order value
Spotify30-day retentionSkip rate, complaint ratePlaylist saves, feature discovery
GoogleCTR on the redesigned cardTime-to-click (too fast means accidental), clicks on other resultsScroll depth, bounce rate

A guardrail is what actually makes a "winner" a winner. Netflix's autoplay might raise next-episode rates while also raising unsubscribes, that's not a win, that's a trade-off, and it needs a leadership call, not a quiet ship decision.

4. The exposure window

How long the experiment runs has to be decided before it starts.

A few rules of thumb: run for at least one full week to capture weekday and weekend behavior, since people behave differently on each, and run in whole weeks so no weekday is over-represented. Run longer for new-user experiments, often at least two weeks, so the test covers people who signed up on different days, and long enough that the outcome itself can be measured: a 30-day retention metric needs every user to have had 30 days since they entered the test. Never stop early just because a significant result happened to show up, that's the peeking problem, coming up shortly. And never extend the experiment just because significance wasn't reached either, that's p-hacking wearing a different disguise.

Part 3: The eight-step framework

Here's the full, industry-standard process. Steps 1 through 5 all happen before a single data point gets collected.

Before the experiment

Step 1: Define primary, guardrail, and secondary metrics. Step 2: State hypotheses (H₀ and H₁). Step 3: Choose α and target power. Step 4: Calculate required sample size (minimum detectable effect). Step 5: Determine experiment duration.

During the experiment

Step 6: Randomize and run. Do not peek.

After the experiment

Step 7: Run the sanity checks (group sizes first, then baseline balance), then run the statistical test. Step 8: Make the decision (ship / no-ship / iterate).

Part 4: Sample size and power, before you start anything

This is one of the most skipped steps in amateur experimentation, and one of the most important in the professional version. Running an underpowered experiment is a bit like going to court with too little evidence, the guilty usually walk (a real effect goes undetected) and everyone's time gets wasted doing it.

The two-proportion sample size formula

When the primary metric is a proportion, click rate, conversion rate, retention, which is most of them in tech, the sample size formula per group looks like this:

n = [ zα/2 √(2p(1−p)) + zβ √(p₁(1−p₁) + p₂(1−p₂)) ]²(p₂ − p₁)²
n is the number per group. p₁ = baseline rate, p₂ = the rate after the change if the lift is exactly the MDE (the smallest lift worth catching, next section), p = their average. zα/2 = 1.96 for a two-tailed test at α = 0.05 (use zα = 1.645 for one-tailed), zβ = 0.84 for 80% power.

The two terms in the numerator are each doing a different job. The first (zα/2) sets where the "significant" line sits, so that false positives stay at the rate actually chosen. The second (zβ) makes sure there's enough data to catch real effects at the power wanted. Both have to be satisfied at once, exactly why they get added together rather than picked between.

That zβ=0.84 figure isn't a rule of thumb, it comes directly from the power asked for. Power is the probability of correctly detecting a real effect, and 80% power means wanting the true effect to clear the detection threshold 80% of the time. The z-score sitting at the 80th percentile of a standard normal distribution is 0.84 (stats.norm.ppf(0.80)), so that's the value going into the formula. Ask for 90% power instead and zβ becomes 1.28, a bigger number, pushing the required sample size up too, since higher power needs more data, the same way higher confidence needs a bigger zα.

The minimum detectable effect (MDE)

Before computing a sample size, one question needs an answer: what's the smallest improvement actually worth caring about?

This is a business call, not a statistical one. It comes down to the cost of rolling the change out (engineering time, infrastructure), the risk involved (user trust, brand), and the expected benefit at scale (revenue, engagement). A feature that takes three months to build probably only earns its keep at a 5%+ lift. A one-day CSS tweak might be worth shipping for a 0.5% lift.

One rule follows from this, and it's easy to get wrong: the sample size gets computed from the MDE, never from the lift the team is hoping for, and never from the result that eventually shows up. Sizing for an optimistic lift produces a small, cheap experiment that will usually miss a real but smaller effect. Sizing from the observed result, after the fact, is circular: it can only ever say the experiment was big enough to find what it found. So each experiment below is sized for the MDE in its problem statement.

Pythonimport numpy as np from scipy import stats def sample_size_two_proportion(p_baseline, p_treatment, alpha=0.05, power=0.80, tails=2): """Sample size per group for a two-proportion z-test.""" z_alpha = stats.norm.ppf(1 - alpha / tails) z_beta = stats.norm.ppf(power) p_bar = (p_baseline + p_treatment) / 2 numerator = (z_alpha * np.sqrt(2 * p_bar * (1 - p_bar)) + z_beta * np.sqrt(p_baseline*(1-p_baseline) + p_treatment*(1-p_treatment)))**2 denominator = (p_treatment - p_baseline)**2 return int(np.ceil(numerator / denominator)) # Each experiment sized for its MDE: the smallest lift worth catching print(f"Netflix (52% -> 57%, two-tailed): n = {sample_size_two_proportion(0.52, 0.57):,}") print(f"Swiggy (71% -> 74%, one-tailed): n = {sample_size_two_proportion(0.71, 0.74, tails=1):,}") print(f"Spotify (38% -> 42%, two-tailed): n = {sample_size_two_proportion(0.38, 0.42):,}") print(f"Google (3.1% -> 3.2%, two-tailed): n = {sample_size_two_proportion(0.031, 0.032):,}")
OutputNetflix (52% -> 57%, two-tailed): n = 1,556 Swiggy (71% -> 74%, one-tailed): n = 2,739 Spotify (38% -> 42%, two-tailed): n = 2,354 Google (3.1% -> 3.2%, two-tailed): n = 478,903

Uber's metric is different. Each driver contributes their own acceptance rate, a continuous number per driver, so the comparison is between two averages (a t-test, Day 12) rather than two proportions. The sample size formula for two means has the same structure, with the metric's standard deviation σ in place of the p(1−p) terms:

n = 2 (zα/2 + zβ)² σ²MDE²
n per group, with σ estimated from historical data on the same metric, before the experiment starts.
Pythondef sample_size_two_means(sd, mde, alpha=0.05, power=0.80, tails=2): """Sample size per group for comparing two means (similar SDs assumed).""" z_alpha = stats.norm.ppf(1 - alpha / tails) z_beta = stats.norm.ppf(power) return int(np.ceil(2 * (z_alpha + z_beta)**2 * sd**2 / mde**2)) # Assumed from past data: per-driver acceptance rates vary with an SD of about 14.7pp print(f"Uber (+3pp on a per-driver rate, two-tailed): n = {sample_size_two_means(0.147, 0.03):,}")
OutputUber (+3pp on a per-driver rate, two-tailed): n = 377

Netflix needs 1,556 people per group to reliably catch a 5-point lift, and it has 4,000. Swiggy needs 2,739 for a 3-point lift, one-tailed, and has 5,000. Spotify needs 2,354 for a 4-point change in either direction, and has 6,000. Uber needs only about 377 drivers per group, because each driver's acceptance rate averages over many surge offers and so carries a lot of information, and it has 3,500. All four experiments are comfortably big enough for what they're trying to detect.

Google is the one that doesn't add up, and it's worth slowing down on. The problem says even 0.1 percentage points matters, and catching a 0.1-point lift on a 3.1% baseline takes about 479,000 users per group. The planned experiment has 80,000. Run the formula backwards and 80,000 per group is only enough to reliably catch a lift of about 0.25 percentage points, two and a half times the lift the team said it cared about. This is exactly the mismatch a design review exists to catch before launch: either the MDE is really 0.25 points, or the experiment needs to be six times bigger. For Google, the second option is cheap. At an assumed billion card impressions a day, 479,000 users per group is a small slice of a single day's traffic, and that's exactly why Google can afford to chase tiny CTR lifts at all. A startup with 1,000 daily users would need about 958,000 users in total, more than two and a half years of traffic, so it couldn't run this particular experiment no matter how badly it wanted to. (Solution 5 comes back to this: the actual lift turned out large enough for 80,000 per group to catch, but a 0.1-point lift would most likely have been missed.)

The lesson underneath all of this: the smaller the effect being chased, the more data it takes, and how much data is actually available quietly decides which experiments are even possible to run.

How MDE shapes the decision

Python# Netflix, sample size vs minimum detectable lift (baseline 52%, two-tailed) for mde in [0.01, 0.02, 0.03, 0.05, 0.09, 0.15]: n = sample_size_two_proportion(0.52, 0.52 + mde) label = f"+{mde*100:.0f}pp" print(f"MDE = {label:<5} -> n = {n:>7,} per group")
OutputMDE = +1pp -> n = 39,146 per group MDE = +2pp -> n = 9,775 per group MDE = +3pp -> n = 4,338 per group MDE = +5pp -> n = 1,556 per group MDE = +9pp -> n = 476 per group MDE = +15pp -> n = 167 per group

Detecting a 1-point lift takes roughly 234 times more data than detecting a 15-point lift. That's not a rounding curiosity, it comes straight from the shape of the formula. The denominator is (p₂−p₁)², the effect size squared. Halve the effect being chased and the required sample doesn't double, it roughly quadruples, because the effect sits in the denominator squared. (Not exactly 4 times, or exactly 225 times for 1 point against 15, because the p(1−p) terms in the numerator shift a little as p₂ moves.) This is exactly why teams almost always negotiate the MDE before touching the sample size formula at all, agreeing on the smallest lift worth acting on is really agreeing on how long everyone's willing to wait.

0 10,000 20,000 30,000 40,000 1pp: 39,146 2pp: 9,775 3pp: 4,338 15pp: 167 5pp, Netflix's MDE: 1,556 per group 1pp 3pp 5pp 7pp 9pp 11pp 13pp 15pp minimum detectable effect (lift above the 52% baseline) users needed per group 0 10,000 20,000 30,000 40,000 1pp: 39,146 2pp: 9,775 15pp: 167 5pp, Netflix's MDE: 1,556 per group 1pp 3pp 5pp 7pp 9pp 11pp 13pp 15pp minimum detectable effect (lift above the 52% baseline) users needed per group
The curve isn't gentle, it's an inverse square. Netflix's actual MDE of 5 points needs 1,556 users per group. Catching a 1-point lift would need 39,146, about 25 times more for an effect 5 times smaller, because the effect sits in the denominator squared.

Part 5: Randomization, the integrity of the whole experiment

Random assignment is what separates A/B testing from just watching people and drawing conclusions. Get this part wrong and everything downstream is invalid, no matter how careful the analysis looks afterward.

How to actually randomize

User-level hashing is the standard approach:

Pythonimport hashlib def assign_variant(user_id: str, experiment_name: str, traffic_percentage: float = 0.50) -> str: """ Deterministically assign a user to control or treatment. Same user always gets same variant for the same experiment. Adding experiment_name prevents the same users always landing in treatment. """ hash_input = f"{experiment_name}_{user_id}" hash_value = int(hashlib.md5(hash_input.encode()).hexdigest(), 16) bucket = (hash_value % 10000) / 10000 # 0.0000 to 0.9999 return "treatment" if bucket < traffic_percentage else "control" for user_id in ["user_001", "user_002", "user_003", "user_042"]: variant = assign_variant(user_id, experiment_name="spotify_onboarding_v2") print(f" {user_id} -> {variant}")
Output user_001 -> treatment user_002 -> control user_003 -> control user_042 -> control

MD5 gives three things at once: the same user always lands in the same variant (deterministic), the assignment is uniform and unrelated to anything about the user (nobody's biased toward being an early or late signup), and different experiments assign the same user independently, since the experiment name is baked directly into the hash. That last property matters: if every experiment used the same buckets, the same unlucky users would land in treatment every time, and the effects of one experiment would bleed into the next. (MD5 isn't used here for security, just as a fast, well-mixed way to turn an ID into a number. Note that with only four users, there's no reason to expect an even 2/2 split; balance only shows up across thousands.)

The sanity check, always do this first

Before analyzing any results, check that the randomization actually worked. There are two checks, and the order matters.

Check 1: did each group get the share it was supposed to?

The most important sanity check is also the simplest. A 50/50 split of 8,000 Netflix users should land close to 4,000 each. Chance alone typically moves it by a few dozen either way (the standard deviation of the count is about 45), and almost never by more than about 130. When the counts drift further than chance can explain, it's called a sample ratio mismatch (SRM), and it almost always means something in the pipeline is broken: a bug in the assignment code, a redirect that loses some treatment users before they're logged, a bot filter that treats the two groups differently, or a new feature that crashes for some users so their visits never get recorded. A chi-square goodness-of-fit test compares the observed counts with the counts the planned split says should appear.

Pythondef srm_check(n_control, n_treatment, expected_share=0.5): """Chi-square test: do the group sizes match the planned split?""" total = n_control + n_treatment expected = [total * (1 - expected_share), total * expected_share] chi2, p_val = stats.chisquare([n_control, n_treatment], f_exp=expected) verdict = "OK" if p_val >= 0.001 else "SAMPLE RATIO MISMATCH: stop and debug" print(f"control={n_control:,} treatment={n_treatment:,} chi2={chi2:.2f} p={p_val:.4f} {verdict}") srm_check(4_000, 4_000) # the planned Netflix split srm_check(4_052, 3_948) # a small wobble, well within what chance produces srm_check(4_000, 3_700) # about 300 treatment users went missing somewhere
Outputcontrol=4,000 treatment=4,000 chi2=0.00 p=1.0000 OK control=4,052 treatment=3,948 chi2=1.35 p=0.2449 OK control=4,000 treatment=3,700 chi2=11.69 p=0.0006 SAMPLE RATIO MISMATCH: stop and debug

Two details are worth understanding. First, the threshold is much stricter than 0.05. Teams run this check on every single experiment, so a loose threshold would raise false alarms constantly, and a real SRM is usually not subtle: losing 300 users out of 4,000 gives a p-value under 0.001. Second, when the check fails, the right response is to stop and find the cause, not to adjust the numbers and carry on. An SRM means the users who made it into the analysis are not the users randomization picked. If the missing 300 treatment users were the ones for whom the new feature crashed, the remaining treatment group is a filtered, happier-than-average crowd, and no statistical test afterwards can undo that. Researchers from Microsoft and Booking.com who catalogued the causes (Fabijan and colleagues, at the KDD conference in 2019) compare an SRM to a fever: a symptom of many different underlying problems, and one that should never be ignored, because ignoring it can make a bad product change look good.

Check 2: do the groups look alike on things the change couldn't affect?

Once the counts check out, the two groups should look alike on any metric that wasn't being tested, especially things measured before the experiment started.

Pythonfrom scipy import stats def sanity_check(control_df, treatment_df, check_columns): """ For each baseline metric, check that control and treatment are not significantly different BEFORE the experiment. If they are, randomization failed. """ print(f"Control n={len(control_df):,} | Treatment n={len(treatment_df):,}") all_passed = True for col in check_columns: ctrl_mean = control_df[col].mean() trt_mean = treatment_df[col].mean() _, p_val = stats.ttest_ind(control_df[col], treatment_df[col]) status = "PASS" if p_val > 0.05 else "FAIL: IMBALANCE DETECTED" if p_val <= 0.05: all_passed = False print(f" {col}: ctrl={ctrl_mean:.3f} trt={trt_mean:.3f} p={p_val:.3f} {status}") return all_passed

Typical columns to check: user age (days since signup), historical purchase rate, device type, geography. If one of these comes back with p<0.05 for a metric that wasn't even being tested, it's worth investigating, and a large imbalance usually means the randomization has a bug somewhere.

One honest caution about reading this check: with a 0.05 threshold, about 1 check in 20 will "fail" by pure chance even when randomization is perfect, that's what α = 0.05 means. Check ten baseline columns and see one marginal failure, and that's roughly what chance predicts. A big imbalance, several failures at once, or the same failure showing up experiment after experiment is a different story, and points to something real in the assignment or the logging.

Always run an A/A test first

Before trusting any new experiment infrastructure, run an A/A test: both groups get the exact same experience. Run the usual statistical test once the target sample size is reached. What should show up, across many A/A tests: p-values spread roughly evenly between 0 and 1, so about 5% of A/A tests come back "significant" purely by chance, and no systematic difference in metrics between the two groups. If A/A tests keep coming back significant, something's actually broken in the randomization or the logging pipeline, not in the world.

Part 6: The peeking problem, the trap that quietly corrupts most experiments

This is one of the most common sources of false positives in real-world A/B testing. Understanding it properly is what separates a rigorous data scientist from a careless one.

What peeking actually is

An experiment is running. The dashboard shows p=0.07. Two days later, p=0.04. It gets called a win and shipped.

This feels completely rational. It's actually statistically disastrous.

Here's why: a p-value comes with a promise, that when there's no real effect it drops below 0.05 only about 5% of the time. That promise holds for one look, at a sample size decided in advance. Every extra time it gets checked, the chance of stumbling into a false positive goes up, even when H₀ is true and there's no real effect anywhere.

The reason is that a p-value isn't a steady reading that settles toward the truth as data arrives. When H₀ is true, it wanders. At any single moment it's about equally likely to be anywhere between 0 and 1, and as new users come in it drifts up and down across that range. Check it once, and it's below 0.05 only 5% of the time. Check it twenty times, and it only has to dip below the line at one of those twenty moments for a peeker to declare a winner.

a peeker stops at 250 per group: p = 0.025 planned end: p = 0.86 below 0.05: "significant" 0 0.25 0.5 0.75 1 0 250 500 750 1000 users per group so far p-value at each check a peeker stops here: p = 0.025 end: p = 0.86 below 0.05: "significant" 0 0.25 0.5 0.75 1 0 500 1000 users per group so far p-value at each check
One simulated experiment where control and treatment are identical, both at a 50% rate, checked every 50 users per group. The p-value wanders, dips below 0.05 at 250 users per group (and grazes it again at 350), then climbs back. A peeker stops at the dip and ships. Waiting for the planned 1,000 users per group gives the honest answer: no difference.

Let's prove it with a simulation

Before the code: 10,000 experiments get simulated where it's already known, by construction, that there's no real difference between control and treatment, both groups get the same underlying 50% rate. Since there's genuinely nothing to find, any experiment that declares a "significant" result is by definition wrong, a false positive. For each of those 10,000 fake experiments, two approaches get tried: check the p-value every 50 users and stop the moment it looks significant (peeking), versus check it exactly once at the end (correct). Then just count how often each approach cries wolf.

Pythonnp.random.seed(42) N_SIMULATIONS = 10_000 false_pos_peeking = 0 false_pos_correct = 0 for _ in range(N_SIMULATIONS): # TRUTH: H0 is true, both groups have identical p=0.50. No real effect anywhere. control = np.random.binomial(1, 0.50, 1000) treatment = np.random.binomial(1, 0.50, 1000) # WRONG: peek every 50 users, stop the moment it looks significant peeked_sig = False for checkpoint in range(50, 1001, 50): c, t = control[:checkpoint], treatment[:checkpoint] p_pool = (c.sum() + t.sum()) / (2 * checkpoint) se = np.sqrt(p_pool * (1-p_pool) * (2/checkpoint)) z = (t.mean() - c.mean()) / se if abs(z) > 1.96: peeked_sig = True break if peeked_sig: false_pos_peeking += 1 # CORRECT: test only once, at the pre-specified n=1000 p_pool = (control.sum() + treatment.sum()) / 2000 se = np.sqrt(p_pool * (1-p_pool) * (2/1000)) z = (treatment.mean() - control.mean()) / se if abs(z) > 1.96: false_pos_correct += 1 print(f"Expected false positive rate at alpha=0.05: 5.00%") print(f"False positives WITH peeking: {false_pos_peeking/N_SIMULATIONS:.2%}") print(f"False positives WITHOUT peeking: {false_pos_correct/N_SIMULATIONS:.2%}")
OutputExpected false positive rate at alpha=0.05: 5.00% False positives WITH peeking: 26.01% False positives WITHOUT peeking: 5.27%

Peeking pushes the false positive rate from 5% up to 26%. Every one of those 10,000 experiments had nothing to find, yet with peeking, more than one in four of them still declared a "significant" difference. On a real team, that's shipping things that don't work, over and over, without ever knowing it. (The 5.27% for the check-once approach is just 5% plus simulation noise: with 10,000 runs, anything from about 4.6% to 5.4% is expected.)

5.27% Check once, at the end the plan 26.01% Check every 50 users, stop at p < 0.05 α = 5% share of 10,000 no-effect experiments declared significant 5.27% Check once, at the end the plan 26.01% Check every 50 users, stop at p < 0.05 α = 5% share of 10,000 no-effect experiments declared significant
Same 10,000 fake experiments, same complete absence of a real effect. Just checking the p-value 20 times and stopping at the first "significant" reading, instead of waiting for the pre-planned sample size, raises the false positive rate from about 5% to about 26%: roughly five times as many false alarms.

Think of flipping a fair coin. Commit to exactly 100 flips and check significance once at the end, and the wrong conclusion of bias happens about 5% of the time. But check after every single flip and stop the moment p dips under 0.05, and the wrong conclusion happens far more often, because any random little run of heads looks significant if the check stops at exactly the right instant.

The fix: decide in advance, then don't look

The discipline here is simple, even if it takes willpower: calculate the required sample size before starting, set a hard end date or user count, don't look at p-values until that threshold is hit, then analyze once and make one decision.

If an organization genuinely needs to monitor an experiment for safety (a guardrail metric tanking, say), sequential testing methods exist for exactly this, the Sequential Probability Ratio Test or alpha-spending functions, specifically built to allow peeking without inflating Type I error. Part 9 sketches how they work. Watching a guardrail for safety is fine on its own, as long as the ship decision isn't quietly being made from a peek at the primary metric.

Part 7: A few more pitfalls worth knowing about

The novelty effect

Show people something new and they engage with it more, not necessarily because it's better, just because it's unfamiliar and interesting. That effect fades.

Say Swiggy launches a new "food mood" discovery feature. Week one, engagement is 40% higher. Two months later, it's 3% higher. If the A/B test only ran for one week, it would have confidently declared a winner that barely existed.

The fix: run long enough for the effect to settle, often at least two weeks and longer for major UI changes, and plot the treatment effect day by day across the test. If it's driven by novelty, the decay will show up on the plot. A genuine improvement holds its lift.

The opposite pattern happens too, sometimes called change aversion: a redesign starts out looking worse because regular users have to relearn where things are, then recovers as they adjust. One useful way to tell these apart is to compare new users, who never saw the old design and so can't find it either novel or annoying, against existing users.

Network effects and SUTVA violations

SUTVA (Stable Unit Treatment Value Assumption) is the quiet assumption every A/B test leans on: the treatment one user experiences shouldn't affect another user's outcome.

This breaks down constantly in social or marketplace products. At Uber, drivers in both groups compete for the same pool of surge requests. If the new screen makes treatment drivers accept more of them, some of those are trips a control driver would otherwise have taken, so control drivers look worse partly because treatment drivers took their trips, and the measured gap exaggerates what would happen if every driver got the new screen. Interference can push the estimate the other way too: more drivers accepting surge trips puts more cars on the road, which can calm surge in an area and change what everyone there gets offered. At Spotify, a treatment user sharing a new playlist feature with a control-group friend contaminates that friend's experience. On a messaging app, basically any feature involving communication between people can't be cleanly isolated at all.

The fix: cluster randomization, assign whole clusters (friend groups, geographic regions, driver pools) to control or treatment, rather than individuals. This keeps the SUTVA assumption intact at the cluster level, even if it doesn't hold perfectly at the individual one. Marketplaces also use switchback designs, which flip a whole city between control and treatment in alternating blocks of time, so everyone in one place at one hour sees the same version. The price of both: there are far fewer clusters (or time blocks) than individual users, so the effective sample size drops, and the analysis has to treat each cluster, not each user, as the unit.

Simpson's paradox

A trend that shows up in every subgroup can flip entirely once those subgroups get combined, because the subgroups make up very different shares of each group.

Pythonimport pandas as pd # New onboarding tested on both Mobile and Desktop users data = { 'Segment': ['Mobile', 'Mobile', 'Desktop', 'Desktop'], 'Group': ['Control', 'Treatment', 'Control', 'Treatment'], 'Users': [9000, 1000, 1000, 9000], 'Retained': [3150, 320, 450, 3420], } df = pd.DataFrame(data) df['Retention'] = df['Retained'] / df['Users'] print(df[['Segment','Group','Retention']].to_string(index=False)) ctrl_total = df[df['Group']=='Control'][['Users','Retained']].sum() trt_total = df[df['Group']=='Treatment'][['Users','Retained']].sum() print(f"\nOverall Control: {ctrl_total['Retained']/ctrl_total['Users']:.2%}") print(f"Overall Treatment: {trt_total['Retained']/trt_total['Users']:.2%}")
OutputSegment Group Retention Mobile Control 0.35 Mobile Treatment 0.32 Desktop Control 0.45 Desktop Treatment 0.38 Overall Control: 36.00% Overall Treatment: 37.40%
35% control 9,000 32% treatment 1,000 Mobile 45% control 1,000 38% treatment 9,000 Desktop 36.0% control 10,000 37.4% treatment 10,000 Overall 30-day retention; numbers under the bars are users in each group 35% cont. 9,000 32% trea. 1,000 Mobile 45% cont. 1,000 38% trea. 9,000 Desktop 36.0% cont. 10,000 37.4% trea. 10,000 Overall 30-day retention; numbers under the bars are users in each group
Treatment loses on mobile (32% vs 35%) and loses on desktop (38% vs 45%), yet wins overall (37.4% vs 36.0%). The numbers under the bars show why: control is 90% mobile users and treatment is 90% desktop users, and desktop users retain better regardless of onboarding. The overall comparison is really comparing device mixes, not onboarding flows.

Both groups have exactly 10,000 users, so a sample ratio check on the totals would pass. But look at the mix inside them: 90% of control is mobile and 90% of treatment is desktop. Fair randomization can't produce that. With 10,000 users per group assigned by a hash, each group's desktop share would land within a percentage point or two of the other's. A 90/10 against 10/90 split means the assignment itself was broken, for example a staged rollout that sent the new onboarding mostly to desktop users, or an assignment rule that accidentally depended on the device. So this example is really a bug that Simpson's paradox dresses up as a win. The right response is to fix the assignment and rerun the experiment, not to celebrate the overall number.

Milder versions of the same imbalance do happen by chance, especially in smaller experiments and in small segments, and that's where the routine fixes come in. Always break results down by the major segments, device type, geography, user tenure, as part of the sanity check, including the share of each group that falls in each segment. If a segment turns out imbalanced, either stratify the randomization (assign within each segment separately, so every segment is split evenly by design) or control for it statistically with regression. And when the segment mix differs between groups, the like-for-like comparisons within each segment are the fair ones, not the combined total.

Multiple metrics and false discovery

Track 20 metrics and call something a winner the moment any one of them dips under p<0.05, and the real overall false positive rate sits around 64%, the same math from Day 12 (that figure assumes none of the 20 metrics truly moved and that they're independent; real metrics are correlated, which changes the exact number but not the lesson). Define the primary metric before the experiment starts. Anything interesting that shows up in a secondary metric is a hypothesis worth testing next time, not evidence already in hand.

Part 8: Solving all five, end to end

Time to run all five experiments start to finish.

Solution 1: Netflix autoplay, two-proportion z-test (two-tailed)

Setup: control 2,080/4,000 (52.0%), treatment 2,440/4,000 (61.0%), next-episode rate.

Pythonp_control, p_treatment, n = 0.52, 0.61, 4000 x_control = int(p_control * n) x_treatment = int(p_treatment * n) print(f"H0: p_treatment = p_control H1: p_treatment != p_control") # pooled SE for the test statistic p_pool = (x_control + x_treatment) / (2 * n) SE = np.sqrt(p_pool * (1 - p_pool) * (1/n + 1/n)) z_stat = (p_treatment - p_control) / SE p_value = 2 * stats.norm.sf(abs(z_stat)) print(f"z = {z_stat:.4f}, p-value = {p_value:.2e}") # unpooled SE for the CI se_ci = np.sqrt(p_control*(1-p_control)/n + p_treatment*(1-p_treatment)/n) diff = p_treatment - p_control print(f"\nAbsolute lift: +{diff*100:.1f}pp, Relative lift: +{diff/p_control:.1%}") print(f"95% CI for lift: [+{(diff-1.96*se_ci)*100:.2f}pp, +{(diff+1.96*se_ci)*100:.2f}pp]")
OutputH0: p_treatment = p_control H1: p_treatment != p_control z = 8.1187, p-value = 4.71e-16 Absolute lift: +9.0pp, Relative lift: +17.3% 95% CI for lift: [+6.84pp, +11.16pp]

Ship it. z=8.12 with a p-value that's essentially zero. The 9-percentage-point lift (52% to 61%) is both statistically and practically significant, and the CI says the true lift is above 6.8pp even in the pessimistic case, which clears the team's 5-point MDE with room to spare. A hypothetical guardrail check on unsubscribe rate and complaints held steady in this scenario. The one open question left is product judgment, not statistics: does a 10-second countdown fit a brand built around user choice and control? That's a call for leadership, not for the p-value.

Solution 2: Uber surge UI, Welch's two-sample t-test

Setup: each driver's own acceptance rate over the test period, simulated for both groups, n=3,500 drivers each. Control rates are drawn around 68% and treatment rates around 74%, with a driver-to-driver spread of about 14.7 points, and every rate is capped between 0% and 100%. Capping trims a little off the top of the treatment group, so the true lift built into this simulation is about 5.9 percentage points. A real analysis would never know that number, but here it lets us check whether the confidence interval catches the truth.

Pythonnp.random.seed(2) n = 3500 ctrl = np.random.normal(loc=0.68, scale=0.147, size=n).clip(0, 1) trt = np.random.normal(loc=0.74, scale=0.146, size=n).clip(0, 1) print(f"H0: mu_control = mu_treatment H1: mu_control != mu_treatment") # Welch's t-test, doesn't assume equal variances t_stat, p_value = stats.ttest_ind(trt, ctrl, equal_var=False) diff = trt.mean() - ctrl.mean() SE = np.sqrt(ctrl.var(ddof=1)/n + trt.var(ddof=1)/n) print(f"Welch's t = {t_stat:.4f}, p-value = {p_value:.2e}") print(f"Absolute lift: +{diff*100:.2f}pp, 95% CI: [+{(diff-1.96*SE)*100:.2f}pp, +{(diff+1.96*SE)*100:.2f}pp]") s_pool = np.sqrt((ctrl.var(ddof=1) + trt.var(ddof=1)) / 2) # equal group sizes cohens_d = diff / s_pool size = ("large" if abs(cohens_d) >= 0.8 else "medium" if abs(cohens_d) >= 0.5 else "small" if abs(cohens_d) >= 0.2 else "negligible") print(f"Cohen's d: {cohens_d:.3f} ({size} effect)") daily_surge_offers = 200_000 # assumed figure, for illustration print(f"\n+{diff*100:.1f}pp x 200,000 daily surge offers = ~{diff*daily_surge_offers:,.0f} extra accepted trips/day")
OutputH0: mu_control = mu_treatment H1: mu_control != mu_treatment Welch's t = 16.6476, p-value = 4.68e-61 Absolute lift: +5.70pp, 95% CI: [+5.03pp, +6.38pp] Cohen's d: 0.398 (small effect) +5.7pp x 200,000 daily surge offers = ~11,407 extra accepted trips/day

Ship it, with one caveat. The lift is 5.7 percentage points, and the CI of roughly 5.0 to 6.4 points comfortably clears the team's 3-point MDE, giving the product team a defensible range to plan around. It also contains the 5.9-point lift that was built into the simulation, which is what a 95% interval should do about 95% of the time. Cohen's d of about 0.40 sits between the small and medium benchmarks, closer to medium, which is large for a pure UI change with no change to driver pay at all.

Quick reminder from Day 12, since the exact numbers are easy to forget: Cohen's d of roughly 0.2 counts as small, 0.5 as medium, 0.8 as large. These are the thresholds the code's if/else chain checks against, which is why it prints "small" for 0.40: the label marks which benchmark has been passed, and 0.40 has passed 0.2 but not yet 0.5. The labels are rough conventions, not laws, and the number itself is more informative than the word.

The caveat is the one from Part 7. With an assumed 200,000 surge offers a day, a 5.7-point lift works out to roughly 11,400 extra accepted trips a day, but only if every extra acceptance is a trip that would otherwise have gone unserved. Drivers in both groups were competing for the same requests, so some of the treatment group's extra trips were trips a control driver would have accepted anyway. At full rollout, the marketplace-wide gain is likely to be smaller than the per-driver comparison suggests. A team that needs that marketplace-wide number would confirm it with a city-level or switchback experiment before counting on it.

Solution 3: Swiggy ML ranking, one-tailed proportion test

Setup: control 3,550/5,000 (71.0%), treatment 3,800/5,000 (76.0%), order completion.

Python# One-tailed: we only care if the new ranking is better p_control, p_treatment, n = 0.71, 0.76, 5000 x_control = int(p_control * n) x_treatment = int(p_treatment * n) print(f"H0: p_treatment <= p_control H1: p_treatment > p_control") p_pool = (x_control + x_treatment) / (2 * n) SE = np.sqrt(p_pool * (1-p_pool) * (2/n)) z_stat = (p_treatment - p_control) / SE p_value = stats.norm.sf(z_stat) # one-tailed print(f"z = {z_stat:.4f}, p-value (one-tailed) = {p_value:.2e}") se_ci = np.sqrt(p_control*(1-p_control)/n + p_treatment*(1-p_treatment)/n) diff = p_treatment - p_control print(f"Absolute lift: +{diff*100:.1f}pp, 95% CI: [+{(diff-1.96*se_ci)*100:.2f}pp, +{(diff+1.96*se_ci)*100:.2f}pp]") print(f"One-sided 95% lower bound (matches the one-tailed test): +{(diff-1.645*se_ci)*100:.2f}pp") daily_sessions = 3_000_000 # assumed figure, for illustration print(f"\n+{diff*100:.0f}pp x 3M daily sessions = ~{diff*daily_sessions:,.0f} extra orders/day")
OutputH0: p_treatment <= p_control H1: p_treatment > p_control z = 5.6647, p-value (one-tailed) = 7.37e-09 Absolute lift: +5.0pp, 95% CI: [+3.27pp, +6.73pp] One-sided 95% lower bound (matches the one-tailed test): +3.55pp +5pp x 3M daily sessions = ~150,000 extra orders/day

Ship it. Five percentage points on order completion is a large lift. If the app sees, say, three million sessions a day (an assumed figure for this illustration), that works out to roughly 150,000 extra orders a day, which would repay the engineering work on personalization many times over, as long as the lift holds after launch and the guardrail, session abandonment, stays flat. The pessimistic end matters too. The one-sided 95% lower bound, about 3.55 points, is the interval that lines up exactly with a one-tailed test (Day 12's quick check explained why), and even that clears the team's 3-point MDE. The one-tailed test is defensible here because the direction was genuinely pre-specified from offline evaluation, and a worse result would have triggered the exact same action (rollback) as no result at all.

Solution 4: Spotify onboarding, two-tailed proportion test

Setup: control 2,280/6,000 (38.0%), treatment 2,580/6,000 (43.0%), 30-day retention.

Pythonp_control, p_treatment, n = 0.38, 0.43, 6000 x_control = int(p_control * n) x_treatment = int(p_treatment * n) print(f"Two-tailed: onboarding changes could help or hurt") p_pool = (x_control + x_treatment) / (2 * n) SE = np.sqrt(p_pool * (1-p_pool) * (2/n)) z_stat = (p_treatment - p_control) / SE p_value = 2 * stats.norm.sf(abs(z_stat)) print(f"z = {z_stat:.4f}, p-value = {p_value:.2e}") diff = p_treatment - p_control se_ci = np.sqrt(p_control*(1-p_control)/n + p_treatment*(1-p_treatment)/n) print(f"Absolute lift: +{diff*100:.0f}pp, Relative lift: +{diff/p_control:.1%}") print(f"95% CI: [+{(diff-1.96*se_ci)*100:.2f}pp, +{(diff+1.96*se_ci)*100:.2f}pp]") # Revenue impact for one month's new-user cohort (all three inputs are assumed figures) monthly_new_users = 5_000_000 extra_retained = diff * monthly_new_users premium_conversion = 0.12 # share of retained users who go Premium avg_revenue_per_premium = 9.99 # monthly price, in dollars print(f"\nExtra retained users: {extra_retained:,.0f}") print(f"Extra Premium conversions: {extra_retained*premium_conversion:,.0f}") print(f"Monthly revenue impact: ${extra_retained*premium_conversion*avg_revenue_per_premium:,.0f}")
OutputTwo-tailed: onboarding changes could help or hurt z = 5.5788, p-value = 2.42e-08 Absolute lift: +5pp, Relative lift: +13.2% 95% CI: [+3.25pp, +6.75pp] Extra retained users: 250,000 Extra Premium conversions: 30,000 Monthly revenue impact: $299,700

Ship it. Five percentage points of 30-day retention is a 13.2% relative lift. Under the assumed figures in the code (5 million new users a month, 12% of retained users going Premium, $9.99 a month), that's roughly $300K in extra monthly recurring revenue from just one month's cohort, and the gain builds up as each new month's cohort goes through the better onboarding. Treat that as rough sizing, not a forecast: it assumes the extra retained users go Premium at the same rate as everyone else, which is worth checking in the data. One more honest detail: the CI's lower end, 3.25 points, sits a little below the 4-point MDE, so the data can't quite rule out a lift slightly smaller than the team's bar. The lift is still clearly positive, and the best estimate, 5 points, is above the bar. The two-tailed test was the right call here too, an unfamiliar interactive onboarding flow could plausibly have confused new users and hurt retention, and this test design would have caught that just as readily as it caught the improvement.

Solution 5: Google search layout, statistical vs. practical significance at real scale

Setup: control 2,480/80,000 (3.1%), treatment 2,880/80,000 (3.6%), card CTR on each user's first impression.

Pythonp_control, p_treatment, n = 0.031, 0.036, 80_000 x_control = int(p_control * n) x_treatment = int(p_treatment * n) p_pool = (x_control + x_treatment) / (2 * n) SE = np.sqrt(p_pool * (1-p_pool) * (2/n)) z_stat = (p_treatment - p_control) / SE p_value = 2 * stats.norm.sf(abs(z_stat)) print(f"z = {z_stat:.4f}, p-value = {p_value:.2e}") diff = p_treatment - p_control se_ci = np.sqrt(p_control*(1-p_control)/n + p_treatment*(1-p_treatment)/n) print(f"Absolute lift: +{diff*100:.1f}pp, Relative lift: +{diff/p_control:.1%}") print(f"95% CI: [+{(diff-1.96*se_ci)*100:.3f}pp, +{(diff+1.96*se_ci)*100:.3f}pp]") # Cohen's h: the effect size measure built for proportions h = 2 * (np.arcsin(np.sqrt(p_treatment)) - np.arcsin(np.sqrt(p_control))) size = ("large" if abs(h) >= 0.8 else "medium" if abs(h) >= 0.5 else "small" if abs(h) >= 0.2 else "below the 0.2 'small' benchmark") print(f"Cohen's h: {h:.4f} ({size})") # How likely was a test this size to catch the 0.1pp lift the team said matters? se_null = np.sqrt(2 * p_control * (1 - p_control) / n) power_01 = stats.norm.sf(1.96 - 0.001 / se_null) print(f"Power to detect +0.1pp with {n:,} per group: {power_01:.0%}") daily_impressions = 1_000_000_000 # assumed figure, for illustration daily_extra_clicks = daily_impressions * diff print(f"\n+{diff*100:.1f}pp CTR x {daily_impressions/1e9:.0f}B daily card impressions") print(f"= {daily_extra_clicks/1e6:.0f} million extra clicks per day") print(f"= {daily_extra_clicks*365/1e9:.1f} billion extra clicks per year")
Outputz = 5.5575, p-value = 2.74e-08 Absolute lift: +0.5pp, Relative lift: +16.1% 95% CI: [+0.324pp, +0.676pp] Cohen's h: 0.0278 (below the 0.2 'small' benchmark) Power to detect +0.1pp with 80,000 per group: 21% +0.5pp CTR x 1B daily card impressions = 5 million extra clicks per day = 1.8 billion extra clicks per year

Cohen's h is used here instead of Cohen's d, and that's not a typo, it's the effect size measure Jacob Cohen designed specifically for comparing two proportions. The reason is that a proportion's spread depends on where it sits. A yes/no outcome with rate p has a standard deviation of √(p(1−p)): that's 0.50 at a 50% rate, but only about 0.17 at 3%. So the same 0.5-point gap means different things in different places. Near 50%, it's a small nudge relative to how noisy the outcome is. Near 3%, the outcome is far less noisy, and the same gap is a bigger shift relative to that noise, and also a much bigger relative change (3.1% to 3.6% is a 16% jump, while 50% to 50.5% is a 1% jump).

h = 2 arcsin(√p₂) − 2 arcsin(√p₁)
The arcsine-square-root transform stretches the scale near 0% and 100%, where proportions are less noisy, and squeezes it near 50%, so that equal distances in h mean roughly equal amounts of signal wherever the baseline sits.

Statisticians call this a variance-stabilizing transformation: after it, a proportion's sampling noise is about the same everywhere on the scale. For small gaps, h comes out very close to the gap divided by the standard deviation at the average rate, here 0.005 / √(0.0335 × 0.9665) ≈ 0.028, matching the code. The difference is that h stays well behaved for large gaps and near 0% and 100%, where that simple ratio breaks down. The same small/medium/large benchmarks (0.2/0.5/0.8) apply, on this transformed scale.

Ship it, after checking the guardrails. This is the statistical-versus-practical-significance lesson running in reverse. Cohen's h=0.028 is well below even the 0.2 "small" benchmark, tiny by any conventional yardstick. But at an assumed billion card impressions a day, a 0.5pp lift works out to about 5 million extra clicks daily, or somewhere around 1.8 billion a year, if the lift measured on first impressions holds across all of them. An effect size means nothing on its own, it only means something once the scale it applies to is known. The guardrails still need a look before shipping: a card that gains clicks by stealing them from the result above it, or by drawing accidental taps, hasn't actually helped anyone.

The power check in the code is the other lesson, and it closes the loop from Part 4. This experiment had only about a 21% chance of catching the 0.1pp lift the team said it cared about. It got away with being too small because the real lift turned out five times bigger than that. Had the true lift been 0.1pp, the most likely outcome would have been a "not significant" result and a genuinely valuable change wrongly shelved. A non-significant result from an underpowered test isn't evidence that nothing happened, it's evidence that the test couldn't see.

Part 9: Beyond basic A/B testing

Multi-armed bandits

Classical A/B testing treats the whole thing as pure learning, accepting some cost during the experiment in exchange for knowledge, then acting only once it's over. A multi-armed bandit instead shifts traffic toward whichever variant is currently winning while the experiment is still running, cutting down that cost.

Picture a casino with three slot machines. Classical A/B testing says: play each one the same number of times, then pick the best. A bandit says: pull each one a few times, then start playing the best-performing one more and more, adjusting continuously.

Bandits earn their keep when the experiment is long-running and leaving traffic on the losing variant isn't affordable, when the effect is large and detectable quickly, or when personalizing and different users might have genuinely different "best" variants. The trade-off is real though: bandits sacrifice some statistical power and are harder to reason about than a clean A/B test. For major product decisions, a fixed-sample A/B test is still the gold standard.

Sequential testing

Sequential testing allows looking at the data as it accumulates and stopping the moment there's enough evidence, without inflating Type I error. The oldest version is Abraham Wald's Sequential Probability Ratio Test (SPRT), from the 1940s. A version that's common in practice today is the group sequential test: decide in advance roughly how many looks there will be, and give each look a stricter significance threshold than 0.05, so that across all the looks combined the false positive rate stays at 5%. Early looks get very strict thresholds, so only an overwhelming result can stop the test early, and later looks get closer to the usual one. The rule for spending that 5% budget across the looks is called an alpha-spending function. This is the actual, formal fix for the peeking problem: checking as often as planned becomes fine, because the stopping rule is built directly into the statistical test itself, not bolted on afterward.

Real case: how Spotify handles peeking

In 2023, Spotify's experimentation team published a comparison of sequential testing methods on its engineering blog, and explained that Spotify's Experimentation Platform uses group sequential tests, with the alpha-spending approach proposed by Lan and DeMets in 1983. The post makes the peeking point with numbers too: in one of its examples, repeatedly checking a standard z-test that was designed for a 5% false positive rate gives a true false positive rate closer to 10%, and it keeps growing as the checks continue. That fits the simulation in Part 6, which checked 20 times and reached 26%. How much damage peeking does depends on how many times you look, but it's never zero.

Quick reference

A/B testing, quick reference

Before the experiment: define one primary metric that decides ship/no-ship. Define guardrail metrics that must not degrade. State H₀ and H₁, choose one- or two-tailed. Set α=0.05, target power=80%. Decide the MDE, the minimum lift actually worth caring about. Calculate the required n per group. Determine experiment duration, minimum 1 to 2 weeks.

During the experiment: hash-based random assignment, so the same user always gets the same variant. Do not peek at p-values. Monitor guardrail metrics for safety only.

After the experiment: sanity checks first, do the group sizes match the planned split (the SRM check), and are baseline metrics balanced across groups? Run the correct test (proportion z or Welch's t). Report p-value, effect size, 95% CI, and absolute lift together. Segment the analysis (device, region, user tenure). Check guardrail metrics. Make one decision: ship, no-ship, or iterate.

Common traps: peeking and stopping early (false positives jump from 5% to 26%). Changing the primary metric after seeing results (p-hacking). Ignoring the novelty effect (first-week enthusiasm). Individual randomization in social or marketplace products (SUTVA violations). Running 20 metrics at α=0.05 (a 64% chance of at least one false positive). Large n making tiny, meaningless lifts "significant." Sizing the test from the hoped-for lift instead of the MDE. Ignoring a sample ratio mismatch instead of debugging it. Before-after comparisons instead of a parallel control group.

The big things to remember

A/B testing is hypothesis testing with a control group. The random split is what actually makes causal inference possible, without it it's just correlation analysis wearing an experiment's clothes. The most important work happens before the experiment starts, defining the primary metric and computing the required sample size in advance is what separates a rigorous experiment from a fishing expedition. MDE drives everything, sample size scales with the inverse square of the effect being chased, so halving the MDE roughly quadruples the data needed, and how much traffic is actually available quietly decides which experiments are even possible. Peeking destroys experiments, the simulation showed the false positive rate jumping from 5% to 26%, fix the sample size, set the end date, and don't look until it's actually done. Statistical significance alone isn't enough, Google's 0.5pp CTR lift had a tiny effect size and an enormous business impact, the p-value says the effect is unlikely to be noise, effect size and scale say whether it matters. Guardrails stop a battle win from becoming a war loss, autoplay could raise next-episode rates while quietly raising unsubscribes too. And sanity checks come before analysis, always, verify that the group sizes match the planned split and that randomization actually produced balanced groups on pre-experiment metrics, since groups that differ going in make anything found coming out confounded.

Closing the loop

Thirteen days ago, this series opened with a simple question: how does a data scientist think about numbers? Everything since has built toward this exact article. Descriptive statistics gave the vocabulary. Probability and distributions gave the machinery. The Central Limit Theorem made confidence intervals possible. Hypothesis testing turned those intervals into decisions. And A/B testing is where all of it lands: the actual process a real company runs, this week, to decide whether to ship something.

Look back at how much of this article rests on earlier days. The sample size formula is Day 12's power, turned around to ask how much data a test needs. The peeking simulation is Day 12's multiple testing problem in slow motion, the same experiment tested twenty times. The confidence intervals around every lift are Day 11's, and the normal curve underneath all of them is Day 10's, made usable by the Central Limit Theorem.

The formulas were never really the point. The point was always this: a sample can't be trusted blindly, and it can't be dismissed blindly either. Somewhere in between sits an honest, quantified answer, and now there's a full toolkit for finding it.

Quick check

Interview-style questions on A/B testing, the kind that come up in data science interviews. The answers are one click away.

What is the Minimum Detectable Effect, and how do you decide what it should be?

The MDE is the smallest effect that would be practically meaningful enough to actually ship the change. It's a business decision, not a statistical one, set before computing a sample size, not after. Three things shape it. Cost: a feature needing six months of engineering demands a real lift to justify it, maybe MDE=5pp, while a one-day CSS change might be worth shipping for 0.5pp. Risk: changes to core experience like onboarding or payment need a meaningful MDE, since even a small negative effect there is a real risk, while a low-risk backend change can tolerate a smaller MDE. Scale: at Google's volume, even a 0.1pp CTR MDE is worth chasing, while at a startup with 10K daily users, a 0.1pp lift is both too small to measure reliably and too small to care about. The practical move: get the PM, the engineering lead, and the data scientist to agree on the MDE before anyone writes the sample size formula, that conversation also quietly forces everyone to agree on what "success" actually means.

A test comes back p=0.03. A PM says "great, we're done, ship it." What do you check first?

Six things, roughly in this order. Did the primary metric actually pass, or was this a secondary metric? A secondary metric coming in significant is a hypothesis worth testing next time, not a ship signal today. What's the effect size and absolute lift? p=0.03 says the effect is probably not just noise, not that it matters: a 0.1pp lift on a 12% baseline lands at about p=0.03 with a million users per group, and may well not be worth shipping. Are the guardrails intact? A 2pp conversion lift alongside a 1pp jump in unsubscribes could easily be a net negative. Did the test actually reach its planned sample size, and do the group sizes match the planned split? If it was stopped early, the result might just be a peeking artifact, and if the split is off, the comparison itself can't be trusted. Any segment imbalance hiding underneath, an overall lift masking real harm to a specific segment, exactly the Simpson's paradox risk? And could this be novelty? If it's week one of a major UI change, wait for week two before trusting the number.

What's the difference between the randomization unit and the analysis unit, and why does mismatching them cause problems?

The randomization unit is what actually gets assigned (user, session, device). The analysis unit is what gets measured and compared (a click, an order, a conversion event). When they don't match, pseudo-replication shows up, multiple correlated measurements from the same unit get counted as if they were independent observations. That violates the independence assumption baked into the test, understates the real variance, inflates the test statistic, and produces false positives. Randomizing by user but measuring CTR by click event means a user who searches 50 times contributes 50 "observations," but they're not independent, they all come from one person with consistent behavior. The standard error ends up too small, the test statistic too large, and the p-value looks far more confident than it should. The fix: aggregate up to the randomization unit before testing. If randomized by user, compute each user's own CTR first and compare those user-level averages across groups. n becomes the number of users, not the number of clicks. (Larger platforms often keep the click-level data and use a technique called the delta method to compute a correct standard error for the ratio instead, which gives the same protection.) The reverse mismatch causes trouble too: randomize each search separately but report a per-user metric, and the same person ends up in both groups.

What's the difference between pooled and unpooled standard error in a proportion test, and when do you use each?

Both show up in A/B tests for proportions, and which one to use is a principled choice, not a stylistic one.

SEpooled = √(p(1−p)(1/n₁ + 1/n₂)),   p = (x₁+x₂)/(n₁+n₂)
Use inside the hypothesis test, since H₀ assumes both groups share one true rate.
SEunpooled = √(p̂₁(1−p̂₁)/n₁ + p̂₂(1−p̂₂)/n₂)
Use inside the confidence interval, since no shared rate is being assumed there, just an estimate of the true difference.

This is the same distinction Day 12 made for single-proportion tests, where p₀ was used inside the test but p̂ inside the CI. Using pooled SE for a CI, or unpooled SE for a test statistic, is technically wrong either way, the results only drift a little for large n, but using the right one for each calculation is exactly the kind of precision that separates careful work from sloppy work.

An A/B test runs two weeks and shows a strong, significant result. A PM wants to extend it to four weeks "just to be safe." What's the response?

Extending an experiment after seeing a significant result is the same kind of mistake as stopping early, it's p-hacking wearing a different outfit. If the extension is hoping to "confirm" a significant result with more data, that's now a second, informal test with stopping rules that were never actually pre-specified, and the Type I error rate is no longer under control at α. If instead the extension happens because the result was not significant and more data is hoped to get there, that's textbook p-hacking, fishing until the number finally cooperates. The right answer: fix the duration and sample size before the experiment begins. Follow that discipline, and the result at the pre-specified endpoint is valid on its own, no extension required. The one legitimate reason to extend: "the target sample size hasn't been hit yet because traffic came in lower than expected." That's not fishing for significance, that's just finishing what was planned. And if the real worry is a novelty effect, that's a fair concern, but it belongs in the plan from the start (a longer pre-registered duration, or a holdout group after launch), not in an unplanned extension.

Two experiments are running at the same time on overlapping users. What risks does that create?

Two real risks, and one that's mostly a myth. Interaction effects: if experiment A changes the homepage and experiment B changes checkout, users exposed to both might behave differently than users exposed to just one, or neither. What gets measured for each experiment is then an average of its effect with and without the other change, which can be misleading if the change ends up shipping in a world where the other one has shipped too. Conflicting changes: if A and B both modify the same button or the same page element, users who land in both treatments can get a broken or confusing experience. The myth: without an interaction, overlapping experiments don't bias each other. Because each experiment is randomized independently (the experiment name is in the hash), B's treatment users end up spread evenly across A's control and treatment, so B adds the same noise to both of A's groups and cancels out of A's comparison. Mitigations, roughly cheapest to most robust: traffic isolation, give each concurrent experiment its own non-overlapping slice of users, clean but wasteful with limited traffic. Factorial design, explicitly assign users to one of four cells, (A_ctrl, B_ctrl), (A_trt, B_ctrl), (A_ctrl, B_trt), (A_trt, B_trt), then analyze with a regression that includes an interaction term (a logistic regression for a yes/no metric; the idea is the same as a two-way ANOVA), running one experiment with four groups instead of two separate 50/50 experiments, which reveals not just what A does and what B does, but whether having both at once produces something different from just adding their effects together. Sequencing, just run the experiments one after another, cleaner but slower. Companies running thousands of simultaneous experiments build dedicated infrastructure for this. Google described its version in a 2010 paper at the KDD conference, "Overlapping Experiment Infrastructure: More, Better, Faster Experimentation," by Diane Tang and colleagues. Experiments are grouped into layers: experiments in the same layer never share users, so changes that could conflict (two tweaks to the same element) go in the same layer, while experiments in different layers overlap freely on the same traffic. That design is what let Google run many more experiments at once without running out of users. Smaller organizations often apply the same idea by hand: keep experiments that touch the same part of the product in separate slices of traffic, and let unrelated experiments overlap.

A feature wins its A/B test but shows no improvement after launch. What could explain that?

A handful of explanations, each pointing at a different failure mode. Novelty decayed, the test captured a week or two of peak newness, and the lift quietly evaporated once things stopped feeling new. The test population wasn't representative: if the test ran only in one country, on one platform, or only on new users, the rest of the user base can react differently once the change rolls out to everyone. (A random 5% of all users is representative; a hand-picked 5% often isn't.) The metric wasn't the real goal, optimizing for click rate when the actual business goal was revenue per session, and the two can move in opposite directions. Network effects weren't captured, in a marketplace, scaling a change up alters market dynamics (more demand, fewer available drivers, longer waits) in ways a small test could never have shown. Or it was a false positive all along: among experiments where the change truly does nothing, about one in twenty will still declare a "significant" result at α=0.05, and since only a minority of ideas work at all (10% to 20% at Google and Bing, from the real case earlier), false positives can make up a noticeable share of all "winners." Even real winners tend to look bigger in the test than they turn out to be. Across many experiments, the results that only just cleared the significance bar are disproportionately ones where noise happened to push the estimate up, so the effect after launch is often smaller, a pattern sometimes called the winner's curse. The lesson: A/B tests are necessary, but not sufficient on their own. Keep monitoring after launch, and where it matters, keep a small holdout group on the old experience for weeks or months, so the long-run effect is measured against a real control group rather than a before-after comparison.

How do you size an experiment when the baseline rate is very low, like a 0.5% payment failure rate?

The formula doesn't change, but rare-event metrics need enormous samples, exactly why they tend to make poor primary metrics for A/B tests. Sizing a test to detect a move from 0.5% to 0.4% failure needs roughly 70,000 per group (the formula from Part 4 gives 70,321, two-tailed at 80% power), even though the change itself is a 20% relative reduction. A few ways around this when a rare metric is genuinely unavoidable: find a proxy metric that's more frequent and correlates with the rare one ("payment retry attempted" might stand in for "payment failed"). Use a ratio metric measured within a smaller, high-volume segment where the failures actually concentrate. Increase traffic allocation, putting 50% of all traffic into the experiment instead of 10% gets 5× the sample in the same calendar time. Or just accept a longer runtime, sometimes the honest answer really is that detecting a meaningful change in a rare event takes more time, full stop.

What is a guardrail metric, and can it ever be intentionally overridden?

A guardrail metric is one that must not get worse during an experiment, no matter how well the primary metric performs. It's the floor a team won't ship below, regardless of the headline result. Netflix's primary metric might be next-episode click rate, with unsubscribe rate as the guardrail. A feature that doubles next-episode clicks while also raising unsubscribes by 50% isn't a win, it's extraction. Can a guardrail ever be knowingly crossed? Yes, but only as an explicit, documented leadership decision, never as an analyst's unilateral call. Legitimate cases exist: the degradation is small and sits inside a pre-agreed tolerance band, the primary gain is large enough to clearly justify the trade, or the degradation is expected to be temporary, a learning-curve effect during a new onboarding flow, say. In these cases, the data scientist's job is to lay the trade-off out plainly, primary improved by X, guardrail degraded by Y, and let the product and leadership team make the ship or no-ship call with full information in front of them. Deciding on one's own that a guardrail breach is "fine" is never the analyst's decision to make.

That's the series. Back to the start, Day 1 The Foundation

Thirteen days, from why one salary out of ten can make an "average" lie, to running an experiment a company can trust. Day 1 is where the two branches of statistics, descriptive and inferential, first came up, and it reads differently once you know where they lead.