A/B Testing and Offline vs. Online Metrics in Machine Learning Systems

A classic frustration in applied machine learning happens right after launch: your new model improves offline validation ROC-AUC by 3.5% and reduces Log Loss in experiments, yet once deployed to production, user click-through rates drop and revenue stalls.

This disconnect occurs because offline proxy metrics measure statistical performance on historical data, whereas online business metrics measure real human behavior in dynamic production environments.

A model can predict historical outcomes more accurately without creating a better user experience. It may also introduce additional latency, change what users see, or influence future data in ways that a static test dataset cannot capture.

To bridge the gap between model development and production impact, ML engineers combine rigorous offline evaluation with controlled online experimentation, especially A/B testing.

In this guide, we will explore offline and online metrics, why their results sometimes disagree, how randomized A/B tests work, how to interpret statistical significance, and how to build a reliable experimentation workflow for production ML systems.


1. Offline Metrics: Fast, Safe, and Static

Offline evaluation measures a model's performance using previously collected data before the model is exposed to real production users.

The dataset is generally divided into training, validation, and test sets. After training, the candidate model makes predictions on held-out data, and evaluation metrics quantify how well those predictions match the known outcomes.

For example, an e-commerce company may evaluate a recommendation model using historical user interactions:

  • User A viewed a laptop.
  • User A clicked a particular laptop recommendation.
  • User B purchased a smartphone.
  • User B ignored several other recommendations.

The model predicts which items users might interact with, and its predictions are compared with the recorded outcomes.

Common offline metrics

Problem typeCommon metricsWhat they measure
ClassificationAccuracy, Precision, Recall, F1Classification quality at a selected threshold
ClassificationROC-AUC, PR-AUCRanking ability across thresholds
ClassificationLog Loss, Brier ScoreQuality of predicted probabilities
RegressionMAE, RMSE, R²Prediction error and explained variance
RankingNDCG@K, MRR, MAPQuality of ranked results
RetrievalRecall@K, Precision@KWhether relevant items appear in retrieved candidates

The correct metric depends on the business problem. For example, PR-AUC may be more informative than accuracy for rare fraud events, while NDCG@K is useful when the order of search results matters.

Strengths of offline evaluation

  1. Fast feedback: Models can be evaluated in seconds or minutes, depending on dataset size.
  2. Low production risk: Experiments do not directly affect live users.
  3. Reproducibility: The same dataset and evaluation procedure can be used to compare model versions.
  4. Cost efficiency: Candidate models can be tested before spending resources on production deployment.
  5. Model selection: Engineers can compare architectures, hyperparameters, and feature sets.

Limitations of offline evaluation

Offline evaluation is essential, but it does not reproduce every aspect of a live production environment.

  • Historical data limitations: The dataset reflects previous user behavior and the previous recommendation or ranking policy.
  • Exposure bias: Historical logs generally contain outcomes only for items that users were actually shown.
  • Feedback loops: A deployed model changes what users see, which can change future behavior and training data.
  • Latency effects: A model can perform better statistically but respond too slowly for the application.
  • Novelty effects: Users may react differently to a new interface or recommendation strategy than historical data suggests.
  • Business trade-offs: Better predictions do not necessarily translate into increased revenue, retention, or customer satisfaction.

Important: A model's offline test score is evidence about performance on a particular evaluation dataset. It is not a guarantee of production success.


2. Online Metrics: Measuring Real Business Impact

Online evaluation measures how a model performs when it interacts with real users, real traffic, and the surrounding production system.

Instead of asking only whether predictions match historical labels, online evaluation asks:

  • Do users click the recommendations?
  • Do they complete purchases?
  • Do they spend more time using the product?
  • Does the new search model help users find relevant results?
  • Does the system remain responsive?
  • Does the change improve business outcomes without harming customer trust?

Three tiers of online metrics

1. Overall Evaluation Criterion (OEC) or North Star KPI

The OEC is the primary metric used to evaluate whether an experiment creates meaningful value.

Examples:

ProductPossible primary metric
E-commerceRevenue per eligible user or purchase conversion
Video streamingQualified watch time per user
Search engineSuccessful search-session rate
Subscription serviceRetention or renewal rate
Advertising platformRevenue per eligible session
BankingSuccessful transaction rate, subject to risk controls

