Sub topic 12
A/B Testing Models Against a Business Outcome
Assume you can serve two model versions behind an HTTP or RPC endpoint, understand metrics such as accuracy and latency, and can read basic Python and probability notation. This chapter focuses on measuring a business result, not only the model's offline score.
What an A/B test answers
An A/B test compares a control group with a treatment group under normal production conditions.
- The control receives the current model.
- The treatment receives the candidate model.
- The primary metric measures the business outcome you want to improve.
For example, a recommendation model might change the purchase conversion rate. The candidate can have higher offline accuracy but lower conversion if its predictions make the product harder to use.
| Group | Model | Example question |
|---|---|---|
| Control | Current model | What conversion rate does the existing system produce? |
| Treatment | Candidate model | Does the new model change conversion? |
Randomly assign an appropriate unit, such as a user, account, or session. Keep that assignment sticky so one user does not switch models between requests. Otherwise, the user may receive a mixture of behaviors, and the comparison becomes difficult to interpret.
Use an experiment-specific salt when hashing an identifier. This keeps assignments deterministic while preventing unrelated experiments from sharing the same buckets.
import hashlib
def variant(user_id: str, experiment: str, treatment_percent: float) -> str:
digest = hashlib.sha256(
f"{experiment}:{user_id}".encode()
).hexdigest()
bucket = int(digest, 16) % 10_000
return "treatment" if bucket < treatment_percent * 100 else "control"
print(variant("user-123", "fraud-model-v2", 10))Choose metrics before launch
Choose one primary metric before looking at results. Examples include completed purchases, approved applications, retained users after seven days, or revenue per eligible user.
Also define guardrails. Guardrails are limits on outcomes that must not get worse, even if the primary metric improves.
- Primary: purchase conversion rate.
- Guardrail: checkout error rate.
- Guardrail: p95 response latency.
- Guardrail: fraud loss per transaction.
Define the eligible population precisely. If only users who receive a recommendation can be affected, do not silently include users who never entered the recommendation flow. Record exclusions and missing events so the denominator is auditable.
Compare proportions and uncertainty
For a binary outcome, calculate the proportion of successes in each group:
\hat p_c = x_c/n_c,\qquad \hat p_t = x_t/n_twhere \(x\) is the number of successes and \(n\) is the number of eligible observations.
A two-proportion test estimates whether the observed difference could plausibly be random variation. The test does not prove that the candidate is valuable. It only evaluates the evidence under its statistical assumptions.
from math import sqrt
from statistics import NormalDist
def two_proportion_z_test(x_control, n_control, x_treatment, n_treatment):
p_control = x_control / n_control
p_treatment = x_treatment / n_treatment
pooled = (x_control + x_treatment) / (n_control + n_treatment)
standard_error = sqrt(
pooled * (1 - pooled) *
(1 / n_control + 1 / n_treatment)
)
z = (p_treatment - p_control) / standard_error
p_value = 2 * (1 - NormalDist().cdf(abs(z)))
return z, p_value
z, p = two_proportion_z_test(480, 10_000, 540, 10_000)
print(f"z={z:.2f}, p={p:.3f}")A small p-value is not enough for promotion. Check the effect size, confidence interval, practical value, and guardrails. A statistically detectable improvement of 0.01 percentage points may not repay the cost or risk of deployment.
Run the experiment carefully
Before starting, write down:
- The primary metric and its calculation.
- The assignment unit and traffic split.
- The minimum useful effect.
- The planned sample size and experiment duration.
- Promotion and rollback rules.
- The label window, if outcomes arrive later.
Do not repeatedly inspect the result and stop at the first favorable value. This practice, called peeking, increases false positives unless the stopping rule accounts for repeated looks. Watch for sample ratio mismatch too: if a planned 90/10 split becomes 70/30, investigate routing or logging before trusting any outcome.

Exercise
The treatment conversion rate is higher, but latency exceeds the guardrail. Should you promote the candidate?
Show answer
No. Investigate or roll back until the latency guardrail is satisfied, even if the primary metric improves.