TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Shadow, Canary, A/B and Blue-Green for Models

Shadow, Canary, A/B and Blue-Green for Models

A new model passed every offline check: better validation metrics, the registry gate, the tests in CI. It can still fail in production, in ways the offline evaluation could not see: live inputs that differ from the test set, a feature computed slightly differently online, a latency spike under real load, or a better metric that makes users click less. Release strategies limit how much damage a bad model can do before you notice, and they produce the online evidence for keeping a good one. The DevOps track covers the traffic mechanics (canary, blue-green, progressive rollouts with Argo Rollouts); this lesson adds what is specific to models, above all the statistics of deciding from a small slice of traffic.

Four ways to release a model

shadow current: 100 % new: copy only users see current; new is only logged canary current: 95 % new: 5 % 5, 25, 50, 100 % if guardrails hold A/B test users in A: 50 % users in B: 50 % random users, weeks, business metric blue-green blue: idle green: 100 % switch all; switch back = rollback
  • Shadow (dark launch). Every request is also sent to the new model and its answer is logged, never returned. Users are not affected at all. You learn whether the model works on live inputs: errors, latency at full load, and how often its predictions agree with the current model's (and, for the disagreements, which one was right once labels arrive). You cannot learn how users react, because they never see the new answers. The cost is double the inference compute.
  • Canary. A small share of live traffic (1 to 5 %) goes to the new model, and the share grows in steps while guardrail metrics stay healthy: error rate, latency, the rate of fallback answers, the distribution of predicted scores. The goal is to catch regressions quickly with limited exposure, with an automatic rollback when a guardrail trips.
  • A/B test. Users (not requests: one user must see one model consistently) are randomly split between models for long enough to compare a business metric: conversions, clicks, revenue, retention. The goal is to measure improvement, which takes far more data than catching a crash.
  • Blue-green. Two complete environments; the new model is deployed to the idle one, tested, and the router switches all traffic at once. Rollback is switching back, in seconds. It needs double capacity during the switch, and the switch exposes everyone, so it is often combined with a shadow or canary phase first.

For ranking and recommendation, interleaving compares two rankers within the same result list, and multi-armed bandits shift traffic towards the better model while the experiment runs (trading statistical cleanliness for less regret).

Is the canary worse? A two-proportion test

The canary served n2n_2 requests with x2x_2 errors, the stable fleet n1n_1 requests with x1x_1 errors. With p^i=xi/ni\hat p_i = x_i / n_i and the pooled p^=(x1+x2)/(n1+n2)\hat p = (x_1 + x_2)/(n_1 + n_2), the test of "the canary's error rate is higher" (two proportions, hypothesis testing) uses

z=p^2−p^1p^(1−p^)(1n1+1n2)z = \frac{\hat p_2 - \hat p_1}{\sqrt{\hat p (1 - \hat p) \left( \frac{1}{n_1} + \frac{1}{n_2} \right)}}

and a one-sided p-value P(Z>z)P(Z > z): only a worse canary is a reason to roll back. How many canary requests are needed? When the stable fleet is much larger, its rate p0p_0 is known precisely and the canary sample size to detect a rise to p1p_1 with significance α\alpha and power 1−β1 - \beta is

n=(zαp0(1−p0)+zβp1(1−p1))2(p1−p0)2n = \frac{\left( z_{\alpha} \sqrt{p_0 (1 - p_0)} + z_{\beta} \sqrt{p_1 (1 - p_1)} \right)^2}{(p_1 - p_0)^2}
python · try it yourself
import math
from scipy.stats import norm

def two_proportion_z(x1, n1, x2, n2):
    """z statistic for p2 > p1 with the pooled proportion, and its one-sided p-value."""
    p1, p2 = x1 / n1, x2 / n2
    p = (x1 + x2) / (n1 + n2)
    z = (p2 - p1) / math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2))
    return p1, p2, z, norm.sf(z)