A good OEC should represent a meaningful product or business outcome rather than merely an easily measured intermediate action.

For example, increasing clicks is not necessarily valuable if those clicks do not lead to useful content or successful purchases.

2. Engagement and proxy metrics

Proxy metrics are intermediate signals that can provide faster feedback than long-term business outcomes.

Examples include:

  • Click-through rate (CTR)
  • Add-to-cart rate
  • Search-result interaction rate
  • Product-detail views
  • Session duration
  • Video completion rate
  • Zero-result search rate

These metrics help explain how users respond to a change.

However, proxy metrics should not automatically replace the primary business objective.

3. Guardrail metrics

Guardrails define boundaries that should not be violated while optimizing the primary metric.

Technical guardrails

  • P95 and P99 inference latency
  • API error rate
  • Timeout rate
  • CPU and GPU utilization
  • Memory consumption
  • Page-load performance

Business and trust guardrails

  • Unsubscribe rate
  • Customer complaints
  • Refund or cancellation rate
  • Churn rate
  • Spam reports
  • Failed transactions
  • User abandonment

For example, suppose a new recommendation model increases revenue per user by 1%, but also increases P99 latency from 80 ms to 450 ms. That latency increase may damage the experience enough to make the deployment undesirable.

Guardrails help prevent teams from optimizing one metric at the expense of the entire product.


3. Offline vs. Online Metrics: Key Differences

DimensionOffline evaluationOnline evaluation
EnvironmentHistorical datasetLive production traffic
TimingBefore deploymentDuring or after deployment
UsersNo new live interaction requiredReal users
CostUsually lowerCan involve production and experimentation costs
RiskLow direct user riskCan affect user experience and revenue
ReproducibilityGenerally high with fixed dataAffected by changing traffic and behavior
Feedback loopsUsually not capturedCan be observed over time
LatencyCan be measured in benchmarksMeasured under real system conditions
Main purposeAssess predictive qualityAssess real-world impact

The two approaches are complementary.

Offline evaluation filters out weak candidates. Online experiments help determine whether promising candidates create measurable production value.


4. Why Offline Improvements Sometimes Fail Online

A model can improve offline metrics and still fail to improve production outcomes for several reasons.

1. Proxy metric and business objective misalignment

Suppose a video recommendation model is optimized for CTR.

The model learns to recommend sensational videos that attract clicks. Users click frequently but leave after a few seconds.

The result:

  • CTR increases.
  • Average watch time decreases.
  • User satisfaction may decline.
  • Long-term retention may suffer.

The model optimized the proxy metric but failed to improve the broader business objective.

Lesson: Choose offline and online metrics that are connected to the actual product goal.

2. Latency and system overhead

A larger neural network may improve offline ROC-AUC by 0.5%, but introduce 180 ms of additional inference latency.

That extra delay can affect:

  • Page rendering
  • Search response time
  • Recommendation loading
  • Mobile user experience
  • Request timeout rates

A model should be evaluated not only for predictive quality but also for serving performance.

3. Counterfactual and selection bias

Imagine a recommendation platform that historically displays only five products to each user.

The logs record clicks and purchases for those five displayed products. They do not reveal what would have happened if the platform had shown five different products.

This creates a counterfactual problem: the outcomes of unshown items are unknown.

The new model may recommend products that the old model rarely displayed. A simple offline comparison may incorrectly treat missing interactions as negative feedback.

This problem is closely related to exposure bias and selection bias.

Possible approaches include:

  • Logging item exposure and ranking position.
  • Recording the probability that an item was selected or displayed, when the serving policy supports it.
  • Using inverse propensity scoring (IPS).
  • Using self-normalized IPS (SNIPS).
  • Using doubly robust estimators.
  • Running carefully designed randomized experiments to collect additional evidence.

These methods rely on assumptions about the logging policy, exposure, and available data. They do not automatically eliminate bias.

4. Feedback loops and cannibalization

A recommendation model may promote high-margin products in a prominent widget.

The widget generates more clicks, but customers simply purchase those products instead of buying them through another part of the platform.

The widget's local performance improves, while the platform's total revenue remains unchanged.

