A/B testing LLM features
Randomly split users between old and new model or prompt, compare one pre-chosen primary metric, and let guardrails (latency, cost, safety) veto. Size it with a power analysis; never stop at the first significant peek.
Analogy: A clinical trial for a prompt: random assignment, an endpoint fixed before the trial starts, safety monitoring that can halt it, and no unblinding halfway because the results look good.
How it works
- Randomization makes it the only method that measures causal impact on real outcomes; offline evals only predict it.
- Randomize by user with sticky assignment, so nobody sees both models.
- Peeking, stopping at the first p < 0.05, inflates false positives; fix the horizon or use a sequential test.
- Run at least 1–2 full weeks: novelty brings curiosity usage in week one, so watch the trend.
- CUPED adjusts with pre-experiment behavior, winning back power lost to the extra noise of stochastic outputs.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your 50/50 A/B test of a new model shows 52% / 48% of users after a week, and the slower treatment arm has fewer logged sessions. The primary metric favors treatment. What do you do?
Go deeper
Full explanation
An A/B test randomly assigns users to the current system (control) or a change (treatment): a new model, prompt or retrieval setup. Randomization makes it the only method that measures causal impact on real outcomes; offline evals only predict it.
Write the plan before launch:
- One primary metric tied to value: task success, resolution without escalation, conversion. Choosing it after seeing results manufactures winners.
- Guardrails that veto a launch: p95 latency, cost per session, safety flags, error rate.
- Sample size from a power analysis on the smallest effect worth shipping. It sets the duration; run at least 1–2 full weeks.
- Unit: randomize by user with sticky assignment and analyze per user, so nobody sees both models.
Traps that hit LLM features:
- Peeking: stopping at the first p < 0.05 inflates false positives. Fix the horizon, or use a sequential test (mSPRT, always-valid p-values) built for continuous monitoring.
- Novelty: a new assistant gets curiosity usage in week one. Watch the trend, not just the total.
- Extra variance: stochastic outputs add noise on top of user-to-user variance. CUPED (adjusting with pre-experiment behavior) wins power back.
- Ranking changes (retrieval, search, recommendations): interleaving merges both rankers' results into one list and credits each click to its ranker, detecting preferences with far fewer users.
Code Power analysis, SRM check and a guardrail-first decision
from scipy.stats import chisquare
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize, proportions_ztest
# 1) Before launch: users per arm to detect +2 pts on a 50% task-success rate
h = proportion_effectsize(0.52, 0.50)
n = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8)
print(f"{n:,.0f} users per arm") # ~9,800: this, not impatience, sets the duration
# 2) Read once, at the pre-registered horizon
def decide(users: dict, wins: dict, guardrails: dict) -> str:
# Sample-ratio mismatch: a broken 50/50 split invalidates every metric
if chisquare([users["A"], users["B"]]).pvalue < 0.001:
return "STOP: SRM, fix assignment first"
# Guardrails veto whatever the primary metric says
for name, (ctrl, treat, max_rel) in guardrails.items():
if treat > ctrl * (1 + max_rel):
return f"NO SHIP: {name} {ctrl} -> {treat}"
_, p = proportions_ztest([wins["B"], wins["A"]], [users["B"], users["A"]])
lift = wins["B"] / users["B"] - wins["A"] / users["A"]
return f"SHIP: {lift:+.1%} (p={p:.3f})" if p < 0.05 and lift > 0 else "NO SHIP: no proven lift"
print(decide(
users={"A": 10_120, "B": 10_045},
wins={"A": 5_060, "B": 5_290}, # +2.7 pts on the primary metric...
guardrails={"p95_latency_s": (2.1, 2.4, 0.10), "cost_usd": (0.031, 0.033, 0.15)},
)) # -> NO SHIP: p95_latency_s 2.1 -> 2.4 (+14% breaks the 10% budget)Real example
You want to swap a support assistant's model for one ~50% cheaper; offline correctness is within 1 point. The plan: 50/50 by user, primary metric = resolved without human escalation (baseline 62%), non-inferiority margin of 2 points, guardrails on p95 latency, CSAT and safety flags. Power analysis says ~9,200 users per arm: 3 weeks. On day 4 the dashboard shows +3 points at p=0.03 and the PM wants to ship; you hold the horizon. At 3 weeks: −0.4 points, 95% CI [−1.8, +1.0], guardrails flat. The worst case sits inside the margin, so you ship and halve the bill.
Trade-offs +3 · −3
+ You gain
- Measures causal impact on business outcomes, not proxies.
- Captures what no offline set anticipates: user adaptation, latency sensitivity, real cost.
- Guardrails turn "better quality, worse latency" into an explicit, pre-agreed decision.
− You pay
- Needs real traffic: a few-point effect takes ~10,000 users per arm.
- Slow: weeks per decision, longer for delayed outcomes like retention.
- Easy to fool yourself with peeking, metric fishing, broken splits and novelty.
Use it when
User-facing changes judged by behavior (task success, conversion, retention) when you have the traffic: a few-point effect needs ~10,000 users per arm.
Avoid it when
Low traffic, effects too small to power, or safety regressions you must block offline. Then rely on offline evals, shadow mode, canaries and qualitative review.
Numbers to know 5
- Lehr's rule: n per arm ≈ 16·p(1−p)/δ² (80% power, α=0.05). Baseline 50%: +2 pts → ~10,000 per arm; +1 pt → ~40,000.
- Peeking: 10 interim looks at p < 0.05 push the real false-positive rate to ~19% (Armitage et al.).
- 20 metrics at α=0.05 → ~64% chance at least one shows a false "win" (1 − 0.95²⁰).
- CUPED at Microsoft (Deng et al., 2013): ~50% variance reduction on some Bing metrics, the same power with ~half the traffic.
- Rule of thumb: run at least 1–2 full weeks to cover weekly cycles and let novelty fade.
Common pitfalls 4
- Stopping the test the day it first turns significant.
- Randomizing per request: the same user sees both models and their sessions contaminate each other.
- Ignoring sample-ratio mismatch: 52/48 instead of 50/50 usually means a bug, e.g. the slower arm loses logged sessions to timeouts.
- Choosing or switching the primary metric after looking at the results.
Interview questions 3
Answer out loud first, then reveal.
How would you A/B test a new model for a chat product?Show answer
I'd write the plan before launch. Randomize by user with sticky assignment. One primary metric tied to value, say task success or resolution without escalation, and guardrails that veto: p95 latency, cost per session, safety-flag rate, errors. A power analysis on the smallest effect worth shipping sets the sample and duration, at least one or two full weeks for novelty and weekly cycles. At read time I check sample-ratio mismatch first, then guardrails, then the primary metric at the fixed horizon, and I segment by key cohorts so an average gain can't hide a regression.
The PM sees p=0.03 on day three and wants to ship. What do you say?Show answer
That this p-value isn't valid yet. With daily peeking at 0.05, the real false-positive rate climbs fast, to about 19% after ten looks. Early days also over-represent heavy users and novelty clicks. So either we wait for the planned horizon or, if we truly need continuous monitoring, we switch to a sequential test like mSPRT with always-valid p-values, which most experimentation platforms support. If the effect is real, it will still be there in two weeks; if speed matters more, I'd rather lower the bar openly than pretend we have proof.
Your team changed the retrieval ranker. Why might you use interleaving instead of an A/B test?Show answer
Because ranking differences are small effects, and an A/B test on downstream metrics needs a huge sample to see them. Interleaving shows each user one merged list, drafting results alternately from rankers A and B, and credits each click to the ranker that contributed it. Every user compares both, which removes between-user variance; it is often reported to need ~10–100× less traffic. The catch: it tells me which ranking users prefer, not the business impact. So I use it to pick a winner fast, then confirm that winner with a normal A/B test on the primary metric.