for x2, n2 in ((48, 2000), (62, 2000)):
    p1, p2, z, pval = two_proportion_z(400, 20000, x2, n2)
    verdict = "roll back" if pval < 0.05 else "no evidence of a regression"
    print(f"stable {p1:.2%} of 20000, canary {p2:.2%} of {n2}: z = {z:.2f}, one-sided p = {pval:.3f} -> {verdict}")

def canary_size(p0, p1, alpha=0.05, power=0.8):
    """Canary requests to detect p0 -> p1 when the stable rate p0 is known precisely (large baseline)."""
    za, zb = norm.isf(alpha), norm.isf(1 - power)
    return math.ceil((za * math.sqrt(p0 * (1 - p0)) + zb * math.sqrt(p1 * (1 - p1))) ** 2 / (p1 - p0) ** 2)

rps, share = 50, 0.05
for p1 in (0.03, 0.025, 0.022):
    n = canary_size(0.02, p1)
    print(f"detect 2.0% -> {p1:.1%}: {n:6d} canary requests = {n / (rps * share) / 60:6.1f} min at {share:.0%} of {rps} req/s")
stable 2.00% of 20000, canary 2.40% of 2000: z = 1.21, one-sided p = 0.114 -> no evidence of a regression
stable 2.00% of 20000, canary 3.10% of 2000: z = 3.27, one-sided p = 0.001 -> roll back
detect 2.0% -> 3.0%:   1398 canary requests =    9.3 min at 5% of 50 req/s
detect 2.0% -> 2.5%:   5233 canary requests =   34.9 min at 5% of 50 req/s
detect 2.0% -> 2.2%:  31282 canary requests =  208.5 min at 5% of 50 req/s

A canary at 2.40 % against 2.00 % on the stable fleet (2,000 against 20,000 requests) gives z=1.21z = 1.21 and p=0.114p = 0.114: a 20 % relative rise, but with 2,000 requests it cannot be told apart from noise. At 3.10 %, z=3.27z = 3.27 and p=0.001p = 0.001: roll back. The sample-size lines are the real constraint. Detecting a rise from 2.0 % to 3.0 % takes 1,398 canary requests, 9.3 minutes at 5 % of 50 req/s. Halving the difference to 2.5 % needs 5,233 requests (34.9 minutes), and a 10 % relative rise to 2.2 % needs 31,282 requests, three and a half hours. The required sample grows with 1/Δ21/\Delta^2: a canary catches large regressions quickly, and small ones only slowly or not at all. Plan the canary's duration and share from this formula, and use an A/B test for small differences.

Looking at the canary repeatedly

A canary is watched continuously, which breaks the assumption of a single test. Each look at the data is another chance for noise to cross the threshold. A simulation with 4,000 canaries that are exactly as good as the stable model (2 % errors), checked after every 500 requests, 10 times:

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
sims, checks, step = 4000, 10, 500          # look at the canary after every 500 requests, 10 looks
p_stable = 0.02                             # known from the large stable fleet

def run(p_canary, z_crit):
    errors = rng.binomial(step, p_canary, size=(sims, checks)).cumsum(axis=1)
    n = step * np.arange(1, checks + 1)
    z = (errors / n - p_stable) / np.sqrt(p_stable * (1 - p_stable) / n)
    alarm = z > z_crit
    first = np.where(alarm.any(axis=1), alarm.argmax(axis=1), -1)
    return alarm.any(axis=1).mean(), alarm[:, -1].mean(), first

for z_crit, label in ((1.645, "z > 1.645 at every look"), (2.326, "z > 2.326 at every look")):
    any_look, last_only, _ = run(p_stable, z_crit)
    print(f"no regression, {label}: alarm at some look {any_look:.1%}, alarm at the final look only {last_only:.1%}")
any_look, _, first = run(0.03, 2.326)
caught = first[first >= 0]
print(f"real regression 2% -> 3%, z > 2.326: caught in {any_look:.1%} of runs, "
      f"median {np.median((caught + 1) * step):.0f} requests to the alarm")