This is called a form of cannibalization.

It illustrates why teams should measure outcomes across the relevant user journey or business system rather than optimizing an isolated component.

5. Training-serving skew

A model may be trained using features that are calculated differently in production.

For example:

  • Training uses a user's average purchase value over the previous 30 days.
  • Production accidentally uses the previous 7 days.
  • Training fills missing values with the median.
  • Production replaces missing values with zero.

Even a strong offline model can perform poorly when its production inputs do not match the training pipeline.

6. Distribution changes and delayed outcomes

User behavior, product availability, seasonality, and market conditions can change after training.

Additionally, some business outcomes take time to become observable.

For example, a recommendation may influence a subscription renewal several weeks later. A short experiment may capture clicks but not retention.

This is why experiment duration and outcome measurement windows should match the behavior being studied.


5. A/B Testing: The Foundation of Controlled Online Experiments

An A/B test is a randomized controlled experiment that compares two variants under comparable conditions.

  • Control group (A): Receives the existing production model or experience.
  • Treatment group (B): Receives the new candidate model or experience.

Users are randomly assigned to one of the groups. The team then compares predefined outcomes between the groups.

Basic A/B testing architecture

                  Incoming Production Traffic
                              |
                              v
                   Randomized Assignment
                              |
                  +-----------+-----------+
                  |                       |
                  v                       v
          CONTROL GROUP (A)       TREATMENT GROUP (B)
          Existing ML Model       New Candidate Model
                  |                       |
                  v                       v
          Record User Events       Record User Events
                  |                       |
                  +-----------+-----------+
                              |
                              v
                     Metric Aggregation
                              |
                              v
                  Statistical Analysis
                              |
                              v
                 Business Decision / Rollout

The key idea is that both groups operate during the same period, so they experience broadly similar external conditions.

For example, if a shopping platform runs an experiment during a holiday sale, both groups are exposed to the same general promotional environment.

Random assignment helps make the groups comparable on average, including for factors that the team has not explicitly measured.

Example: Testing a new recommendation model

Suppose an e-commerce platform wants to compare its existing recommendation model with a new model.

PropertyControl (A)Treatment (B)
Traffic allocation50%50%
Recommendation modelExisting modelNew model
Primary metricRevenue per userRevenue per user
Secondary metricCTRCTR
GuardrailsLatency, errors, refundsLatency, errors, refunds

Assume the experiment produces the following illustrative results:

MetricControl (A)Treatment (B)
Eligible users10,00010,000
Click-through rate8.0%8.5%
Conversion rate3.0%3.2%
Revenue per user₹120₹124
P95 inference latency75 ms82 ms

The relative CTR improvement is:

\[ \frac{8.5-8.0}{8.0}\times100=6.25\% \]

The relative conversion improvement is:

\[ \frac{3.2-3.0}{3.0}\times100\approx6.67\% \]

The relative revenue-per-user improvement is:

\[ \frac{124-120}{120}\times100\approx3.33\% \]

These results look promising, but they are not enough to declare the treatment successful.

The team must also examine:

  • Statistical uncertainty
  • Confidence intervals
  • Whether the sample size was sufficient
  • Whether the metrics were instrumented correctly
  • Whether latency and other guardrails remained acceptable
  • Whether the improvement is practically meaningful

The example numbers are illustrative, not evidence of a statistically significant result.


6. Statistical Hypothesis Testing in A/B Experiments

A/B testing uses statistical methods to determine whether the observed difference between two groups is consistent with a real treatment effect or could reasonably have occurred due to random variation.

Step 1: Define the hypotheses

Suppose the objective is to determine whether the new model increases conversion rate.

Null hypothesis (H₀):

\[ H_0:p_B=p_A \]

There is no difference in the conversion rates of the control and treatment groups.

Alternative hypothesis (H₁):

\[ H_1:p_B\neq p_A \]

There is a difference between the conversion rates.

If the experiment is explicitly designed to test an increase, a one-sided alternative may be appropriate:

\[ H_1:p_B>p_A \]

The choice between one-sided and two-sided testing should be made before examining the results.

Step 2: Choose a significance level

A common significance level is:

\[ \alpha=0.05 \]

