Platform Engineering · Lesson 325

Model Canary and Shadow Deployment: A/B Tests and Champion/Challenger

Passing an offline gate says a model is good on yesterday's data. Only live traffic says it is good today. There are four ways to let a new model meet real traffic safely. A shadow deployment sends a copy of each request to the challenger and throws its answer away. A canary lets it answer a small, growing share of real users, with automatic rollback. An A/B test splits users at random and measures a business metric, long enough to be sure. Champion/challenger runs this as a permanent loop. This lesson follows one challenger from shadow to full traffic, and shows the two failures that catch teams out: a canary judged on the wrong signal, and an A/B test stopped as soon as it looked good.

Difficulty: Advanced · Know this first: Lesson 324, Lesson 92

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from a registered challenger to champion on full traffic. It is a worked example, not a measurement. The guardrail and significance hops decide whether a bad model is caught.

Try it: would this rollout catch a bad model?

Pick what is wrong with the challenger and what the canary watches, and how the A/B test is read.

canarycaught at
rolled backoutcome

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Rolling out models grows in four levels: reading a rollout, running shadow and canary, running honest experiments, and running champion/challenger as a system.

Basic — Read a rollout

At the basic level you can say which model each user gets and whether the rollout is healthy.

  • Router weights, the mirror target, the version label on each response.
  • Shadow (copied, never returned), canary (a share of users), A/B (a random split, a business metric).
  • The rollout's current step and its analysis result.

Where it breaks: splitting by request, so one user sees both models.

Try it: Basic

Users complain that recommendations change every time they reload. What is wrong with the split?

Now do it: Check how your router assigns traffic.

Intermediate — Shadow and canary

At the intermediate level every new model goes through shadow, then an automated canary.

  • Mirror traffic to the challenger; log paired predictions; review disagreements by slice.
  • Canary steps with pauses as long as the slowest signal; automatic rollback on breach.
  • Guardrails: latency, errors, prediction distribution, low-confidence share, fast business proxies.

Try it: Intermediate

The slowest quality signal (returns) arrives within 24 hours. How long should canary steps be?

Now do it: List your guardrails and how quickly each arrives.

Advanced — Honest experiments

At the advanced level A/B tests are designed before they start.

  • Primary metric, guardrail metrics, minimum detectable effect, power, sample size, duration in whole weeks.
  • No stopping on a peek, or a sequential method chosen in advance.
  • Sample ratio mismatch checks (is the split really 50/50?), novelty checks, and a holdout.

Try it: Advanced

The split is meant to be 50/50 but B has 53% of users. What does it tell you?

Now do it: Add an SRM check to your experiment analysis.

Master — Champion/challenger as a system

At the master level rollout is a continuous, governed loop.

  • A challenger always in shadow; promotion through canary and A/B by pipeline, recorded on the version.
  • A permanent small holdout for long-run effects; interference between experiments managed.
  • Rollback rehearsed; the old champion kept warm until the new one has earned it.

Trade-off: shadow doubles inference cost and long A/B tests slow learning; both are cheaper than shipping a confident, wrong model to everyone.

Try it: Master

Why keep a 2% holdout on the previous champion after promotion?

Now do it: Size a holdout for your main metric.

Go deeper

A canary for a model on KServe: the new revision takes 10% of traffic, the previous one keeps 90%, and rolling back means setting the percentage to 0. Check the KServe documentation for your version.

apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata: {name: recommender}
spec:
  predictor:
    canaryTrafficPercent: 10          # the new revision gets 10%; the last ready one keeps 90%
    model:
      modelFormat: {name: sklearn}
      storageUri: s3://models/recommender/v20

Mirroring (shadow) with an Istio VirtualService: every request goes to v18, and a copy goes to v20, whose answer is discarded.

apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: {name: recommender}
spec:
  hosts: [recommender]
  http:
  - route:
    - destination: {host: recommender, subset: v18}
      weight: 100
    mirror: {host: recommender, subset: v20}
    mirrorPercentage: {value: 100.0}

How the four approaches compare:

Sample size for a conversion test, roughly: n per group ≈ 16 × p(1 − p) / δ², for 80% power at a 5% significance level, where p is the baseline rate and δ the absolute lift you need to detect. At p = 0.05 and δ = 0.002 (a 4% relative lift), that is about 190,000 users per group.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The canary watched the servers, not the model.