no regression, z > 1.645 at every look: alarm at some look 16.6%, alarm at the final look only 4.6%
no regression, z > 2.326 at every look: alarm at some look 5.2%, alarm at the final look only 0.9%
real regression 2% -> 3%, z > 2.326: caught in 99.3% of runs, median 1500 requests to the alarm

Testing at the 5 % level (z>1.645z > 1.645) at every look raises an alarm in 16.6 % of the harmless canaries, more than three times the 4.6 % of a single test at the end. A stricter threshold of z>2.326z > 2.326 (1 % per look) brings the overall false-alarm rate back to 5.2 %, and still catches a real regression from 2 % to 3 % in 99.3 % of runs, after a median of 1,500 requests. Proper sequential tests (alpha spending, the sequential probability ratio test, always-valid p-values) make this exact. Canary-analysis tools such as Argo Rollouts' analysis runs or Kayenta automate the repeated checks, but with their own fixed rules (metric thresholds and failure limits; a Mann-Whitney test per metric in Kayenta), so the correction for repeated looks is still yours to design. The simplest defence is the one simulated: decide the number of looks in advance and use a stricter threshold per look.

Interleaving for rankers

A ranking model is judged by what users click. An A/B test compares the click rate of two user groups, but the number of clicks varies enormously between queries, so the difference between groups is buried in that variance. Team-draft interleaving shows each user one list made from both rankings: the two rankers take turns, like captains picking teams, each adding its best document not yet in the list; a click credits the ranker that contributed that document, and the ranker with more credited clicks wins the query. Each query is a paired comparison, which removes the between-query variance. A simulation with a better ranker A and a noisier ranker B, 200 repetitions of each experiment size:

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
n_docs, shown = 20, 5
exam = 1 / np.arange(1, shown + 1)                       # chance that the user looks at position 1..5

def query():
    rel = rng.beta(0.6, 2.0, n_docs)                     # click probability of each document if seen
    a = np.argsort(-(rel + rng.normal(0, 0.15, n_docs))) # ranker A: better
    b = np.argsort(-(rel + rng.normal(0, 0.25, n_docs))) # ranker B: noisier
    return rel, a, b

def clicks(rel, ranking):
    docs = ranking[:shown]
    return docs[rng.random(shown) < exam * rel[docs]]

def team_draft(a, b):
    """Team-draft interleaving: teams take turns (coin flip on ties) picking their best unpicked document."""
    out, team, ia, ib, na, nb = [], {}, 0, 0, 0, 0
    while len(out) < shown:
        pick_a = na < nb or (na == nb and rng.random() < 0.5)
        src, i = (a, ia) if pick_a else (b, ib)
        while src[i] in team:
            i += 1
        out.append(src[i]); team[src[i]] = "A" if pick_a else "B"
        if pick_a: ia, na = i + 1, na + 1
        else: ib, nb = i + 1, nb + 1
    return np.array(out), team