This means that, under the null hypothesis and the assumptions of the statistical test, the procedure has a 5% probability of rejecting the null hypothesis.

It does not mean there is a 95% probability that the treatment is better.

Step 3: Calculate the p-value

The p-value measures how unusual the observed data, or data more extreme, would be under the null hypothesis and the statistical model.

A simplified decision rule is:

ResultConventional interpretation
p-value < 0.05Reject the null hypothesis at the 5% significance level
p-value ≥ 0.05Insufficient evidence to reject the null hypothesis

A non-significant result does not prove that the two models are identical. The experiment may be underpowered or the actual effect may be too small to detect.

Step 4: Examine the effect size

Statistical significance alone is not enough.

Suppose the new model increases conversion rate from 3.00% to 3.02%.

With a sufficiently large sample, this small difference might be statistically significant.

However, the improvement may not justify the cost of deploying and maintaining a more complex model.

Teams should examine:

  • Absolute improvement
  • Relative improvement
  • Confidence interval
  • Expected business value
  • Infrastructure and operational costs

Statistical significance answers whether the observed difference is difficult to explain by random variation under the null model. Practical significance asks whether the difference is worth acting on.


7. Sample Size and Statistical Power

A/B experiments need enough observations to detect the effect the team cares about.

Running an experiment with too few users can produce an inconclusive result even when a meaningful improvement exists.

Four important concepts are:

  1. Baseline rate: The existing conversion rate or other metric.
  2. Minimum Detectable Effect (MDE): The smallest effect the experiment is designed to detect.
  3. Significance level (α): The tolerated Type I error rate.
  4. Statistical power (1 − β): The probability of detecting the specified effect when it truly exists, under the planning assumptions.

Common planning values are:

  • Significance level: 5%
  • Statistical power: 80%
  • MDE: Defined according to business value and experiment cost

Approximate sample-size formula for two conversion rates

For equal-sized groups, a commonly used approximate planning formula is:

\[ n\approx \frac{ 2(z_{1-\alpha/2}+z_{1-\beta})^2\bar p(1-\bar p) }{ \Delta^2 } \]

Where:

  • \(n\) = approximate sample size per group
  • \(\bar p\) = assumed average conversion rate
  • \(\Delta\) = minimum absolute difference to detect
  • \(z_{1-\alpha/2}\) = critical value for the significance level
  • \(z_{1-\beta}\) = critical value for the desired power

This is an approximation for a two-sided comparison of independent proportions with equal allocation. More precise planning may use software that accounts for the selected test and assumptions.

Python example: Sample-size planning

The statsmodels package can estimate the sample size required for a two-proportion experiment.

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

# Existing conversion rate
control_rate = 0.03

# Minimum conversion rate worth detecting
treatment_rate = 0.033

# Convert the two rates into an effect size
effect_size = proportion_effectsize(
    control_rate,
    treatment_rate
)

# Configure statistical power
analysis = NormalIndPower()

sample_size = analysis.solve_power(
    effect_size=effect_size,
    power=0.80,
    alpha=0.05,
    ratio=1.0,
    alternative="two-sided"
)

print("Required sample size per group:", round(sample_size))

The calculation estimates how many independent observations each group needs under the specified assumptions.

Real experiments may require more traffic because of:

  • Missing or invalid event data
  • Unequal traffic allocation
  • Repeated measurements
  • User-level clustering
  • Multiple comparisons
  • Delayed outcome measurement
  • Variance in revenue or other noisy metrics

Always calculate sample size before launching the experiment rather than stopping when the result first looks favorable.


8. Running an A/B Test in Python

The following simplified example compares conversion rates for two independent groups.

from statsmodels.stats.proportion import proportions_ztest

# Number of users who converted
conversions = [300, 320]

# Total users in each group
users = [10000, 10000]

# Two-proportion z-test
z_stat, p_value = proportions_ztest(
    count=conversions,
    nobs=users,
    alternative="two-sided"
)

control_rate = conversions[0] / users[0]
treatment_rate = conversions[1] / users[1]

print("Control conversion rate:", control_rate)
print("Treatment conversion rate:", treatment_rate)
print("Z-statistic:", z_stat)
print("P-value:", p_value)

if p_value < 0.05:
    print("Statistically significant difference")