Timeline

  • Day 0Recommender v20 passes its offline gate and 24 hours of shadow with no errors and p99 13 ms. Agreement is 91% overall; nobody breaks it down by category.
  • Day 1The canary goes 1% → 5% → 25% → 50%. Its analysis compares p99 latency and 5xx rate with v18: both are better.
  • Day 2The merchandising team sees add-to-cart in indoor furniture halve for half of users, and returns climb. v20 confuses a new garden-furniture category with indoor items.
  • Day 2 + 16 minThe rollout is aborted; 100% back on v18.

What changed after

Shadow agreement is reviewed per category before any canary, the canary analysis includes the prediction mix per category and add-to-cart rate against v18, steps are long enough for those signals, and new categories get a targeted evaluation set.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A practice cluster with KServe or Istio to run the manifests in "Go deeper" (optional). The commands below need only Linux and Python 3.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Assign users to a model the sticky way: a hash of the user ID, so a user always gets the same model.

    for u in alice bob carol dave erin; do
      h=$(printf "%s" "exp-42:$u" | sha256sum | cut -c1-8)
      bucket=$(( 16#$h % 100 ))
      [ $bucket -lt 10 ] && m=challenger || m=champion
      echo "$u bucket=$bucket -> $m"
    done

    Options: The experiment name (exp-42) is part of the hash, so different experiments split users independently; 16# reads the hex digits as a number; buckets 0–9 are a 10% canary.

    Expect: Five users, each with a bucket from 0 to 99 and a model; run it again and every answer is the same.

  2. Check a split for sample ratio mismatch: 50/50 planned, counts observed.

    python3 -c "import math; a,b=50210,48790; n=a+b; z=(a-n/2)/math.sqrt(n/4); p=math.erfc(abs(z)/math.sqrt(2)); print(f'z={z:.2f} p={p:.2g}', 'SRM: do not trust this test' if p<0.001 else 'split looks fine')"

    Options: A chi-square or z test of the counts against the planned ratio; a very small p (under 0.001) means assignment or logging is broken.

    Expect: z=4.51 and a tiny p: the split is not 50/50, so something other than the model differs between groups.

  3. Estimate how many users an A/B test needs before you start it.

    python3 -c "p=0.05; rel=0.04; d=p*rel; n=16*p*(1-p)/d**2; print(f'baseline {p:.0%}, lift {rel:.0%} relative -> about {n:,.0f} users per group')"

    Options: 16 × p(1−p) / δ² is the usual rule of thumb for 80% power at a 5% significance level.

    Expect: About 190,000 users per group for a 4% relative lift on a 5% baseline.

2. Python: peeking.py

This program runs 2,000 A/A tests, where both groups get the same model, so every "significant" result is false. It reads each test once at its planned end, and again the way people often do: every day, stopping at the first p under 0.05. Then it shows a canary analysis that watches only latency missing a model that is wrong. Save it as peeking.py, then run it.

# peeking.py
import math
import random

rnd = random.Random(42)
DAYS, USERS_PER_DAY, RATE = 14, 2000, 0.05

def p_value(ca, na, cb, nb):
    pa, pb, pool = ca / na, cb / nb, (ca + cb) / (na + nb)
    se = math.sqrt(pool * (1 - pool) * (1 / na + 1 / nb))
    return math.erfc(abs(pa - pb) / se / math.sqrt(2)) if se else 1.0

def conversions(n):
    # normal approximation to a binomial draw, fast enough for 2,000 tests
    return max(0, round(rnd.gauss(n * RATE, math.sqrt(n * RATE * (1 - RATE)))))

end_wins = peek_wins = 0
for _ in range(2000):
    ca = cb = na = nb = 0
    peeked = False
    for day in range(DAYS):
        na += USERS_PER_DAY; nb += USERS_PER_DAY
        ca += conversions(USERS_PER_DAY); cb += conversions(USERS_PER_DAY)
        if not peeked and p_value(ca, na, cb, nb) < 0.05:
            peeked = True
    end_wins += p_value(ca, na, cb, nb) < 0.05
    peek_wins += peeked
print("2,000 A/A tests: no real difference anywhere")
print(f"  read once at day 14:      {end_wins / 20:.1f}% 'significant'   (should be about 5%)")
print(f"  peek daily, stop at p<.05: {peek_wins / 20:.1f}% 'significant'")
print()

# a canary of a model that is fast and wrong for one category
champion = {"p99_ms": 14, "errors": 0.001, "add_to_cart": {"indoor": 0.081, "garden": 0.064}}
challenger = {"p99_ms": 12, "errors": 0.001, "add_to_cart": {"indoor": 0.040, "garden": 0.066}}
def analyse(guards):
    breaches = []
    if "system" in guards:
        if challenger["p99_ms"] > champion["p99_ms"] * 1.1: breaches.append("latency")
        if challenger["errors"] > champion["errors"] * 1.5: breaches.append("errors")
    if "model" in guards:
        for cat, base in champion["add_to_cart"].items():
            if challenger["add_to_cart"][cat] < base * 0.9:
                breaches.append(f"add-to-cart {cat} {challenger['add_to_cart'][cat]:.3f} vs {base:.3f}")
    return "ROLL BACK: " + ", ".join(breaches) if breaches else "promote to next step"
print("canary watching latency and errors:       ", analyse({"system"}))
print("canary watching those plus model signals: ", analyse({"system", "model"}))

Run it, and you should see this output:

$ python3 peeking.py
2,000 A/A tests: no real difference anywhere
  read once at day 14:      5.5% 'significant'   (should be about 5%)
  peek daily, stop at p<.05: 22.0% 'significant'

canary watching latency and errors:        promote to next step
canary watching those plus model signals:  ROLL BACK: add-to-cart indoor 0.040 vs 0.081

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/model-canary-and-shadow-deployment && cd ~/labs/model-canary-and-shadow-deployment) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Model Canary and Shadow Deployment: A/B Tests and Champion/Challenger", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Assign users to a model the sticky way: a hash of the user ID, so a user always gets the same model.'
  'Check a split for sample ratio mismatch: 50/50 planned, counts observed.'
  'Estimate how many users an A/B test needs before you start it.'
)

