A/B Testing Models: Significance Without the Traps
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !Confidence intervals and p-values
- !How your serving layer routes traffic
- !Basics of metric definitions such as CTR and conversion
What You'll Learn
- 1Size an experiment from a minimum detectable effect up front
- 2Assign users to variants deterministically and reproducibly
- 3Choose between t-test, non-parametric, and bootstrap analysis
- 4Recognize peeking, novelty, and interference before they bias a launch
What makes a model experiment different
An A/B test for a feature change asks whether users behave differently. An A/B test for a model asks something harder: whether a system that adapts to each user behaves differently, and whether it keeps behaving that way after the initial novelty wears off. The unit of randomization is still the user, but the treatment is a scoring function that produces a distribution rather than a single button colour, so variance arrives from two places â user heterogeneity and model stochasticity â and the analysis has to tolerate both. Teams that reuse their marketing-experiment template without adjustment routinely declare victories that vanish within a week.
The other difference is cost. A model variant must be trained, registered, served, and monitored for the whole duration of the test, which means experiment length is a budget decision rather than a statistical ideal. That pressure is exactly why discipline matters: a test cut short because it is expensive is a test whose result you should distrust. Fixing the sample size before launch, and committing to run until it is reached, converts an open-ended argument into a scheduled decision.
Sizing the experiment before launch
Sample size is determined by three inputs, and two of them are business choices rather than statistical ones. The baseline rate comes from history. The minimum detectable effect is what change would actually alter your roadmap â if a 2% lift would not change anything, do not design a test that can only detect 0.2%. Power is conventionally 0.8, raising it to 0.9 multiplies the required sample substantially, so spend that only where a false negative is genuinely expensive.
| Input | Where it comes from | Effect of increasing it |
|---|---|---|
| Baseline rate | Historical metric for the test population | Slightly reduces required sample |
| Minimum detectable effect | Smallest lift worth acting on | Fewer users, but only larger wins are visible |
| Significance level | Convention, usually 0.05 | Larger samples for stronger evidence |
| Power | Cost of missing a real win | Larger samples, sharply past 0.8 |
| Variance of the metric | Behaviour of the population | Larger samples; skewed metrics suffer most |
A useful habit is to compute the required size and then ask what traffic fraction it implies in days. If the answer is six weeks at 5% of traffic, either accept the duration, revisit the minimum detectable effect, or reconsider whether the metric can be made less noisy â a lower-variance metric needs fewer users for the same confidence, which is often the cheapest lever available.
Deterministic assignment and metric logging
Assignment must be a pure function of experiment identifier and user identifier, so that a user lands in the same variant on every request, on every device, and when you replay the log six weeks later. Hashing accomplishes this without storing assignment state. Anything based on a random draw per request will split a single user across variants, contaminating the results in a way that inflates variance and can bias the estimate if assignment correlates with session timing.
# assignment.py
import hashlib
import json
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, List, Optional
@dataclass
class Variant:
name: str
model_version: str
traffic: float
@dataclass
class Experiment:
key: str
variants: List[Variant]
primary_metric: str
min_sample: int = 10_000
alpha: float = 0.05
def __post_init__(self):
total = sum(v.traffic for v in self.variants)
if abs(total - 1.0) > 1e-6:
raise ValueError(f"traffic splits sum to {total}, not 1.0")
class Assigner:
@staticmethod
def variant(exp: Experiment, user_id: str) -> Variant:
digest = hashlib.sha256(f"{exp.key}:{user_id}".encode()).hexdigest()
bucket = int(digest[:8], 16) / 0xFFFFFFFF
cumulative = 0.0
for v in exp.variants:
cumulative += v.traffic
if bucket < cumulative:
return v
return exp.variants[-1]
@staticmethod
def split_sizes(exp: Experiment, population: int) -> Dict[str, int]:
return {v.name: int(population * v.traffic) for v in exp.variants}
class MetricLog:
def __init__(self, experiment_key: str, path: str):
self.key = experiment_key
self.path = path
def record(self, user_id: str, variant: str, metric: str, value: float) -> None:
row = {
"experiment": self.key,
"user": user_id,
"variant": variant,
"metric": metric,
"value": value,
"ts": datetime.now(timezone.utc).isoformat(),
}
with open(self.path, "a") as fh:
fh.write(json.dumps(row) + "\n")
exp = Experiment(
key="recsys-v2-2026-02",
variants=[
Variant("control", "rec-v1", 0.5),
Variant("treatment", "rec-v2", 0.5),
],
primary_metric="click_through_rate",
)
print(Assigner.variant(exp, "user_4821").name)
print(Assigner.split_sizes(exp, 240_000))
Two properties follow from hashing and are worth asserting in a test: the same user always maps to the same variant, and changing the experiment key reshuffles the entire population. The second is a feature â it prevents carry-over from a previous test â and the reason experiment keys must be unique rather than reused from a template.
Choosing the analysis
The t-test is the default for a reason: with tens of thousands of users per arm, the central limit theorem rescues most skewed metrics and the result is robust. Its assumptions become a problem with small samples or heavy-tailed revenue metrics, where the bootstrap or a non-parametric test is safer. The bootstrap is also the right tool when the metric is a ratio â revenue per user, conversions per session â because resampling the whole ratio respects the dependence that a naive test on aggregated values destroys.
# analysis.py
import numpy as np
from scipy import stats
from typing import Dict, Tuple
def welch_test(control: np.ndarray, treatment: np.ndarray,
alpha: float = 0.05) -> Dict[str, float]:
t, p = stats.ttest_ind(treatment, control, equal_var=False)
diff = treatment.mean() - control.mean()
se = np.sqrt(treatment.var(ddof=1) / len(treatment)
+ control.var(ddof=1) / len(control))
z = stats.norm.ppf(1 - alpha / 2)
return {
"lift": float(diff),
"relative_lift": float(diff / control.mean()),
"p_value": float(p),
"ci_low": float(diff - z * se),
"ci_high": float(diff + z * se),
"significant": bool(p < alpha),
}
def bootstrap_lift(control: np.ndarray, treatment: np.ndarray,
n_boot: int = 10_000, alpha: float = 0.05) -> Dict[str, float]:
rng = np.random.default_rng(42)
diffs = np.empty(n_boot)
for i in range(n_boot):
c = rng.choice(control, size=len(control), replace=True)
t = rng.choice(treatment, size=len(treatment), replace=True)
diffs[i] = t.mean() - c.mean()
low, high = np.percentile(diffs, [100 * alpha / 2, 100 * (1 - alpha / 2)])
observed = treatment.mean() - control.mean()
p = 2 * min((diffs <= 0).mean(), (diffs >= 0).mean())
return {
"lift": float(observed),
"ci_low": float(low),
"ci_high": float(high),
"p_value": float(p),
"significant": bool(low > 0 or high < 0),
}
def required_sample(baseline: float, mde: float,
alpha: float = 0.05, power: float = 0.8) -> int:
p1, p2 = baseline, baseline + mde
pooled = (p1 + p2) / 2
z_a = stats.norm.ppf(1 - alpha / 2)
z_b = stats.norm.ppf(power)
num = (z_a * np.sqrt(2 * pooled * (1 - pooled))
+ z_b * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
return int(np.ceil(num / (p2 - p1) ** 2))
control = np.random.beta(2, 10, size=50_000)
treatment = np.random.beta(2.1, 10, size=50_000)
print("t-test:", welch_test(control, treatment))
print("bootstrap:", bootstrap_lift(control, treatment))
print("n per arm:", required_sample(baseline=0.2, mde=0.02))
Report the effect size and its interval alongside the p-value. A result can be statistically significant and practically irrelevant, and the interval is what lets a decision-maker see the difference rather than a binary label.
The traps that bite in practice
Peeking is the classic. Checking the dashboard every morning and stopping when the p-value crosses 0.05 raises the false positive rate far above the nominal level, because you are running many correlated tests without correcting for any of them. If you must monitor continuously, use a sequential method with an error-spending boundary, or simply pre-commit to the sample size and look at the metric only when the experiment reaches it.
Novelty is subtler: users notice a change, try it differently, and revert after a week. Run the test at least one full usage cycle â often two weeks for consumer products â and compare the first three days against the last three days. A treatment effect that decays sharply inside the test window predicts decay after launch. Interference is worse still, because no amount of duration fixes it: if one user's treatment affects another's outcome â social feeds, marketplace pricing, shared queues â the SUTVA assumption breaks and the estimated effect is biased in a direction you cannot easily bound.
From result to launch decision
The analysis ends with a number; the organization needs a decision, and the gap between them is where most experimentation programs lose their credibility. Write the decision rule into the experiment definition before launch â for example, promote if the lift exceeds 1% with an interval excluding zero and no guardrail regression â then let the rule produce the recommendation and a named owner make the call. When the result is a tie, that is an outcome worth recording rather than a reason to extend the test: extending after seeing a tie is just another form of peeking, dressed up as diligence.
After the decision, close the loop properly. Archive the experiment with its final sample sizes, effect sizes, and reasoning; note what you would do differently; and keep the control and treatment code paths identified rather than deleted, because the loser of today's test frequently becomes the baseline that tomorrow's challenger must beat. Teams that archive honestly accumulate a body of evidence about their own metrics â how large effects usually are, how long tests really take â which makes every subsequent sizing calculation more realistic than any textbook formula.
â ī¸Pre-commit before you look
Common Mistakes
Stopping the test as soon as p is below 0.05
Fix: Commit to the required sample up front, or use a sequential design with a proper error-spending boundary.
Choosing the minimum detectable effect after seeing results
Fix: Derive it from the smallest lift that would change a decision, and size the test from that.
Randomizing per request instead of per user
Fix: Hash experiment key plus user identifier so assignment is stable across devices and replays.
Ignoring guardrail metrics because the primary metric improved
Fix: Monitor latency, error rate, and unsubscribe rates as hard constraints that can veto a launch.
Best Practices
- Record the decision rule and stop date in the experiment definition itself
- Report effect size and confidence interval, not just a p-value
- Split the test window into halves to detect novelty decay
- Use the bootstrap for ratio metrics such as revenue per user
- Keep control and treatment on identical infrastructure so latency differences do not leak into the metric
Interview Questions
Q1: Why is peeking at results harmful?
Repeated significance testing without correction inflates the false positive rate; the nominal 5% can behave like 20% or more depending on how often you look.
Q2: How do you size an A/B test?
From baseline rate, minimum detectable effect, alpha, and power â computed before launch and turned into a required sample per arm.
Q3: What breaks when users influence each other?
The independence assumption. Network interference biases the estimated effect, sometimes reversing its sign, and needs cluster randomization or switchback designs.
Q4: When would you use a multi-armed bandit instead?
When the objective is cumulative reward during the test rather than an unbiased estimate â exploration budgets and short-lived treatments.
Key Takeaways
- Size first, then run: fix sample and decision rule before assignment begins
- Hash-based per-user assignment keeps variants stable and replayable
- Match the test to the metric â Welch's t-test by default, bootstrap for ratios
- Peeking, novelty, and interference each bias results in a different direction
- Guardrail metrics can veto a winning primary metric; monitor them as constraints