else:
    print("Insufficient evidence of a difference")

The conversion rates are:

\[ p_A=\frac{300}{10000}=0.03 \]

\[ p_B=\frac{320}{10000}=0.032 \]

Absolute improvement:

\[ 0.032-0.03=0.002 \]

This is an increase of 0.2 percentage points.

Relative improvement:

\[ \frac{0.032-0.03}{0.03}\times100 \approx6.67\% \]

The code performs a two-sided test for a difference in proportions. It does not account for every possible production-experiment issue, such as clustering, repeated peeking, or multiple testing.

A production experiment should also report a confidence interval for the treatment effect and verify that the test's assumptions are appropriate.


9. Common A/B Testing Mistakes

A statistically valid experiment can still produce a misleading conclusion if it is designed or operated incorrectly.

1. Peeking at results repeatedly

Suppose a team checks the p-value every hour and stops the experiment as soon as it falls below 0.05.

Repeatedly testing the same data without a suitable sequential-testing procedure increases the probability of false positives.

Better approach:

  • Define the sample size and stopping rule in advance.
  • Use a fixed-horizon design when appropriate.
  • If continuous monitoring and early stopping are necessary, use a valid sequential-testing method or alpha-spending approach.

2. Sample Ratio Mismatch (SRM)

A 50:50 experiment is expected to allocate approximately equal numbers of eligible users to both groups.

Suppose the final assignment counts are:

  • Control: 7,000 users
  • Treatment: 3,000 users

This unexpected imbalance may indicate an implementation or logging problem.

Possible causes include:

  • Incorrect randomization
  • Broken assignment logic
  • Missing event records
  • Filtering differences between variants
  • Users being excluded from one group

This issue is called Sample Ratio Mismatch (SRM).

Investigate the assignment and logging pipeline before trusting the experiment results.

3. Changing the experiment during execution

Changing the model, eligibility criteria, primary metric, or traffic allocation halfway through an experiment can make interpretation difficult.

Keep experiment versions and configuration changes auditable. If a material change is required, consider restarting the experiment or using a design that explicitly accounts for it.

4. Running too many experiments without correction

If a team tests many hypotheses, some may appear significant simply by chance.

For example, running 20 independent tests at a 5% significance level increases the chance of at least one false positive.

Possible approaches include:

  • Bonferroni correction
  • Holm correction
  • False Discovery Rate (FDR) procedures

The right correction depends on whether the metrics are confirmatory, exploratory, or part of a larger experiment program.

5. Ignoring novelty and seasonal effects

Users may initially react positively or negatively to a new interface simply because it is unfamiliar.

Similarly, a promotion, holiday, or major external event can influence the results.

Run both variants concurrently and long enough to capture relevant usage cycles. For long-term outcomes, consider follow-up measurement after the initial experiment.

6. Randomizing at the wrong level

If users interact repeatedly with the product, assigning different variants to the same user across sessions can create contamination.

For example, a user may see the old recommendation model on a mobile session and the new model on a desktop session.

For many recommendation and personalization experiments, stable user-level assignment is preferable.

The randomization unit should match the experiment's interference and exposure structure. Marketplace, network, or social-product experiments may require cluster-level or other specialized designs.

7. Ignoring guardrail failures

A model should not be declared successful solely because the primary KPI improves.

If revenue increases but server errors, latency, refunds, or complaints rise sharply, the treatment may be unacceptable.

Guardrails should be defined before launch, with clear thresholds and operational responses.


10. Advanced Experimentation Techniques

A/B testing is foundational, but production ML systems sometimes require additional experimental methods.

1. Multivariate testing

Instead of testing only one change, a multivariate experiment evaluates multiple factors or combinations of factors.

For example:

  • Recommendation model version
  • Ranking strategy
  • UI layout
  • Number of recommendations displayed

This can reveal interactions between changes, but it usually requires more traffic and careful experimental design.

2. Multi-Armed Bandits

A Multi-Armed Bandit (MAB) allocates traffic among alternatives while learning which option performs better.

Unlike a traditional fixed-allocation A/B test, a bandit can gradually direct more traffic toward promising variants.

Common algorithms include:

  • Epsilon-Greedy
  • Upper Confidence Bound (UCB)
  • Thompson Sampling

