A/B Testing for Data Scientists: Design, Analysis and Pitfalls

A practical guide to A/B testing — choosing metrics and guardrails, randomisation, sample size and power, test duration with Indian festival effects, sample ratio checks, analysis with confidence intervals, segments and multiple testing, and the pitfalls that mislead teams — with tested Python code.

Quick Answer: A good A/B test starts before any code runs: a clear hypothesis, one primary metric with guardrails, the right unit of randomisation, a sample size calculated from the smallest effect worth detecting, and a fixed duration covering full weekly cycles. After it runs, check that groups split as designed, report the effect with a confidence interval rather than only a p-value, and decide based on business impact. Most failed experiments fail in design, not analysis.

A/B testing is how product companies decide whether a change actually helps: a new checkout flow, a different recommendation algorithm, a cheaper delivery fee, a reworded push notification. In India, e-commerce, quick commerce, fintech, food delivery and OTT companies run hundreds of experiments a year, and "design an A/B test" is one of the most common data science interview questions.

Our statistics guide introduced hypothesis testing and a simple A/B example. This article goes further: how to design a test properly, how to analyse it, and the pitfalls that lead teams to wrong conclusions. The Python examples were run to confirm they work.

Step 1: Start With a Hypothesis and a Decision

Write down what you are changing, what you expect to happen and why, and what you will do with the result. "Showing the delivery date on product pages will increase add-to-cart rate, because uncertainty about delivery causes drop-off; if it wins by at least 3% we will roll it out to all categories." A hypothesis tied to a decision keeps the test focused and stops people from searching through metrics afterwards for something that looks positive.

Step 2: Choose Metrics Carefully

Metric roleWhat it isExample for a checkout redesign
Primary metricThe one metric the decision rests onCheckout conversion rate
Secondary metricsHelp explain why the primary movedPayment page drop-off, time to complete
Guardrail metricsMust not get worse, even if the primary improvesRefund rate, payment failures, page load time

The primary metric should be sensitive enough to move within the test period and closely tied to the business goal. Revenue per user is often too noisy for short tests; conversion rate or add-to-cart rate may be more practical, with revenue as a secondary metric. Guardrails protect against wins that cause damage elsewhere — a checkout that converts better but doubles payment failures is not a win.

Step 3: Decide the Unit of Randomisation

Usually users are randomly assigned to control or treatment, and stay in their group throughout the test. Randomising by session or page view can expose the same person to both versions and blur the result. Some changes require larger units: a pricing change in a food delivery marketplace can affect restaurants and delivery partners shared by both groups, so tests may be randomised by city or by time period instead. Choosing the unit is a design decision interviewers often probe.

Step 4: Calculate the Sample Size

The required sample depends on the baseline rate, the minimum detectable effect — the smallest change worth acting on — the significance level and the desired power. Smaller effects need far more users. For a conversion rate of 4.0% and a smallest worthwhile lift to 4.4%:

from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize

baseline = 0.040          # current conversion rate: 4.0%
target   = 0.044          # smallest lift worth detecting: 4.4%

effect = proportion_effectsize(target, baseline)
n_per_group = NormalIndPower().solve_power(
    effect_size=effect, alpha=0.05, power=0.80, alternative="two-sided"
)
print(round(n_per_group))

This gives roughly 39,000 users per group at 5% significance and 80% power. If your page gets 10,000 eligible users a day split across two groups, the test needs about eight days — and in practice you would round up to full weeks. If the number is impossibly large, test a bolder change, choose a more sensitive metric, or accept that the test cannot answer the question.

Step 5: Plan the Duration

Run tests for whole weeks so that weekday and weekend behaviour are both represented. Avoid starting or ending during unusual periods unless that period is what you want to learn about. In India this matters more than in many markets: Diwali sales, Big Billion Day–style events, salary weeks at the start of the month, cricket finals and regional festivals can change user behaviour sharply. A test that ran only during a festive sale tells you how the change performs during festive sales, not in normal weeks.

Fix the duration before you start. Deciding to stop when results look good — or to extend when they look bad — is one of the most common ways teams fool themselves.

Step 6: Check the Experiment Is Healthy

Before looking at outcomes, check the sample ratio: if you designed a 50/50 split, the groups should be close to equal. A significant imbalance — a sample ratio mismatch — usually means a bug in assignment, logging or eligibility, and the results cannot be trusted until it is explained. Also check that the treatment was actually delivered, that key events are logged in both groups, and that pre-experiment behaviour looks similar across groups.

Step 7: Analyse the Result

For a conversion metric, a two-proportion test and a confidence interval for the difference are the standard starting point:

from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
from scipy.stats import chisquare

conversions = [1180, 1080]      # treatment, control
visitors    = [25200, 24800]

# 1. sample ratio mismatch check (expected 50/50 split)
srm_p = chisquare(visitors).pvalue

# 2. significance test for the difference in conversion
z, p_value = proportions_ztest(conversions, visitors)

# 3. confidence interval for the difference (treatment minus control)
low, high = confint_proportions_2indep(conversions[0], visitors[0],
                                       conversions[1], visitors[1])
