The one-line mental model
An A/B test is a randomized experiment: assign units to variants, measure a pre-registered metric, and use a hypothesis test plus a confidence interval to decide whether the observed lift is real â not a fluctuation of who happened to land in each group.
You will be able to:
- State a null hypothesis and run a two-proportion z-test or Welch t-test
- Compute required sample size from baseline, minimum detectable effect, alpha, and power
- Interpret p-values and confidence intervals without common fallacies
- Diagnose peeking, multiple-comparison, novelty, and Simpson's-paradox failures
- Decide when a multi-armed bandit is a better fit than a fixed-split test
Prerequisites
- !Probability distributions and sampling
- !Hypothesis testing basics
- !Mean, variance, and standard error
What You'll Learn
- 1Translate a product question into a testable hypothesis and metric
- 2Size an experiment before launching it
- 3Run a proportion or continuous-metric significance test in Python
- 4Build a guardrail against peeking and segment-level reversals
From product idea to falsifiable hypothesis
Most "let's A/B test it" requests are not hypotheses. A hypothesis names the population, the intervention, the metric, and the direction: "Among new visitors on mobile, replacing the red CTA with green will increase checkout start rate by at least 5% relative." That sentence forces you to fix the unit of analysis (visitor), the randomization unit (visitor, not pageview), the metric (checkout start rate), and the minimum detectable effect (5% relative lift). Without the last piece you cannot size the test, and without a fixed duration you will be tempted to peek.
Control is the current experience; treatment is the change. Random assignment is what makes the groups exchangeable at launch â after that, any systematic difference in the outcome is attributable to the treatment under the SUTVA assumption that one user's variant does not influence another's outcome. When that assumption fails (social features, marketplace interference), the causal claim weakens and you should design cluster randomization instead.
| Term | Meaning in practice |
|---|---|
| Control (A) | The baseline experience you ship against |
| Treatment (B) | The variant whose effect you are measuring |
| Unit of analysis | The entity a metric is computed on (user, session) |
| Alpha (Îą) | False-positive rate, conventionally 0.05 |
| Power (1 â β) | Probability of detecting a true effect, conventionally 0.80 |
| MDE | Minimum detectable effect you care about |
| Guardrail metric | A metric that must not regress (latency, refunds) |
The math behind the two-proportion z-test
For conversion metrics you compare two proportions. The null hypothesis is that the true rates are equal; the test statistic pools the sample proportions to estimate a common standard error.
Here the pooled proportion combines successes from both arms. For continuous metrics such as revenue per user, Welch's t-test is the default because it does not assume equal variances â and variances in control and treatment frequently differ once a UI change alters the distribution shape.
Sizing the experiment before you launch
Underpowered tests waste calendar time and still produce noisy winners. The sample size formula for proportions falls out of the desired z-scores for alpha and power and the expected rates in each arm.
import numpy as np
from scipy import stats
def sample_size_proportions(p_control, mde_relative, alpha=0.05, power=0.80):
p_treatment = p_control * (1 + mde_relative)
z_alpha = stats.norm.ppf(1 - alpha / 2)
z_beta = stats.norm.ppf(power)
n = (z_alpha + z_beta) ** 2 * (
p_control * (1 - p_control) + p_treatment * (1 - p_treatment)
) / (p_treatment - p_control) ** 2
return int(np.ceil(n))
def sample_size_continuous(std_dev, mde_absolute, alpha=0.05, power=0.80):
z_alpha = stats.norm.ppf(1 - alpha / 2)
z_beta = stats.norm.ppf(power)
return int(np.ceil(2 * (z_alpha + z_beta) ** 2 * std_dev ** 2 / mde_absolute ** 2))
# 10% baseline conversion, want to detect a 10% relative lift (to 11%)
n_per_arm = sample_size_proportions(0.10, 0.10)
total = n_per_arm * 2
print(f"Per arm: {n_per_arm:,} | Total: {total:,}")
print(f"Duration at 2,000 eligible visitors/day: {total / 2000:.1f} days")
Run this calculation during design review, not after the test has been live for a week. If the required duration is longer than the product cycle allows, either accept a larger MDE, expand the eligible audience, or reconsider whether the change is worth testing at all.
Running the test and reporting it properly
A complete analysis reports the lift, the p-value, and a confidence interval for the difference â the interval tells stakeholders both whether zero is excluded and how large the plausible effect is.
import numpy as np
import pandas as pd
from scipy import stats
def ab_test_proportions(control, treatment, alpha=0.05):
n_c, n_t = len(control), len(treatment)
p_c, p_t = control.mean(), treatment.mean()
p_pool = (control.sum() + treatment.sum()) / (n_c + n_t)
se_pool = np.sqrt(p_pool * (1 - p_pool) * (1 / n_c + 1 / n_t))
z = (p_t - p_c) / se_pool
p_value = 2 * (1 - stats.norm.cdf(abs(z)))
se_diff = np.sqrt(p_c * (1 - p_c) / n_c + p_t * (1 - p_t) / n_t)
z_crit = stats.norm.ppf(1 - alpha / 2)
ci = (p_t - p_c - z_crit * se_diff, p_t - p_c + z_crit * se_diff)
return {
"control_rate": p_c, "treatment_rate": p_t,
"relative_lift": (p_t - p_c) / p_c,
"p_value": p_value, "ci_95": ci, "significant": p_value < alpha,
}
rng = np.random.default_rng(42)
control = rng.binomial(1, 0.10, 15000)
treatment = rng.binomial(1, 0.112, 15000)
print(ab_test_proportions(control, treatment))
| Reported item | Why it matters |
|---|---|
| Absolute and relative lift | Absolute drives accounting; relative drives road-map debates |
| 95% confidence interval | Shows the range of effects still consistent with the data |
| P-value | Evidence against the null â never the probability the variant "wins" |
| Sample sizes per arm | Lets reviewers judge power after the fact |
| Duration and dates | Exposes novelty windows and weekday cycles |
Pitfalls that silently invalidate results
Peeking is the most expensive mistake in industry experimentation. Checking a fixed-horizon test daily and stopping when p crosses 0.05 inflates the false-positive rate from 5% to 30% or more, because each look is an additional chance to cross the line on noise. Remedies: commit to the pre-computed sample size, use group-sequential boundaries, or switch to an always-valid p-value framework.
Multiple comparisons compound the same problem. Testing five primary metrics at Îą = 0.05 yields a family-wise error rate of about 23%. Pre-register one primary metric, apply Holm or Benjamini-Hochberg correction to secondaries, and treat everything else as exploratory.
Novelty and primacy effects inflate or deflate the first days of a redesign as users react to change rather than to its lasting value. Run at least one full business cycle â typically 14 days â and plot the daily lift to confirm stability.
Simpson's paradox reverses conclusions when aggregate and segment-level results disagree, usually because traffic mix differs across arms by device or geography. Always slice the result by the segments you randomize on and by major covariates before shipping.
â ī¸Pre-registration is cheap insurance
When a bandit beats a fixed split
Multi-armed bandits adapt allocation toward the better-performing arm as evidence accumulates, trading statistical purity for lower opportunity cost during the experiment. Thompson sampling and epsilon-greedy strategies are the two most common; both sacrifice the clean fixed-horizon inference of a classical test in exchange for faster learning. They are the right tool when the cost of showing users a worse variant during the learning phase is high â a homepage hero, a pricing page â and the wrong tool when you need a publishable p-value at a fixed sample size.
For most product experiments, the fixed split remains the default: it is easier to explain to stakeholders, simpler to analyze, and its sample size can be computed before launch. Reserve bandits for high-stakes, long-running surfaces where the opportunity cost of exploration is a measurable revenue or engagement loss. Hybrid designs â a short fixed-ramp bandit phase followed by a classical test on the winning arm â are increasingly common and worth understanding as a middle ground.
A fixed A/B test gives you clean causal inference but pays exploration cost across the whole duration. A multi-armed bandit adapts traffic toward the better arm as evidence accumulates, reducing regret â at the price of a less straightforward causal estimate. Thompson sampling maintains a Beta posterior per arm, samples from each, and picks the argmax; it is a strong default because it balances exploration and exploitation without tuning an epsilon.
class ThompsonBandit:
def __init__(self, n_arms):
self.alpha = np.ones(n_arms)
self.beta = np.ones(n_arms)
def select(self):
return int(np.argmax(np.random.beta(self.alpha, self.beta)))
def update(self, arm, reward):
if reward >= 1:
self.alpha[arm] += 1
else:
self.beta[arm] += 1
def simulate(bandit, true_rates, n_rounds=20000):
rng = np.random.default_rng(7)
rewards = 0
for _ in range(n_rounds):
a = bandit.select()
r = int(rng.random() < true_rates[a])
bandit.update(a, r)
rewards += r
return rewards
bandit = ThompsonBandit(3)
total = simulate(bandit, [0.10, 0.12, 0.09])
print(f"Total conversions: {total}, posteriors: {bandit.alpha / (bandit.alpha + bandit.beta)}")
Use bandits for low-stakes optimization such as notification copy. Use fixed tests when a regulator, an executive review, or a public write-up needs a defensible causal number.