Bandits can be useful for ongoing optimization, but adaptive allocation complicates causal interpretation. They are not automatically a replacement for a properly designed A/B test.

3. Interleaving experiments

Interleaving is especially useful for comparing search and ranking systems.

Instead of assigning an entire user to one ranking system, the experiment combines results from two rankers in a single result list using a defined interleaving method.

User interactions can then provide evidence about relative ranking preferences.

Interleaving can be more traffic-efficient for some ranking comparisons, but it measures a different outcome from a conventional user-level A/B test.

4. Switchback experiments

In marketplaces and systems where users or providers influence one another, individual randomization may create interference.

A switchback experiment alternates between variants across predefined time blocks or geographic regions.

For example, a delivery platform might use one pricing or matching policy during one time block and another policy during a later block.

The design must account for time trends, carryover effects, and appropriate block randomization.

5. CUPED: Reducing Variance

CUPED stands for Controlled-experiment Using Pre-Experiment Data.

It uses a correlated pre-experiment measurement to reduce the variance of an experiment metric.

A simplified adjusted outcome is:

\[ Y_{\text{adjusted}}=Y-\theta(X-\bar X) \]

Where:

  • \(Y\) = outcome measured during the experiment
  • \(X\) = a correlated pre-experiment metric
  • \(\bar X\) = average pre-experiment metric
  • \(\theta\) = adjustment coefficient

When the pre-experiment metric is strongly correlated with the experiment outcome and the assumptions hold, CUPED can improve statistical power without requiring more users.

For example, a user's purchase activity before an experiment may help explain their purchase activity during the experiment.


11. Offline Counterfactual Evaluation for Recommendation and Ranking

Online A/B testing can be expensive or risky, so teams often want to estimate how a new policy might perform using historical interaction logs.

This is known as off-policy evaluation or counterfactual evaluation.

Suppose the old recommendation policy selected an item with probability \(p_i\), and the new policy would select that item with probability \(q_i\).

An inverse propensity scoring estimator can reweight observed outcomes:

\[ \hat V_{\text{IPS}}= \frac{1}{N}\sum_{i=1}^{N} \frac{q_i}{p_i}r_i \]

Where:

  • \(N\) = number of logged observations
  • \(p_i\) = probability of the logged action under the behavior policy
  • \(q_i\) = probability of that action under the target policy
  • \(r_i\) = observed reward

The weight \(q_i/p_i\) adjusts for the fact that some actions were more likely to be selected by the logging policy than others.

Why IPS can be difficult

  • Very small propensities can create extremely large weights.
  • The logging policy's action probabilities must be available or reliably estimated.
  • The target policy must have sufficient support in the logged data.
  • Unobserved confounding or incorrect logging can invalidate conclusions.

Self-normalized IPS can reduce some variance:

\[ \hat V_{\text{SNIPS}}= \frac{ \sum_i w_i r_i }{ \sum_i w_i } \]

where \(w_i=q_i/p_i\).

Doubly robust methods combine a reward model with propensity-based correction and can remain consistent if at least one of the two relevant models is correctly specified under the method's assumptions.

These techniques can reduce experimentation costs, but they should not be treated as universal substitutes for online experiments.


12. Building a Production ML Experimentation Workflow

A reliable experimentation process connects model development, evaluation, deployment, and business measurement.

Step 1: Define the business objective

Start with the problem the model is supposed to solve.

Examples:

  • Increase successful purchases.
  • Improve search relevance.
  • Reduce fraudulent transactions.
  • Improve customer retention.
  • Reduce the time required to find relevant content.

Choose one primary metric that represents the objective.

Step 2: Evaluate offline

Evaluate the candidate model using an appropriate held-out dataset.

Check:

  • Predictive metrics
  • Performance across important user segments
  • Calibration, where probability estimates matter
  • Robustness and data quality
  • Latency and resource benchmarks
  • Potential training-serving skew

Use temporally appropriate splits when the application involves time-dependent data.

Step 3: Define the experiment

Specify:

  • Control and treatment variants
  • Randomization unit
  • Eligible population
  • Traffic allocation
  • Primary metric
  • Secondary metrics
  • Guardrails
  • Minimum Detectable Effect
  • Sample size and experiment duration
  • Stopping rules
  • Analysis method

