A/B Testing and Online Experimentation
A/B Testing and Online Experimentation
Learn how to design, run, analyze, and interpret controlled online experiments for products, Machine Learning systems, websites, and business decisions.
Introduction
Offline evaluation tells us how a model or feature performed on historical data. It does not always tell us what will happen when real users interact with the changed system.
A/B testing is a controlled experiment in which eligible experimental units are randomly assigned to different versions of an experience. Their outcomes are then compared using predefined metrics.
Version A is commonly the current experience, called the control. Version B is the proposed change, called the treatment or variant. Random assignment helps make the groups comparable before the treatment is applied.
Learning Objectives
By the End of This Lesson
- Explain the purpose of A/B testing
- Distinguish correlation from causal evidence
- Define control, treatment, and experimental unit
- Write a clear and testable hypothesis
- Select primary, secondary, and guardrail metrics
- Understand random assignment and sample-ratio checks
- Explain null and alternative hypotheses
- Interpret p-values and confidence intervals correctly
- Distinguish statistical significance from practical significance
- Understand false positives, false negatives, and statistical power
- Plan sample size using a minimum detectable effect
- Calculate absolute and relative changes
- Analyze binary and continuous metrics
- Recognize repeated-peeking and early-stopping risks
- Understand novelty, carryover, interference, and logging risks
- Apply experimentation to Machine Learning systems
- Create an experiment decision record
Prerequisites
Recommended Knowledge
- Basic probability and statistics
- Mean, variance, and standard deviation
- Sampling and population concepts
- Machine Learning evaluation metrics
- Basic Python, NumPy, and pandas
- Basic business-metric interpretation
Packages for the Coding Examples
- NumPy
- pandas
- SciPy
- statsmodels
python -m pip install numpy pandas scipy statsmodels
Control and Treatment
Control
- Represents the current or baseline experience
- Provides a reference for comparison
- Should remain stable during the experiment
- Is commonly called version A
Treatment
- Receives the proposed change
- Differs according to the documented treatment
- Is evaluated against the same metric definitions
- Is commonly called version B
Correlation vs Causation
Observational data can reveal that two variables move together, but this does not prove that one caused the other. Users who choose a feature may already differ from users who do not choose it.
Random assignment helps break systematic relationships between treatment assignment and pre-existing user characteristics. If the experiment is implemented correctly, differences in outcomes can be attributed more credibly to the treatment.
Choose the Experimental Unit
The experimental unit is the entity independently assigned to a variant. It should match how the treatment operates and how interference can occur.
| Unit | Possible Use | Important Risk |
|---|---|---|
| User | Personalized interface or recommendation change | One user may use several devices |
| Account | Business or subscription experience | Several users may share one account |
| Session | Short-lived experience | A returning user may see several variants |
| Store | Retail process or pricing experiment | Stores may differ substantially in size or location |
| Geographical Area | Region-level policy or marketing intervention | Neighboring areas may influence each other |
| Time Block | Infrastructure or marketplace experiment | Traffic and demand may vary by time |
Random Assignment
Random assignment gives eligible experimental units a defined chance of receiving each variant. It is the foundation of a controlled experiment.
Assignment Requirements
- Define the eligible population before starting
- Assign units using a reproducible randomization mechanism
- Keep assignment persistent when repeated exposure matters
- Prevent one unit from appearing in incompatible groups
- Log assignment before measuring treatment outcomes
- Validate traffic allocation after launch
- Investigate unexpected group-size differences
Write the Hypothesis First
A useful hypothesis describes the change, affected population, expected mechanism, primary outcome, expected direction, and decision the result will support.
Define Metrics Before Launch
| Metric Type | Purpose | Example |
|---|---|---|
| Primary Metric | Represents the outcome used for the main decision | Completed registration rate |
| Secondary Metric | Provides additional diagnostic or behavioral context | Time required to complete registration |
| Guardrail Metric | Detects unacceptable harm elsewhere | Error rate or complaint rate |
| Diagnostic Metric | Helps explain the mechanism behind the result | Form-step abandonment |
| Data-Quality Metric | Checks experiment instrumentation and assignment | Missing assignment records |
Conversion Rate
A binary conversion metric records whether an experimental unit completed a defined outcome.
If the unit is a user, one user should not be counted as several independent observations merely because the user generated several events.
Absolute and Relative Change
Report both absolute and relative changes. A relative percentage without the baseline can be difficult to interpret.
Null and Alternative Hypotheses
The null hypothesis represents no difference between variants. The alternative represents a difference. A directional alternative should be justified and chosen before observing the result.
Type I and Type II Errors
| Decision Error | Meaning | Practical Interpretation |
|---|---|---|
| Type I Error | Rejecting a true null hypothesis | Concluding that the treatment had an effect when it did not |
| Type II Error | Failing to reject a false null hypothesis | Missing a real treatment effect |
| Power | Probability of detecting a specified effect when it exists | Ability of the planned experiment to detect the intended improvement |
Understand the P-Value
A p-value measures how surprising the observed result, or a more extreme result, would be if the null hypothesis and statistical assumptions were true.
Confidence Intervals
A confidence interval communicates the estimated effect together with uncertainty. It is usually more informative than a significance label alone.
Questions to Ask
- Does the interval include no effect?
- Does the interval include the minimum useful effect?
- Does it include meaningful harm?
- Is the interval too wide for a confident decision?
- How does uncertainty affect the rollout decision?
Statistical vs Practical Significance
A statistically detectable result may still be too small to justify implementation. The treatment may require engineering work, create support costs, increase latency, or introduce operational risk.
| Question | Statistical View | Practical View |
|---|---|---|
| Is there evidence of a difference? | Hypothesis test and confidence interval | Not sufficient by itself |
| How large is the effect? | Effect estimate | Compare with minimum useful change |
| Is implementation worthwhile? | Statistics provide evidence | Consider cost, risk, maintenance, and strategy |
| Could the change cause harm? | Review uncertainty and guardrails | Apply safety and operational limits |
Minimum Detectable Effect
The minimum detectable effect, commonly abbreviated as MDE, is the effect size the experiment is designed to detect with the selected significance level and statistical power.
Sample-Size Inputs
- Baseline metric level
- Minimum effect worth detecting
- Significance level
- Desired statistical power
- One-sided or two-sided hypothesis
- Expected traffic allocation
- Metric variance
- Experimental-unit definition
- Expected exclusions and data loss
Plan Sample Size in Python
The following example demonstrates sample-size planning for two independent conversion proportions. The values are illustrative rather than universal recommendations.
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
baseline_rate = 0.10
minimum_target_rate = 0.11
effect_size = proportion_effectsize(
baseline_rate,
minimum_target_rate
)
power_analysis = NormalIndPower()
sample_size_per_group = power_analysis.solve_power(
effect_size=effect_size,
alpha=0.05,
power=0.80,
ratio=1.0,
alternative="two-sided"
)
print(
round(sample_size_per_group)
)
Analyze a Binary Conversion Experiment
This example compares two independent conversion proportions using aggregated synthetic results.
import numpy as np
from statsmodels.stats.proportion import proportions_ztest
from statsmodels.stats.proportion import confint_proportions_2indep
control_conversions = 1020
control_users = 10000
treatment_conversions = 1110
treatment_users = 10000
control_rate = (
control_conversions
/ control_users
)
treatment_rate = (
treatment_conversions
/ treatment_users
)
absolute_change = (
treatment_rate
- control_rate
)
relative_change = (
absolute_change
/ control_rate
)
conversion_counts = np.array([
control_conversions,
treatment_conversions
])
sample_sizes = np.array([
control_users,
treatment_users
])
test_statistic, p_value = proportions_ztest(
count=conversion_counts,
nobs=sample_sizes,
alternative="two-sided"
)
confidence_interval = confint_proportions_2indep(
count1=treatment_conversions,
nobs1=treatment_users,
count2=control_conversions,
nobs2=control_users,
method="wald",
compare="diff",
alpha=0.05
)
print("Control rate:", control_rate)
print("Treatment rate:", treatment_rate)
print("Absolute change:", absolute_change)
print("Relative change:", relative_change)
print("Test statistic:", test_statistic)
print("P-value:", p_value)
print("95% confidence interval:", confidence_interval)
Analyze a Continuous Metric
Revenue, order value, session duration, and latency are examples of continuous metrics. Their distributions may be skewed or contain extreme values, so the analysis plan should reflect the metric's behavior.
import numpy as np
from scipy.stats import ttest_ind
rng = np.random.default_rng(42)
control_revenue = rng.gamma(
shape=2.0,
scale=20.0,
size=5000
)
treatment_revenue = rng.gamma(
shape=2.05,
scale=20.0,
size=5000
)
test_statistic, p_value = ttest_ind(
treatment_revenue,
control_revenue,
equal_var=False
)
mean_difference = (
treatment_revenue.mean()
- control_revenue.mean()
)
print(
"Control mean:",
control_revenue.mean()
)
print(
"Treatment mean:",
treatment_revenue.mean()
)
print(
"Mean difference:",
mean_difference
)
print(
"P-value:",
p_value
)
Run an A/A Test
An A/A test sends both groups to the same experience while retaining the experiment assignment and measurement pipeline.
What an A/A Test Can Reveal
- Broken or biased assignment
- Unexpected sample-ratio differences
- Variant-specific logging behavior
- Inconsistent metric calculation
- Unstable experiment infrastructure
- Unexpected false-positive behavior across repeated tests
Sample-Ratio Mismatch
Sample-ratio mismatch occurs when observed variant counts differ unexpectedly from the planned allocation beyond plausible random variation.
Possible Causes
- Assignment-service errors
- Variant-specific crashes or redirects
- Missing exposure events
- Eligibility applied after assignment
- Bot or employee filtering applied inconsistently
- Cross-device identity differences
- Data-pipeline loss for one variant
Repeated Peeking and Early Stopping
Repeatedly checking a conventional fixed-horizon test and stopping as soon as significance appears can increase false-positive risk.
Multiple Testing
Testing many metrics, variants, subgroups, and hypotheses increases the chance that at least one apparently positive result occurs by chance.
Risk Controls
- Declare one primary decision metric
- Limit unnecessary variant and subgroup searches
- Separate confirmatory analysis from exploration
- Apply an appropriate multiplicity adjustment where required
- Report the complete family of tested outcomes
- Treat unplanned subgroup findings as hypotheses for future validation
Novelty and Carryover Effects
| Effect | Meaning | Risk |
|---|---|---|
| Novelty Effect | Users react temporarily because an experience is new | Short-term lift may not persist |
| Learning Effect | Users need time to understand a changed experience | Early performance may understate later value |
| Carryover Effect | Previous treatment exposure affects later behavior | Switching variants may contaminate comparison |
| Seasonal Effect | Behavior changes with recurring calendar or business conditions | An unrepresentative period may distort conclusions |
Interference and Network Effects
Standard analysis often assumes that one unit's treatment does not change another unit's outcome. This assumption can fail in social networks, marketplaces, collaborative tools, games, and shared accounts.
A/B Testing Machine Learning Systems
A model can improve offline accuracy but fail to improve the product outcome. It may increase latency, reduce diversity, change user behavior, or optimize a proxy that does not represent long-term value.
| Layer | Example Comparison | Possible Metrics |
|---|---|---|
| Model | Existing model vs candidate model | Business outcome, latency, errors |
| Ranking | Existing ranking logic vs new objective | Engagement, conversion, diversity |
| Threshold | Existing decision threshold vs proposed threshold | Outcome value, review workload, harmful errors |
| Interface | Prediction hidden vs prediction shown | Adoption, decision quality, overrides |
| Fallback | Default behavior vs alternative fallback | Reliability, recovery, user impact |
Recommended Experiment Workflow
Define the Decision
State what decision will be made from the result and who owns it.
Write the Hypothesis
Define the treatment, population, mechanism, expected outcome, and direction before launch.
Define Metrics
Specify the primary metric, guardrails, diagnostic metrics, units, windows, and calculation rules.
Plan the Experiment
Choose the experimental unit, allocation, MDE, power, significance level, sample requirement, and stopping rule.
Validate Instrumentation
Test assignment, exposure logging, metric pipelines, exclusions, and variant delivery before broad launch.
Launch Safely
Increase exposure according to the operational plan while monitoring safety, reliability, and data-quality guardrails.
Analyze the Result
Review assignment quality, metric validity, effect estimates, confidence intervals, guardrails, and sensitivity analyses.
Make and Record the Decision
Document whether to ship, reject, modify, repeat, or investigate, together with the supporting evidence and limitations.
Monitor After Rollout
Confirm that the effect and guardrails remain acceptable after broader deployment.
Common Experimentation Mistakes
Experiment Decision Record
| Information | What to Record |
|---|---|
| Problem | Decision, opportunity, and affected population |
| Hypothesis | Treatment, mechanism, metric, and expected direction |
| Variants | Exact control and treatment definitions |
| Assignment | Experimental unit, allocation, persistence, and eligibility |
| Metrics | Primary, secondary, guardrail, and data-quality definitions |
| Statistics | MDE, significance level, power, sample plan, and test method |
| Quality Checks | Assignment, exposure, missingness, and sample-ratio validation |
| Results | Variant values, absolute effect, relative effect, interval, and p-value |
| Decision | Ship, reject, modify, repeat, or investigate |
| Limitations | Uncertainty, threats to validity, and open questions |
| Follow-Up | Rollout monitoring and future experiments |
Hands-On Practice
Write an Experiment Hypothesis
Choose a product or model change and define the population, mechanism, primary outcome, and expected direction.
Define the Metrics
Document the numerator, denominator, unit, window, exclusions, and guardrails.
Choose the Experimental Unit
Determine whether randomization should occur by user, account, session, store, region, cluster, or time block.
Plan Sample Size
Select the baseline, MDE, significance level, power, allocation, and analysis method.
Analyze Synthetic Results
Calculate variant metrics, absolute change, relative change, confidence interval, and p-value.
Review Experiment Quality
Check sample allocation, missing exposure records, variant delivery, exclusions, and guardrails.
Write the Decision
State whether to ship, reject, repeat, modify, or investigate, and explain the evidence and uncertainty.
Knowledge Check
What distinguishes an A/B test from an observational comparison?
Explain the role of controlled random assignment.
What is an experimental unit?
Explain how it relates to assignment, independence, and analysis.
Why should the primary metric be defined before launch?
Explain how post-result metric selection can create misleading evidence.
What does a p-value measure?
Explain its meaning under the null hypothesis without treating it as the probability that the null is true.
Why is a confidence interval useful?
Explain how it communicates effect direction, magnitude, and uncertainty.
What is the minimum detectable effect?
Explain how it connects business value with sample-size planning.
Why is repeatedly peeking at a fixed-horizon test dangerous?
Explain how opportunistic stopping can increase false positives.
What is sample-ratio mismatch?
Explain why unexplained allocation differences threaten trust in the experiment.
Why might an offline model improvement fail online?
Consider user response, latency, error costs, proxy metrics, system interactions, and changing feedback.
Why should guardrails be reviewed before shipping?
Explain why improving one metric does not justify unacceptable harm elsewhere.
Lesson Summary
| Concept | Main Point |
|---|---|
| A/B Test | Controlled comparison between randomly assigned experiences |
| Control | Current or baseline experience |
| Treatment | Proposed changed experience |
| Experimental Unit | Entity independently assigned to a variant |
| Primary Metric | Main outcome used for the experiment decision |
| Guardrail | Metric used to detect unacceptable harm |
| Null Hypothesis | Represents no treatment difference |
| P-Value | Measures result extremity under the null and assumptions |
| Confidence Interval | Communicates effect estimate and uncertainty |
| Power | Probability of detecting a specified effect when it exists |
| MDE | Smallest effect the experiment is planned to detect |
| Sample-Ratio Mismatch | Unexpected difference between planned and observed allocation |
| Multiple Testing | Testing many outcomes increases false-discovery risk |
| Practical Significance | Assesses whether the effect is valuable enough to act upon |
| Online Model Test | Measures real-system impact rather than offline score alone |
Key Takeaway
A trustworthy A/B test starts with a clear decision, testable hypothesis, valid experimental unit, random assignment, predefined metrics, justified sample plan, and reliable instrumentation. Results should be interpreted using effect sizes, uncertainty, guardrails, practical value, and operational risks. Statistical significance alone is not enough to justify a rollout.
Get Machine Learning updates by email
Short, practical lessons and course updates from Rumman Ansari. No spam.