Sub topic 12
A/B Testing Models Against a Business Outcome
This chapter assumes you can read short Python snippets, know basic model metrics, and understand proportions and averages. It also assumes you have seen shadow and canary releases earlier in this tutorial.
What an A/B test answers
Shadow deployment asks whether the candidate model runs correctly on live traffic. A canary asks whether it is safe to expose to users. An A/B test asks a different question: does the candidate cause a better business outcome than the stable model?
In an A/B test, each unit (usually a user) is randomly assigned to one of two groups.
- Control (A) receives predictions from the stable model.
- Treatment (B) receives predictions from the candidate model.
Both groups run at the same time, so seasonality, marketing campaigns, and outages affect them equally. Random assignment means the groups differ, on average, only in which model they saw. That is what lets you read a difference in outcomes as caused by the model.
Offline metrics such as AUC or F1 are proxies. A fraud model with higher recall can still reduce revenue if it blocks good customers. The A/B test measures the outcome you care about, such as conversion, retained revenue, or chargeback losses.
The experiment workflow
Decide the steps before the experiment starts. Choosing the metric or stopping time after you see the data lets you find whatever result you hoped for.
Step 1: Write down the hypothesis and metrics
Pick one primary metric that decides the outcome. For a ranking model it might be purchase conversion per user. Add guardrail metrics that must not get worse: p95 latency, error rate, refund rate. Add diagnostic metrics such as click-through rate to help explain a result, but do not use them to declare a winner.
A useful hypothesis names the direction and the size: "Ranker v2 raises purchase conversion from 4.8% to at least 5.4%." The size you care about is called the minimum detectable effect (MDE). It sets the sample size below.
Step 2: Assign units deterministically
The randomization unit should match the thing whose outcome you measure. If the metric is per user, randomize by user ID. Randomizing per request would show the same user both models and blur the effect.
Assignment must be sticky: the same user always gets the same variant. A salted hash gives this without storing any state. The salt is specific to the experiment, so one experiment's assignment does not correlate with another's.
import hashlib
def bucket(unit_id: str, salt: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest()
return int(digest, 16) % buckets
def choose_variant(unit_id: str, salt: str, candidate_percent: float) -> str:
threshold = int(candidate_percent * 100) # percent of 10000 buckets
return "candidate" if bucket(unit_id, salt) < threshold else "stable"
print(choose_variant("user-123", "ranker-v2-exp1", 5))For a 50/50 test, pass candidate_percent=50. Log the assignment (unit ID, experiment, variant, timestamp) at the moment the user is actually exposed, not only when the assignment is computed. Analysis should include only units that were exposed.
Step 3: Compute the sample size before you start
Statistical power is the probability that the test detects a real effect of at least the MDE. The usual targets are a 5% significance level (alpha) and 80% power. A smaller MDE or a lower baseline rate needs many more samples.
For two proportions, the required sample per group is approximately:
n = (z(alpha/2) + z(beta))^2 × (p1(1 − p1) + p2(1 − p2)) / (p2 − p1)^2
from math import ceil
from statistics import NormalDist
def sample_size_per_group(p1: float, p2: float,
alpha: float = 0.05, power: float = 0.80) -> int:
z_alpha = NormalDist().inv_cdf(1 - alpha / 2)
z_beta = NormalDist().inv_cdf(power)
variance = p1 * (1 - p1) + p2 * (1 - p2)
return ceil((z_alpha + z_beta) ** 2 * variance / (p2 - p1) ** 2)
print(sample_size_per_group(0.048, 0.054))This prints about 21,100 per group. Divide the total by your daily eligible traffic to get the duration. Round up to whole weeks so that every day of the week appears equally often.
Step 4: Check assignment before reading results
Before looking at the metric, confirm that the groups have the sizes you designed. If you planned 50/50 and observed 50,900 versus 49,100, a chi-square test will flag the difference as far larger than chance. This is a sample ratio mismatch (SRM). It usually means a bug: one variant crashes more often and loses logged exposures, a bot filter treats variants differently, or the redirect drops users. A result from a test with SRM cannot be trusted, even if the p-value looks good. Fix the cause and rerun.
Step 5: Test the primary metric
For a conversion rate, use a two-proportion z-test. The null hypothesis says both groups share the same true rate. The p-value is the probability of seeing a difference at least this large if the null were true.
from math import sqrt
from statistics import NormalDist
def two_proportion_z_test(x_a: int, n_a: int, x_b: int, n_b: int):
p_a, p_b = x_a / n_a, x_b / n_b
pooled = (x_a + x_b) / (n_a + n_b)
se = sqrt(pooled * (1 - pooled) * (1 / n_a + 1 / n_b))
z = (p_b - p_a) / se
p_value = 2 * (1 - NormalDist().cdf(abs(z)))
return z, p_value
z, p = two_proportion_z_test(x_a=480, n_a=10000, x_b=540, n_b=10000)
print(round(z, 2), round(p, 3))The output is 1.93 0.054. Control converted at 4.8% and treatment at 5.4%, a 12.5% relative lift. Yet at alpha 0.05 you cannot reject the null. This test had 10,000 users per group, about half of the roughly 21,100 the sample-size calculation required, so it was underpowered for this effect. The correct reading is "inconclusive", not "no effect" and not "almost a win". Collect the planned sample instead of declaring victory.
Report the effect size with a confidence interval, not only the p-value. A tiny lift can be significant with millions of users and still not be worth the engineering cost.
Step 6: Wait for the labels
Many business outcomes arrive late. A loan default takes months, a chargeback takes weeks, and a purchase may follow the exposure by days. If you analyze after three days, the treatment group's late conversions are missing, and so are the control group's. The comparison is still fair only if both groups are measured with the same follow-up window per user.
Practical rules:
- Define the outcome window in advance, such as "purchase within 7 days of first exposure".
- Include a user only after their full window has elapsed, or use a metric that matures quickly and correlates with the slow one.
- Track the rate of missing labels per variant. If the candidate changes which cases get labeled (for example, a model that blocks transactions removes the chance to see whether they were fraud), the labels themselves are biased.
Common failure modes
| Problem | What happens | Defense |
|---|---|---|
| Peeking | Checking the p-value daily and stopping at the first value below 0.05 inflates false positives well beyond 5% | Fix the sample size in advance, or use a sequential method designed for repeated looks |
| Multiple metrics | With 20 metrics, about one will look significant by chance | One primary metric, the rest as guardrails or diagnostics |
| Novelty effect | Users click on anything new, and the lift fades | Run at least one to two weeks and check whether the effect shrinks over time |
| Interference | Users affect each other, as in marketplaces and social feeds, so the control group is contaminated | Randomize by cluster, such as region or seller |
| Wrong unit | Randomizing by request but measuring per user | Match the unit to the metric |
Where A/B testing fits
An A/B test exposes up to half your traffic to an unproven model, so run it after cheaper checks. A typical sequence is offline evaluation, then shadow to verify behavior, then a small canary to verify safety, then an A/B test to verify business value. The A/B test keeps its guardrails live throughout: if latency or error rate breaches a threshold, stop the experiment regardless of the primary metric.
Exercise
A test is planned at 50/50 with 40,000 users. After one week, 20,900 users are in control and 19,100 in treatment, and treatment shows a significant lift (p = 0.01). Should you ship the candidate? Explain.
Show answer
No. A split of 20,900 versus 19,100 is far from 50/50 for samples of this size, so this is a sample ratio mismatch. It points to a bug in assignment, exposure logging, or filtering, and any difference in outcomes could come from that bug instead of the model. Find and fix the cause, then rerun the experiment before trusting the p-value.
Exercise
With the sample size function above, you want to detect a lift from a 2% baseline conversion rate to 2.2%. Will you need more or fewer users per group than for 4.8% to 5.4%, and why?
Show answer
More. The absolute difference is only 0.2 percentage points, compared with 0.6. Because the denominator in the formula is the squared difference, a three times smaller difference needs roughly nine times more samples, partly offset by the smaller variance at a lower baseline. The result is about 80,600 users per group, far more than the 21,100 for the larger lift.