Pre-registering these choices reduces the temptation to select whichever metric looks favorable after seeing the results.

Step 4: Deploy safely

A candidate model can first be deployed using a limited rollout or shadow deployment.

Shadow deployment: The candidate receives production inputs and generates predictions, but its predictions do not control the user experience.

This can help validate:

  • Input compatibility
  • Prediction outputs
  • Latency
  • Resource consumption
  • Error handling

Shadow deployment does not measure the candidate's causal business impact because users are not actually exposed to its decisions.

Step 5: Randomize and collect data

Assign eligible users to variants using a stable, auditable assignment mechanism.

For user-level experiments, a deterministic hash can help keep assignment consistent:

import hashlib

def assign_variant(user_id):
    value = hashlib.sha256(
        str(user_id).encode()
    ).hexdigest()

    bucket = int(value[:8], 16) % 100

    if bucket < 50:
        return "control"

    return "treatment"


print(assign_variant("user_101"))

This example demonstrates deterministic 50:50 assignment. A real system must also manage experiment identifiers, eligibility, user identity, assignment persistence, and mutually exclusive experiment layers where necessary.

Step 6: Monitor the experiment

Track the following throughout the experiment:

Monitoring areaExample metrics
AssignmentGroup counts, allocation ratio, SRM
BusinessConversion, revenue per user, retention
EngagementCTR, watch time, add-to-cart rate
TechnicalP95/P99 latency, errors, timeouts
Data qualityMissing features, invalid events, duplicate records
Safety and trustComplaints, refunds, unsubscribe rate

Do not confuse continuous operational monitoring with repeatedly testing for statistical significance. The experiment should follow its predefined statistical stopping procedure.

Step 7: Analyze and decide

At the end of the experiment:

  1. Validate assignment and instrumentation.
  2. Check sample-ratio consistency.
  3. Calculate treatment effects.
  4. Report confidence intervals and p-values.
  5. Evaluate the primary metric.
  6. Inspect guardrails and important segments.
  7. Assess business value and operational cost.
  8. Decide whether to roll out, iterate, or reject the candidate.

Step 8: Gradually roll out the winning model

A successful experiment may justify a staged rollout:

Offline Evaluation
       |
       v
Shadow Deployment
       |
       v
A/B Test (Small Eligible Traffic)
       |
       v
Experiment Analysis
       |
       v
10% Rollout
       |
       v
50% Rollout
       |
       v
100% Rollout
       |
       v
Continuous Production Monitoring

The rollout percentages are illustrative. The actual schedule should reflect risk, traffic volume, and the ability to detect problems.

Maintain a rollback path so the team can restore the previous model if production behavior deteriorates.


13. Offline and Online Metrics in Different ML Applications

The appropriate metrics depend on the application's objective.

ML applicationOffline metricsOnline metrics
RecommendationRecall@K, NDCG@K, MAPCTR, qualified watch time, revenue per user
Fraud detectionPR-AUC, Recall, Precision, calibrationFraud loss, false-decline rate, approval rate
Search rankingNDCG@K, MRR, Recall@KSuccessful search rate, reformulation rate, conversion
ClassificationF1, ROC-AUC, PR-AUC, Log LossTask completion, customer outcomes, error rate
AdvertisingAUC, Log Loss, calibrationRevenue per impression, conversion value, advertiser outcomes
ForecastingMAE, RMSE, MAPE where appropriateStockout rate, service level, planning cost

A few examples illustrate why both forms of evaluation matter.

Fraud detection: An offline model may achieve higher recall, but if it also blocks too many legitimate transactions, online approval rates and customer experience can deteriorate.

Search ranking: A model may improve NDCG on historical judgments, but live users may still struggle if the new ranking increases latency or surfaces less useful results.

Recommendation: A model may increase clicks while reducing purchases or long-term engagement.

The offline metric tells the team whether the model learned useful patterns. The online metric tells the team whether those patterns improve the actual product.