def ab_test(n):
    ca = sum(len(clicks(*query()[:2])) for _ in range(n // 2))
    cb = 0
    for _ in range(n // 2):
        rel, _, b = query()
        cb += len(clicks(rel, b))
    return ca > cb

def interleave(n):
    wins = 0
    for _ in range(n):
        rel, a, b = query()
        lst, team = team_draft(a, b)
        c = [team[d] for d in clicks(rel, lst)]
        wins += np.sign(c.count("A") - c.count("B"))
    return wins > 0

reps = 200
for n in (50, 200, 800):
    ab = np.mean([ab_test(n) for _ in range(reps)])
    il = np.mean([interleave(n) for _ in range(reps)])
    print(f"{n:4d} queries: A/B test picks the better ranker {ab:.0%} of the time, interleaving {il:.0%}")
  50 queries: A/B test picks the better ranker 70% of the time, interleaving 81%
 200 queries: A/B test picks the better ranker 87% of the time, interleaving 91%
 800 queries: A/B test picks the better ranker 99% of the time, interleaving 100%

With 50 queries, the A/B test picks the better ranker in 70 % of the experiments and interleaving in 81 %; at 200 queries 87 % against 91 %; at 800 both are nearly always right (99 % and 100 %). In this simulation interleaving is the more reliable method at every size, and the gap is largest when data is scarce; published comparisons on real search engines report it to be one to two orders of magnitude more sensitive than A/B tests on click metrics. It answers only "which ranking do users prefer", not "how much revenue", so teams typically use interleaving to screen candidates and A/B tests to confirm the winner.

Pitfalls

  • Randomising by request instead of by user in an A/B test: one user sees both models, effects mix, and requests from the same user are not independent.
  • Comparing the canary with yesterday instead of with the stable fleet at the same time: traffic changes during the day. Compare concurrently, ideally with a fresh baseline deployment of the old model alongside the canary, so both are equally new pods.
  • Too short or too small a canary for the effect you care about. Compute the sample size first.
  • Peeking without correction: repeated looks inflate false alarms (16.6 % instead of 5 % above).
  • Only technical guardrails. A model can return fast, valid answers that are wrong. Add model-level guardrails: score distribution, prediction rate per class, agreement with the old model, and later the labelled outcome (monitoring).
  • Shadow traffic with side effects: the shadow model must not write to databases, send emails or charge cards.

Practice

  1. Stable: 600 errors in 30,000 requests; canary: 30 in 1,000. Compute zz and decide at α=0.05\alpha = 0.05 (one-sided).
Answer

p^1=0.020\hat p_1 = 0.020, p^2=0.030\hat p_2 = 0.030, p^=630/31,000=0.02032\hat p = 630/31{,}000 = 0.02032. Standard error 0.02032⋅0.97968⋅(1/30,000+1/1,000)≈0.00454\sqrt{0.02032 \cdot 0.97968 \cdot (1/30{,}000 + 1/1{,}000)} \approx 0.00454, z=0.010/0.00454≈2.2z = 0.010 / 0.00454 \approx 2.2, p≈0.014<0.05p \approx 0.014 < 0.05: roll back. Check it with two_proportion_z(600, 30000, 30, 1000).

  1. You want to detect a rise of the error rate from 1 % to 1.5 % with α=0.05\alpha = 0.05 and power 0.8. About how many canary requests is that?
Answer

zα=1.645z_\alpha = 1.645, zβ=0.842z_\beta = 0.842: n=(1.6450.0099+0.8420.014775)2/0.0052=(0.1637+0.1023)2/0.000025≈2,831n = (1.645 \sqrt{0.0099} + 0.842 \sqrt{0.014775})^2 / 0.005^2 = (0.1637 + 0.1023)^2 / 0.000025 \approx 2{,}831. canary_size(0.01, 0.015) gives the exact value.

  1. Which strategy fits each case: (a) a fraud model whose new version must be checked on live traffic without affecting any decision; (b) a ranking model expected to raise clicks by 0.5 %; (c) a hotfix of the serving code that must be revertible in seconds?
Answer

(a) Shadow: compare its scores and alerts with the current model's on the same transactions. (b) An A/B test (perhaps preceded by interleaving), sized for a 0.5 % effect. (c) Blue-green (or a fast canary): switch back instantly.

Test yourself

Which strategy exposes no user to the new model's answers?

  1. Shadow
  2. Canary
  3. A/B test
  4. Blue-green

To halve the regression you can detect in a canary (for example 1 point instead of 2), roughly how many more requests do you need?

  1. About 4 times as many
  2. About 2 times as many
  3. The same number
  4. About 1.4 times as many

A canary is tested at the 5 % level after every 500 requests, 10 times. What happens to the false-alarm rate for a harmless canary?

  1. It rises, to 16.6 % in the simulation
  2. It stays at 5 %
  3. It falls below 5 %
  4. It becomes 50 %

Why is team-draft interleaving more sensitive than an A/B test for comparing rankers?

  1. Each query compares both rankers in one list, removing the variance between queries and users
  2. It uses more users
  3. It measures revenue directly
  4. It does not need clicks

What should be the unit of randomisation in an A/B test of a recommendation model?

  1. The user
  2. The request
  3. The server
  4. The hour of day