step_1() {
for u in alice bob carol dave erin; do
  h=$(printf "%s" "exp-42:$u" | sha256sum | cut -c1-8)
  bucket=$(( 16#$h % 100 ))
  [ $bucket -lt 10 ] && m=challenger || m=champion
  echo "$u bucket=$bucket -> $m"
done
}

step_2() {
python3 -c "import math; a,b=50210,48790; n=a+b; z=(a-n/2)/math.sqrt(n/4); p=math.erfc(abs(z)/math.sqrt(2)); print(f'z={z:.2f} p={p:.2g}', 'SRM: do not trust this test' if p<0.001 else 'split looks fine')"
}

step_3() {
python3 -c "p=0.05; rel=0.04; d=p*rel; n=16*p*(1-p)/d**2; print(f'baseline {p:.0%}, lift {rel:.0%} relative -> about {n:,.0f} users per group')"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

You run a recommender serving 20 million users and ship a new model every two weeks. Design the path from registered challenger to champion.

Clarifying questions to ask

How long does shadow run, and what do you compare? Which guardrails does the canary check, and how long is each step? How are A/B tests planned and read? Who decides, and what is recorded? How fast is rollback, and how is it tested?

Rough sizing

Say 3,000 requests a second at peak, a 5% conversion baseline, a target of detecting a 1% relative lift, and a release every two weeks.

Shape of the answer

Mirroring in the mesh or inference platform for 24 hours with paired logs and per-slice agreement review; canary at 1/5/25/50% with Argo Rollouts or KServe, each step long enough for add-to-cart and returns proxies, automated rollback; A/B tests planned with sample size and whole weeks, read at the end with intervals and SRM checks; a 2% holdout; decisions recorded on the registry version; rollback by router weight in seconds, rehearsed monthly.

Trade-offs to name

At this traffic a 1% relative lift needs weeks, so either accept slower learning, test bigger changes, or use interleaving for ranking quality; shadow doubles inference cost for a day; long canary steps slow releases and catch the harms that matter.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Canary on latency onlyHop 5: GuardrailsBreaksThe analysis checks only p99 latency and 5xx rate, both perfect. v20 recommends garden furniture to people browsing indoor furniture; add-to-cart in that category falls by half and returns climb. Nothing in the analysis looks at it.
The A/B test stopped earlyHop 7: SignificanceBreaksThe dashboard is checked daily. On day 3, p = 0.04 with +2.1%, and the test is stopped and v20 declared the winner. The early lift was novelty plus noise.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Router → Shadow → Comparison → Canary → Guardrails → A/B split → Significance → Decision → Rollback. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 326
ML SLOs and Model Incidents: Accuracy, Drift, Fairness, and Response

A model can be up, fast, and wrong. Ordinary SLOs (availability, latency) say nothing about whether its answers are any good, so ML services need ML SLOs as well: prediction quality measured against delayed ground truth, the…

Go to Lesson 326 →

Or browse the full course from the Lessons index.