Plan, run and analyse A/B tests that hold up: power analysis, z-tests and Welch's t-test, the peeking problem, alpha spending, multiple comparisons, CUPED, SRM checks, bootstrapped revenue, and deterministic variant assignment in Django.
An A/B test is a small randomised experiment, and most of the ways it goes wrong are statistical rather than technical: too little traffic, stopping when the dashboard turns green, testing twenty metrics and reporting the one that moved, or a broken randomiser nobody checked. This tutorial covers the inference a product team needs to run experiments that hold up, with simulations that show why each rule exists, and ends with a Django implementation of deterministic variant assignment.
The examples use Python 3.13 with NumPy 2.5.5, SciPy 1.18.1 and statsmodels 0.15.0, the latest stable releases at the time of writing; the Django code targets Django 5.2 LTS and was also tested on Django 6.1.4. Any Python 3.12+ works. Analysis blocks build on each other; run them in one session.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "numpy>=2.5,<3.0" "scipy>=1.18,<2.0" "statsmodels>=0.15,<0.16" "Django>=5.2,<6.0"
Write the analysis plan before launch:
For conversion rates, statsmodels works with Cohen's h, an arcsine-transformed difference between proportions. With a 10% baseline and an MDE of one percentage point:
import numpy as np
from statsmodels.stats.power import NormalIndPower, TTestIndPower
from statsmodels.stats.proportion import proportion_effectsize
baseline, target = 0.10, 0.11 # 10% conversion, +1 point absolute (10% relative)
h = proportion_effectsize(target, baseline) # Cohen's h
n = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8, ratio=1.0,
alternative="two-sided")
print(f"Cohen's h = {h:.4f}; users per arm = {np.ceil(n):,.0f}")
for mde in [0.005, 0.01, 0.02]:
h = proportion_effectsize(baseline + mde, baseline)
n = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8)
print(f"MDE {mde:.3f}: {np.ceil(n):>9,.0f} per arm")
# continuous metric
d = 0.5 / 20.0 # detect +0.5 on a metric with sd 20
n = TTestIndPower().solve_power(effect_size=d, alpha=0.05, power=0.8)
print(f"continuous metric: {np.ceil(n):,.0f} per arm")
# achieved power with a fixed traffic budget
pw = NormalIndPower().power(effect_size=proportion_effectsize(0.11, 0.10), nobs1=5000, alpha=0.05)
print(f"power with 5,000 per arm: {pw:.2f}")
Cohen's h = 0.0326; users per arm = 14,745
MDE 0.005: 57,756 per arm
MDE 0.010: 14,745 per arm
MDE 0.020: 3,835 per arm
continuous metric: 25,118 per arm
power with 5,000 per arm: 0.37
Sample size scales with the inverse square of the effect: halving the MDE roughly quadruples the traffic. At 37% power, the honest options are to run longer, accept a larger MDE, reduce variance (see CUPED) or skip the test. An underpowered test that does reach significance tends to exaggerate the effect, because only the lucky overestimates cross the threshold.
For a binary metric with thousands of users per arm, the two-proportion z-test is the standard tool. Always report the confidence interval for the difference alongside the p-value. The simulated variant below has a true lift of 0.8 points, slightly below the planned MDE.
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
rng = np.random.default_rng(7)
n_a, n_b = 15_000, 15_000
conv_a = rng.binomial(1, 0.100, n_a)
conv_b = rng.binomial(1, 0.108, n_b)
count = np.array([conv_b.sum(), conv_a.sum()])
nobs = np.array([n_b, n_a])
z, p = proportions_ztest(count, nobs)
lo, hi = confint_proportions_2indep(count[0], nobs[0], count[1], nobs[1], compare="diff", method="wald")
print(f"A={conv_a.mean():.4f} B={conv_b.mean():.4f} diff={conv_b.mean()-conv_a.mean():+.4f}")
print(f"z={z:.2f} p={p:.4f} 95% CI for B-A: [{lo:+.4f}, {hi:+.4f}]")
A=0.1035 B=0.1095 diff=+0.0060
z=1.68 p=0.0921 95% CI for B-A: [-0.0010, +0.0130]
The result is not significant at 0.05, yet the variant really is better. The interval explains why the test cannot tell: it runs from a 0.1-point loss to a 1.3-point gain. "Not significant" means the data are compatible with no effect; it does not show that the effect is zero. If a 1.3-point gain would matter, the correct conclusion is "inconclusive", not "no difference".
For means of continuous metrics (time on page, items per order) use Welch's t-test, which does not assume equal variances in both arms. The pooled Student version gives wrong error rates when variances and arm sizes differ, while Welch loses almost nothing when they are equal. With samples in the thousands, the central limit theorem covers skewed data.
from scipy import stats
t_a = rng.gamma(shape=2.0, scale=60, size=4000) # seconds on page, skewed
t_b = rng.gamma(shape=2.2, scale=57, size=3800)
res = stats.ttest_ind(t_b, t_a, equal_var=False)
ci = res.confidence_interval(0.95)
print(f"mean A={t_a.mean():.1f}s B={t_b.mean():.1f}s diff={t_b.mean()-t_a.mean():+.1f}s")
print(f"Welch t={res.statistic:.2f} df={res.df:.0f} p={res.pvalue:.4f} CI [{ci.low:+.1f}, {ci.high:+.1f}]")
mean A=118.4s B=125.4s diff=+7.1s
Welch t=3.75 df=7774 p=0.0002 CI [+3.4, +10.8]
A p-value is the probability, computed under the assumption that H0 and the test's model are true, of observing a test statistic at least as extreme as the one observed. Several popular readings are wrong:
A 95% confidence interval is produced by a procedure that covers the true effect in 95% of repeated experiments. Any single interval either contains the true value or not; the 95% describes the method. Read it as the range of effects compatible with the data, and compare both ends with the MDE: an interval above zero but below the MDE is a real but unimportant effect.
The fixed-horizon test controls the false positive rate only if you analyse once, at the planned sample size. Checking the dashboard daily and stopping the first time p drops below 0.05 is a different procedure with a much higher error rate. The simulation runs 20,000 A/A tests (both arms identical, so every significant result is a false positive) with 20 interim looks of 500 users per arm each:
def peeking_fpr(n_sims=20_000, n_per_look=500, looks=20, p=0.10, seed=1):
"""A/A tests: both arms share one conversion rate, so every 'win' is false."""
rng = np.random.default_rng(seed)
# cumulative conversions per arm at each look, shape (n_sims, looks)
a = rng.binomial(n_per_look, p, size=(n_sims, looks)).cumsum(axis=1)
b = rng.binomial(n_per_look, p, size=(n_sims, looks)).cumsum(axis=1)
n = n_per_look * np.arange(1, looks + 1)
pool = (a + b) / (2 * n)
z = (b - a) / n / np.sqrt(pool * (1 - pool) * 2 / n)
sig = np.abs(z) > stats.norm.ppf(0.975)
return sig.any(axis=1).mean(), sig[:, -1].mean()
peek, fixed = peeking_fpr()
print(f"false positive rate, analyse once at the end: {fixed:.3f}")
print(f"false positive rate, stop at first p < 0.05 over 20 looks: {peek:.3f}")
false positive rate, analyse once at the end: 0.047
false positive rate, stop at first p < 0.05 over 20 looks: 0.241
Analysing once gives the promised 5% (0.047 is within simulation noise). Stopping at the first significant look turns it into 24%: roughly one in four experiments with no effect at all would be shipped as a win. Under H0 the z-statistic wanders like a random walk, and with enough looks it eventually crosses any fixed boundary.
There are legitimate reasons to look early, mainly to stop a harmful variant or a clear winner. Group sequential designs allow a fixed number of planned interim analyses while keeping the overall false positive rate at α. The Lan-DeMets approach defines an alpha spending function α(t) that says how much of the total α may be used by the time a fraction t of the planned sample has been collected. The O'Brien-Fleming-type function spends almost nothing early and nearly the full α at the end:
alpha(t) = 2 - 2 * Phi(z_(alpha/2) / sqrt(t)), where Phi is the standard normal CDF and z_(alpha/2) = 1.96 for α = 0.05.
Boundaries are then chosen look by look so that the probability of crossing for the first time at look k equals α(t_k) - α(t_(k-1)). Dedicated libraries use numerical integration; this Monte Carlo version makes the logic explicit:
from scipy.stats import norm
def obf_spending(t, alpha=0.05):
"""Lan-DeMets O'Brien-Fleming-type spending function (two-sided)."""
return 2 - 2 * norm.cdf(norm.ppf(1 - alpha / 2) / np.sqrt(t))
def boundaries(info_fracs, alpha=0.05, n_paths=400_000, seed=0):
"""Find |z| boundaries per look so cumulative crossing prob = spent alpha (Monte Carlo)."""
rng = np.random.default_rng(seed)
t = np.asarray(info_fracs)
incr = rng.normal(size=(n_paths, len(t))) * np.sqrt(np.diff(t, prepend=0))
z = incr.cumsum(axis=1) / np.sqrt(t) # z-statistic at each look under H0
alive = np.ones(n_paths, bool)
bounds = []
for k, tk in enumerate(t):
target = obf_spending(tk, alpha) - obf_spending(t[k - 1], alpha) if k else obf_spending(tk, alpha)
# choose c so that P(alive and |z_k| > c) = target
c = np.quantile(np.abs(z[alive, k]), 1 - target * n_paths / alive.sum())
bounds.append(c)
alive &= np.abs(z[:, k]) <= c
return np.array(bounds), 1 - alive.mean()
looks = np.array([0.2, 0.4, 0.6, 0.8, 1.0])
b, total = boundaries(looks)
for tk, bk in zip(looks, b):
print(f"look at {tk:.0%} of sample: reject if |z| > {bk:.2f} (nominal p < {2*norm.sf(bk):.5f})")
print(f"overall type I error: {total:.4f}")
look at 20% of sample: reject if |z| > 4.41 (nominal p < 0.00001)
look at 40% of sample: reject if |z| > 3.11 (nominal p < 0.00189)
look at 60% of sample: reject if |z| > 2.56 (nominal p < 0.01058)
look at 80% of sample: reject if |z| > 2.25 (nominal p < 0.02428)
look at 100% of sample: reject if |z| > 2.07 (nominal p < 0.03874)
overall type I error: 0.0500
Early looks require overwhelming evidence; the final look uses |z| > 2.07 instead of 1.96, a modest price for four chances to stop early. The first boundary rests on only a handful of simulated crossings and is the noisiest; the exact value is 4.38. Plan the number and timing of looks and fix the spending function before launch. Always-valid methods such as the mixture sequential probability ratio test allow continuous monitoring, at the cost of wider intervals.
Each test at α = 0.05 has a 5% false positive rate when its null is true. Test ten independent true nulls and the chance of at least one false positive is 1 - 0.95^10, about 40%. Two corrections cover most product needs:
from statsmodels.stats.multitest import multipletests
metrics = ["conversion", "revenue", "add_to_cart", "bounce", "pages", "search_use",
"signup", "return_7d", "support_tickets", "refunds"]
pvals = np.array([0.001, 0.008, 0.012, 0.019, 0.041, 0.18, 0.27, 0.44, 0.62, 0.89])
holm = multipletests(pvals, alpha=0.05, method="holm")
bh = multipletests(pvals, alpha=0.05, method="fdr_bh")
print(f"{'metric':16s} {'raw p':>6s} {'Holm':>6s} {'BH':>6s}")
for m, p, ph, pb, rh, rb in zip(metrics, pvals, holm[1], bh[1], holm[0], bh[0]):
print(f"{m:16s} {p:6.3f} {ph:6.3f}{'*' if rh else ' '} {pb:6.3f}{'*' if rb else ' '}")
metric raw p Holm BH
conversion 0.001 0.010* 0.010*
revenue 0.008 0.072 0.040*
add_to_cart 0.012 0.096 0.040*
bounce 0.019 0.133 0.047*
pages 0.041 0.246 0.082
...
Five metrics have raw p below 0.05. Holm keeps one; Benjamini-Hochberg keeps four, accepting that some of those four may be false. A single pre-declared primary metric needs no correction; the corrections apply to the secondary family.
Much of the variance in a metric such as spend comes from stable differences between users that existed before the test. CUPED (Controlled-experiment Using Pre-Experiment Data) subtracts the part of the outcome predictable from a pre-period covariate X: Y_cuped = Y - θ(X - mean(X)) with θ = cov(Y, X) / var(X). Because X is measured before randomisation, it is independent of the assignment, so the adjusted difference in means is still an unbiased estimate of the effect; only its variance shrinks, by a factor of 1 - ρ² where ρ is the correlation between X and Y.
rng = np.random.default_rng(11)
n = 20_000
pre = rng.gamma(2.0, 25.0, size=n) # spend in the 4 weeks before the test
treat = rng.integers(0, 2, size=n) # 50/50 random assignment
post = 0.8 * pre + rng.normal(0, 25, size=n) + 1.5 * treat # true effect: +1.5
theta = np.cov(post, pre)[0, 1] / np.var(pre, ddof=1)
post_cuped = post - theta * (pre - pre.mean())
def diff_ci(y, t):
res = stats.ttest_ind(y[t == 1], y[t == 0], equal_var=False)
ci = res.confidence_interval(0.95)
return y[t == 1].mean() - y[t == 0].mean(), ci.low, ci.high, res.pvalue
for name, y in [("raw", post), ("CUPED", post_cuped)]:
d, lo, hi, p = diff_ci(y, treat)
print(f"{name:6s} effect={d:+.2f} 95% CI [{lo:+.2f}, {hi:+.2f}] p={p:.1e} var={y.var():.0f}")
print(f"theta={theta:.3f} corr(pre, post)={np.corrcoef(pre, post)[0, 1]:.3f}")
raw effect=+1.88 95% CI [+0.82, +2.93] p=4.8e-04 var=1444
CUPED effect=+1.65 95% CI [+0.95, +2.34] p=3.3e-06 var=627
theta=0.808 corr(pre, post)=0.752
With ρ = 0.752 the variance falls to 1 - 0.752² ≈ 43% of the original (627 vs 1444), the interval narrows by about a third, and the estimate moves closer to the true +1.5. Equivalently, the test needs about 43% of the traffic for the same power. Estimate θ on both arms pooled, never per arm; regression adjustment generalises CUPED to several covariates and to users without pre-period data.
If you configured a 50/50 split, the observed counts should be close to 50/50. A significant deviation, a sample ratio mismatch (SRM), means something between assignment and logging is broken, such as a redirect that drops users in one arm or bot filtering that hits one variant harder. Effects measured on such data are unreliable. Check with a chi-square goodness-of-fit test, and use a strict threshold such as p < 0.001, because the check runs on every experiment.
observed = np.array([50_550, 49_450])
expected = observed.sum() * np.array([0.5, 0.5])
chi2, p = stats.chisquare(observed, expected)
print(f"SRM check: chi2={chi2:.2f} p={p:.2e}")
SRM check: chi2=12.10 p=5.04e-04
A 50.5/49.5 split looks harmless, but with 100,000 users it is very unlikely under correct randomisation. Find the cause before analysing anything.
Revenue per user is mostly zeros with a long right tail. The mean is still the right decision target, and with large samples Welch's interval is usually adequate; for medians, percentiles and ratios there is no simple formula. scipy.stats.bootstrap handles two independent samples directly; BCa intervals correct for bias and skew.
rng = np.random.default_rng(3)
def revenue(n, conv, rng):
buys = rng.random(n) < conv
return np.where(buys, rng.lognormal(mean=3.5, sigma=1.2, size=n), 0.0)
rev_a = revenue(8000, 0.050, rng)
rev_b = revenue(8000, 0.053, rng)
print(f"share of zeros A={np.mean(rev_a == 0):.3f}; top 1% of users hold "
f"{np.sort(rev_a)[-80:].sum() / rev_a.sum():.0%} of A's revenue")
res = stats.bootstrap((rev_b, rev_a), lambda b, a, axis=-1: b.mean(axis=axis) - a.mean(axis=axis),
n_resamples=10_000, method="BCa", rng=np.random.default_rng(0))
w = stats.ttest_ind(rev_b, rev_a, equal_var=False).confidence_interval(0.95)
print(f"revenue/user A={rev_a.mean():.2f} B={rev_b.mean():.2f} diff={rev_b.mean()-rev_a.mean():+.2f}")
print(f"BCa bootstrap 95% CI [{res.confidence_interval.low:+.2f}, {res.confidence_interval.high:+.2f}]")
print(f"Welch 95% CI [{w.low:+.2f}, {w.high:+.2f}]")
buyers_a, buyers_b = rev_a[rev_a > 0], rev_b[rev_b > 0]
res_med = stats.bootstrap((buyers_b, buyers_a),
lambda b, a, axis=-1: np.median(b, axis=axis) - np.median(a, axis=axis),
n_resamples=10_000, method="percentile", rng=np.random.default_rng(0))
ci = res_med.confidence_interval
print(f"median order value A={np.median(buyers_a):.2f} B={np.median(buyers_b):.2f} "
f"95% CI for diff [{ci.low:+.2f}, {ci.high:+.2f}]")
share of zeros A=0.944; top 1% of users hold 60% of A's revenue
revenue/user A=3.68 B=3.36 diff=-0.32
BCa bootstrap 95% CI [-1.15, +0.50]
Welch 95% CI [-1.15, +0.52]
median order value A=31.17 B=33.11 95% CI for diff [-4.22, +7.30]
Two observations. First, B has the higher true conversion rate in this simulation, yet its observed revenue per user is lower: when 1% of users carry 60% of revenue, a few large orders dominate, and the interval spans more than 1.6 units on a mean of 3.7. Second, with 8,000 users per arm the bootstrap and Welch intervals almost coincide, so the bootstrap is a check here, not a rescue. It earns its place for the median order value, a statistic without a convenient standard error. The median among buyers conditions on a post-treatment outcome (who buys), so treat it as descriptive.
Assignment must be random with respect to user characteristics, stable for each user, and reproducible across servers and deploys. Hashing the experiment key together with the user id gives all three without shared state. Including the experiment key makes buckets independent across experiments.
Keep the pure hashing logic in its own module so it can be tested without a database:
# experiments/hashing.py
import hashlib
BUCKETS = 10_000
def bucket_for(experiment_key: str, user_id: int | str) -> int:
"""Deterministic bucket in [0, BUCKETS): same inputs, same bucket, on every server."""
digest = hashlib.sha256(f"{experiment_key}:{user_id}".encode()).digest()
return int.from_bytes(digest[:8], "big") % BUCKETS
def choose_variant(experiment_key: str, user_id: int | str, variants: dict[str, int]) -> str:
"""Map the bucket onto variants in proportion to their integer weights."""
total = sum(variants.values())
point = bucket_for(experiment_key, user_id) * total / BUCKETS
cumulative = 0
for name, weight in sorted(variants.items()): # sorted: dict order cannot matter
cumulative += weight
if point < cumulative:
return name
raise ValueError("variants must have positive weights")
Do not use Python's built-in hash(): string hashing is randomised per process, so two workers would disagree. Before trusting the function, run the SRM test on it:
from collections import Counter
split = {"control": 50, "treatment": 50}
counts = Counter(choose_variant("checkout-button", uid, split) for uid in range(100_000))
chi2, p = stats.chisquare([counts["control"], counts["treatment"]])
print(dict(counts), f"SRM p={p:.2f}")
new_split = {"control": 60, "treatment": 40}
moved = sum(choose_variant("checkout-button", uid, split) != choose_variant("checkout-button", uid, new_split)
for uid in range(100_000))
print(f"users who would switch variant after reweighting: {moved:,}")
{'control': 50049, 'treatment': 49951} SRM p=0.76
users who would switch variant after reweighting: 10,042
The split is uniform. The second number is the reason to also store assignments: if someone changes the weights mid-test, a purely stateless scheme silently moves 10% of users to the other arm, contaminating both. Recording the first assignment freezes it and gives the analysis an exposure log: only users who actually reached the tested page are in the experiment.
# experiments/models.py
from django.conf import settings
from django.db import models
class Experiment(models.Model):
key = models.SlugField(unique=True) # e.g. "checkout-button"
variants = models.JSONField(default=dict) # {"control": 50, "treatment": 50}
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.key
class Assignment(models.Model):
experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE,
related_name="assignments")
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
variant = models.CharField(max_length=50)
assigned_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["experiment", "user"],
name="one_assignment_per_user"),
]
indexes = [models.Index(fields=["experiment", "variant"])]
# experiments/services.py
from django.db.models import Count
from .hashing import choose_variant
from .models import Assignment, Experiment
def get_variant(user, experiment_key: str) -> str:
"""Return the user's variant, recording the first exposure exactly once."""
experiment = Experiment.objects.get(key=experiment_key, is_active=True)
assignment, _ = Assignment.objects.get_or_create(
experiment=experiment,
user=user,
defaults={"variant": choose_variant(experiment.key, user.pk, experiment.variants)},
)
return assignment.variant
def variant_counts(experiment_key: str) -> dict[str, int]:
rows = (Assignment.objects.filter(experiment__key=experiment_key)
.values("variant").annotate(n=Count("id")).order_by("variant"))
return {row["variant"]: row["n"] for row in rows}
The unique constraint makes concurrent first requests safe: get_or_create catches the resulting IntegrityError and returns the row the other request created, and since both computed the same deterministic variant, nothing conflicts. Call get_variant in the view that renders the tested feature, not in middleware, so the table records real exposure. Feed variant_counts into the chi-square check in a daily job and alert on p < 0.001. For anonymous visitors, use a random identifier in a first-party cookie instead of user.pk.
peeking_fpr to stop only when |z| crosses the five O'Brien-Fleming-type boundaries computed above at 20%, 40%, ..., 100% of the sample, and confirm the false positive rate returns to about 5%.Found a mistake in this tutorial? Let us know and we will fix it.