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
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.
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.
Pick what is wrong with the challenger and what the canary watches, and how the A/B test is read.
Three questions. No score is saved anywhere — this is just you against the material.
Rolling out models grows in four levels: reading a rollout, running shadow and canary, running honest experiments, and running champion/challenger as a system.
At the basic level you can say which model each user gets and whether the rollout is healthy.
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.
At the intermediate level every new model goes through shadow, then an automated canary.
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.
At the advanced level A/B tests are designed before they start.
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.
At the master level rollout is a continuous, governed loop.
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.
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.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The canary watched the servers, not the model.
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.
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.
Type each one, read what it prints, and compare it with the note above it.
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
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')"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')"peeking.pyThis 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
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
cut, echo, Pipes, Redirection, Loops, If...Else.You run a recommender serving 20 million users and ship a new model every two weeks. Design the path from registered challenger to champion.
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?
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.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Canary on latency only | Hop 5: Guardrails | Breaks | The 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 early | Hop 7: Significance | Breaks | The 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. |
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.