print(f"SRM p={srm_p:.2f}  p-value={p_value:.3f}  CI=({low:.4f}, {high:.4f})")

With these example numbers, treatment converts at about 4.68% and control at about 4.35%. The sample ratio check passes, but the p-value is about 0.08, and the 95% confidence interval for the difference runs from roughly −0.04 to +0.69 percentage points. Notice also that each group has about 25,000 users — fewer than the 39,000 the sample size calculation required.

The right conclusion: the test is inconclusive and underpowered. The change may well help — the point estimate is positive — but the data cannot rule out no effect. The correct action is to continue to the planned sample size, not to declare a win or a loss. Reporting the interval, rather than only "not significant", makes this clear to stakeholders.

Segments, Multiple Metrics and Corrections

After a test, it is tempting to slice results by city, device, new versus returning users and every other dimension until something looks significant. With twenty segments, one will probably cross the 5% line by chance alone. Decide important segments in advance, treat others as exploratory, and use corrections such as Bonferroni or false discovery rate control when testing many comparisons. A surprising segment result is a hypothesis for the next test, not a conclusion.

Common Pitfalls

PitfallWhat goes wrongFix
PeekingChecking daily and stopping when p dips below 0.05 inflates false positivesFix the sample size in advance, or use sequential methods designed for monitoring
Underpowered testsReal effects are missed and "no difference" is wrongly concludedCalculate sample size first; run longer or test bigger changes
Too many metrics or segmentsSome will look significant by chancePre-register the primary metric; correct for multiple comparisons
Sample ratio mismatchGroups are not the size you designed, signalling a bugCheck the split before analysing; investigate assignment and logging
Novelty and learning effectsEarly behaviour differs from long-run behaviourRun full weeks; look at trends over the test period
Interference between usersTreatment affects control users, as in marketplaces or social featuresRandomise by region, time or cluster instead of user

Making Tests More Sensitive

Teams with lots of experiments use techniques to detect smaller effects with the same traffic. Variance reduction methods such as CUPED use each user's pre-experiment behaviour to remove noise from the comparison. Ratio metrics and capping outliers stabilise noisy revenue metrics. Running tests only on users who could actually be affected — those who reached the checkout page, for example — also increases sensitivity. These are good topics to mention in senior interviews.

From Result to Decision

Statistical significance is not the same as business value. A significant 0.1% lift may not justify engineering and maintenance costs; a non-significant result with a promising interval may justify a longer test. Combine the effect size, its uncertainty, guardrail results, implementation cost and strategic fit into a recommendation. Write it up briefly: the hypothesis, design, results with intervals, health checks, decision and what to test next. A clear experiment write-up is one of the most persuasive portfolio pieces a data scientist can show.

A Pre-Launch Checklist

Before switching a test on, confirm: the hypothesis and decision rule are written down; one primary metric and its guardrails are agreed; the randomisation unit is right for the change; the sample size and duration are calculated and fixed; the test avoids, or deliberately targets, festive and sale periods; assignment and event logging have been verified in a small pilot; and the analysis plan, including key segments, is agreed in advance. After launch, check the sample ratio within the first day, then leave the test alone until it reaches its planned size. Teams that follow a short checklist like this avoid most of the mistakes that make experiment results untrustworthy.

When Not to A/B Test

Some decisions cannot or should not be tested this way: legal or compliance changes that must apply to everyone, changes with too little traffic to reach a useful sample, one-off events, or situations where withholding a fix from the control group would harm users. In those cases, careful before-and-after analysis, staged rollouts or quasi-experimental methods such as difference-in-differences are the alternatives.

A/B Testing in Interviews

A classic question: "We want to change the checkout button colour. Design the experiment." A strong answer covers the hypothesis, primary and guardrail metrics, randomisation unit, sample size inputs, duration in full weeks, health checks, the analysis and how you would decide. Follow-ups usually probe peeking, sample ratio mismatch, multiple metrics, novelty effects and what you would do with an inconclusive result. Practise answering aloud with concrete numbers.

Our Data Science course teaches statistics and experimentation through real product scenarios, and the Machine Learning course covers how experiments are used to evaluate models in production.

People Also Ask / FAQ

How long should an A/B test run?

Until it reaches the planned sample size, and for at least one or two full weeks so weekly patterns are covered. Decide this before starting.

What is a minimum detectable effect?

The smallest change in the metric that would be worth acting on. It drives the sample size: smaller effects need many more users.

What does a p-value of 0.08 mean in an A/B test?

If there were truly no difference, a result at least this extreme would occur about 8% of the time. It is not strong enough evidence at the usual 5% level, but it is not proof of no effect either.

Can I test more than two versions at once?

Yes, in an A/B/n test, but each extra variant needs more traffic and increases the risk of false positives, so adjust sample size and corrections accordingly.

Is A/B testing only for product companies?

It is most common there, but banks, insurers, retailers and marketing teams also test offers, messages, pricing and processes.

Learn Experimentation the Way Product Teams Use It

Live classes, real projects and interview practice — online and in select cities across India Explore the Data Science Course