14. Best Practices for Reliable ML Experimentation

  1. Start with a clear business objective. Do not choose a metric merely because it is easy to optimize.
  2. Use offline evaluation as a screening process. Avoid exposing obviously weak or unsafe candidates to users.
  3. Choose a meaningful primary metric. Keep secondary metrics separate so the experiment remains interpretable.
  4. Define guardrails before deployment. Include technical, business, and user-trust constraints.
  5. Calculate sample size in advance. Base it on baseline performance, MDE, significance level, and desired power.
  6. Randomize at an appropriate level. Stable user-level assignment is common, but not universal.
  7. Validate event instrumentation. Missing, duplicated, or incorrectly attributed events can invalidate results.
  8. Check for Sample Ratio Mismatch. Investigate unexpected assignment imbalances.
  9. Avoid unplanned repeated significance testing. Use valid sequential methods if early stopping is required.
  10. Consider seasonality and delayed outcomes. Measure the full outcome window relevant to the business objective.
  11. Report effect sizes and confidence intervals. Do not report only p-values.
  12. Measure production costs. Include inference latency, compute, infrastructure, and maintenance.
  13. Keep experiments reproducible. Version models, data, code, assignment rules, and metric definitions.
  14. Maintain rollback capability. A successful experiment does not eliminate the need for production monitoring.
  15. Monitor after rollout. Production behavior can change even after an experiment ends.

15. Frequently Asked Questions

Q1. What is the difference between offline and online evaluation in machine learning?

Offline evaluation measures a model using historical, held-out data before live deployment. Online evaluation measures real user behavior and business outcomes after the model is exposed to production traffic.

Q2. Why can a model with better ROC-AUC perform worse in production?

ROC-AUC measures ranking discrimination on an evaluation dataset. It does not directly measure business outcomes, latency, exposure effects, user experience, or long-term behavior. A higher ROC-AUC therefore does not guarantee higher revenue or conversion.

Q3. Is A/B testing necessary for every ML deployment?

No. A/B testing is useful when a model change can be evaluated through controlled user or system outcomes and the experiment can be run safely. Some changes are better evaluated using offline tests, shadow deployment, canary releases, operational monitoring, or specialized experimental designs.

Q4. What does a p-value below 0.05 mean?

Under the null hypothesis and the assumptions of the statistical test, a p-value below 0.05 indicates that the observed result would be relatively unusual if there were no effect. It does not mean there is a 95% probability that the new model is better.

Q5. What is the difference between statistical significance and practical significance?

Statistical significance concerns the strength of evidence against a null hypothesis. Practical significance concerns whether the measured effect is large enough to justify action, considering business value, cost, risk, and operational constraints.

Q6. What is Sample Ratio Mismatch?

Sample Ratio Mismatch occurs when the observed allocation of users across experiment groups differs unexpectedly from the intended allocation. It can indicate assignment, eligibility, or logging problems.

Q7. Can a Multi-Armed Bandit replace A/B testing?

Not universally. Bandits can adaptively allocate traffic to promising options and are useful for ongoing optimization. Traditional A/B testing is often easier to interpret for a fixed causal comparison. The choice depends on the objective and experimental design.

Q8. What is CUPED in experimentation?

CUPED is a variance-reduction technique that uses correlated pre-experiment data to reduce noise in experiment outcomes. When its assumptions hold, it can improve statistical power without requiring additional traffic.

Q9. What are guardrail metrics?

Guardrail metrics are measurements that should remain within acceptable limits while the primary metric is optimized. Examples include inference latency, API errors, refunds, complaints, and churn.

Q10. What should happen after a successful A/B test?

The team should validate the results, review guardrails, assess deployment costs, and gradually roll out the candidate model. Production monitoring and rollback mechanisms should remain active after full deployment.


Conclusion

Offline evaluation and online experimentation solve different but complementary problems in machine learning.

Offline metrics help engineers measure predictive quality, compare candidate models, and identify promising improvements before deployment.

Online metrics reveal how those models affect real users, product performance, and business outcomes.

A/B testing provides a controlled way to estimate the impact of a model change, but reliable conclusions depend on sound randomization, adequate sample size, correct instrumentation, appropriate statistical analysis, and carefully selected guardrails.

The central lesson is simple:

A better offline score does not automatically mean a better production model.

Successful ML engineering connects predictive performance with real-world value through disciplined experimentation, reliable deployment, and continuous monitoring.