Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 56/ 160
03. Mathematics & Statistics

A/B Testing & Experiment Design

Design trustworthy online experiments: metrics, randomization, SRM checks, and peeking risks.

AdvancedRandomize · Metric · Power3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Randomly show half the people the old version and half the new one, then compare results fairly, following rules decided before you start.

Think of it like…

A fair taste test: randomly give each person one of two recipes, don't tell them which, decide beforehand what you'll measure and how many tasters you need, and don't stop the test early just because the first few votes favour your recipe.

Where you’ve seen it

A team tests a new checkout button. Primary metric: purchase conversion (baseline 10%, minimum detectable lift 1 point). Power analysis gives about 14,700 users per arm at α = 0.05 and 80% power; with 3,000 users per arm per day they run 14 days to cover two full weekly cycles. Guardrails: page load time, refund rate and revenue per user. After day 3 the assignment counts are 10,300 vs 9,700 instead of the planned 10,000 each: χ² = 300²/10,000 + 300²/10,000 = 18, p < 0.001, an SRM alarm. Investigation finds a redirect bug dropping treatment users on one browser, so the results are discarded, the bug is fixed and the test restarts.

Words you’ll hear

Randomisation unit
The entity randomly assigned (user, session, device, store); analyses must use the same unit.
Primary and guardrail metrics
The metric that decides success; metrics that must not regress.
SRM (sample ratio mismatch)
Observed group sizes differ from the planned split more than chance allows.
Peeking
Repeatedly checking significance and stopping when it appears, inflating false positives.

Visual diagram

Loading interactive diagram

Theory & deep dive

Designing the experiment

Hypothesis and metrics: state the change and expected effect, pick one primary metric that reflects the goal and is sensitive enough (conversion, revenue per user, retention), and guardrails for harm (latency, errors, refunds, unsubscribes). Define metrics precisely (denominator, attribution window) before launch. Unit and randomisation: randomise at the level where outcomes are independent, usually the user via a stable hash of the user id plus an experiment salt, so a user always sees the same variant. If the metric is per session but the unit is the user, use user-level aggregates or clustered standard errors, because sessions from one user are not independent.

Size and duration: compute n from baseline, minimum detectable effect, α and power (see the power lesson), then divide by eligible daily traffic and round up to whole weeks. Consider variance reduction such as CUPED, which adjusts the metric using each user's pre-experiment value: with correlation ρ between pre and post metric, variance falls by a factor (1 − ρ²), so ρ = 0.5 cuts it by 25% and shortens the test. Run an A/A test occasionally to validate the platform: about 5% of A/A tests should be significant at α = 0.05.

Deterministic assignment

bucket = int(hashlib.md5(f"{user_id}:{experiment_salt}".encode()).hexdigest(), 16) % 100; variant = "B" if bucket < 50 else "A" gives stable, reproducible, uniform assignment; changing the salt re-randomises for a new experiment.

Key takeaway: Pre-define unit, metrics, size and duration; randomise by stable hash; consider CUPED.

Running it safely: SRM, peeking and interpretation

SRM: compare observed assignment counts with the planned ratio using a chi-square test; a tiny p-value (say < 0.001) means randomisation or logging is broken (bot filtering applied differently, redirects, caching, crashes in one arm), and the experiment's results can't be trusted until the cause is found. Peeking: checking a standard test repeatedly and stopping at the first p < 0.05 inflates the false-positive rate (five looks gives roughly 14% instead of 5%). Either analyse once at the planned sample size, or use sequential testing (group-sequential boundaries, always-valid p-values, Bayesian methods) designed for continuous monitoring. Watch for the novelty effect (an initial bump that fades) and primacy effects, and for interference when users affect each other (social features, marketplaces), which needs cluster or switchback designs.

Analysis: run the pre-specified test on the primary metric, report the absolute and relative lift with a confidence interval, check guardrails, and treat segment breakdowns as exploratory (multiple comparisons). Decide using practical significance and cost: a result "significant" for a 0.05-point lift may not justify rollout, and a non-significant result with a wide interval is inconclusive, not evidence of no effect. Record learnings, because a repository of past experiments improves priors and prevents repeating failures. Ship decisions should consider long-term effects, so holdout groups and post-launch monitoring catch effects the test window missed.

An SRM check

chi2, p = stats.chisquare([10300, 9700], f_exp=[10000, 10000]) returns chi2 = 18.0, p ≈ 0.00002. Treat p < 0.001 as an alarm and investigate before reading any outcome metric.

Key takeaway: Check SRM first, avoid peeking or use sequential tests, and judge practical significance.

How it works, step by step

Step 1 of 4
Design

1. Write the plan

Fix the hypothesis, unit, primary and guardrail metrics, MDE, α, power and analysis method before launch.

conversion · MDE 1 pt · α 0.05 · power 80%
Key numbers at this step
Pre-register
the plan

When to use it & trade-offs

What it is

An A/B test randomly assigns units (users, sessions, stores) to control (A) or treatment (B) and compares an outcome, so that any systematic difference can be attributed to the change rather than to who saw it. A trustworthy design fixes in advance the randomisation unit, a single primary metric (plus guardrail metrics that must not get worse), the sample size from a power calculation, the duration (whole weekly cycles) and the analysis plan. During and after the run you check sample ratio mismatch (SRM), avoid peeking, and interpret results with effect sizes and confidence intervals.

Why it matters: Online experiments are the standard way to decide product changes, but most flawed results come from design and process errors, not maths: broken randomisation, metrics chosen after the fact, stopping when the p-value dips under 0.05, or interference between users. A disciplined experiment process turns "we think it's better" into evidence, and failures like SRM or peeking explain why many "wins" disappear after launch.

When to reach for it

  • Product, pricing and UX changes
  • Marketing and recommendation experiments
  • Validating model improvements online

When to avoid or be careful

  • Stopping the test when the p-value first drops below 0.05
  • Changing the primary metric after seeing results
  • Ignoring SRM or logging issues

Experiment approaches

Fixed-horizon A/B test
Best for: Most product changes with enough traffic

Strengths: Simple analysis; valid p-values if run to plan.

Watch out: No early stopping; must wait for the planned sample.

Sequential / always-valid testing
Best for: Continuous monitoring and early stopping needs

Strengths: Valid under peeking; can stop early for big effects.

Watch out: More complex; somewhat less power.

Cluster or switchback designs
Best for: Marketplaces and networks with interference

Strengths: Handles spillover between units.

Watch out: Larger variance; more complex analysis.

Interview signals & numbers to know

When this topic comes up

  • “The test was significant on day 3 but not on day 14”
  • “Assignment counts are 51/49”
  • “How long should we run the test?”
  • Novelty effects
  • CUPED

Benchmarks & rules of thumb

≈ 14% -
false-positive rate with 5 peeks at α = 0.05
χ² = 18, p < 0.001 -
the SRM alarm in the example
1 − ρ² -
variance factor from CUPED

Common mistakes & follow-ups

Common interview mistakes

  • Ending the test at day 3 because the dashboard showed p = 0.03.
  • Randomising by session but analysing by user, understating uncertainty.
  • Reporting five segment cuts and highlighting the one that is significant.

Likely interviewer follow-ups

  • What is SRM and what do you do when you see it?
  • Why is peeking a problem, and how do you monitor safely?
  • How would you design an experiment for a marketplace?
Interview tip: Open with the pre-registered plan (unit, primary metric, sample size). Process discipline is what interviewers are really testing.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply A/B Testing & Experiment Design with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
ANOVA (Analysis of Variance)
Next topic
Vectors, Matrices & Matrix Multiplication