Safe Rollouts: Shadow, Canary, A/B Tests and Rollback
Release a new model in steps that limit risk: shadow mode to compare it on real traffic without affecting anyone, a sticky hash-based canary with written rules on errors, latency and a business metric, A/B tests sized in advance and not stopped at the first good-looking peek, and a rollback that is a single pointer change, with runnable scripts for each step.
Contentsand lesson path
On this page
- Why it matters
- Shadow: real traffic, no effect on users
- Canary: a small slice of real users, with rules
- A/B tests: sized in advance, read once
- Rollback, and choosing the strategy
- Check your understanding
- Apply it
- Review prompt
Lessons of Model Packaging & Serving
- What Exactly Are You Shipping? Model Artifacts and Formats Concept · 20 min
- Batch, Online or Streaming: Picking the Inference Pattern Concept · 15 min
- Lab: A Validated Prediction API with Shared Batch Scoring Lab · 30 min
- Lab: Containerize, Load-Test and Optimize Lab · 30 min
- Safe Rollouts: Shadow, Canary, A/B Tests and Rollback Concept · 15 min
- Check: Serving Design Review Knowledge check · 8 questions
What you will learn
- Choose batch, online or streaming inference and a rollout strategy (shadow, canary, A/B test, rollback) from latency, freshness, cost and risk requirements.
Prerequisites: Containerization
01. Why it matters
A new model that beat the old one offline can still fail in production. Live inputs differ from the evaluation set, a feature is computed slightly differently in the service, latency is higher than expected, or the model is more accurate but users click less. You cannot rule these out before release, so you release in steps, each exposing more users only when the previous step looked healthy, and you keep a fast way back.
This lesson covers the four tools for that, in the order teams usually use them: shadow deployment, canary release, A/B test and rollback. Each section has a short script; you need Python 3.12 with NumPy and scikit-learn, and the scripts use simulated traffic so their output repeats exactly.
mkdir -p rollouts && cd rollouts
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "numpy==2.5.*"02. Shadow: real traffic, no effect on users
In a shadow deployment every request, or a copy of a sample of requests, goes to both models. The current model, the champion, answers; the new one, the challenger, also scores the request, and its output is only logged. Users see exactly what they saw before. Shadow mode catches problems that offline tests miss: inputs the new model cannot handle, crashes, slow responses and predictions that differ more than expected. The shadow call must never break or slow down the real answer, so it is wrapped in error handling and, in a real service, run after the response is sent or on a separate worker.
"""Shadow mode: the challenger scores every request, but only the champion answers."""
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
X = rng.normal(size=(6000, 4))
y = (X @ [1.0, -0.8, 0.5, 0.0] + rng.normal(0, 1, 6000) > 0.3).astype(int)
champion = LogisticRegression().fit(X[:3000, :3], y[:3000]) # three features
challenger = LogisticRegression(C=0.05).fit(X[:3000], y[:3000]) # four, regularised
log = []
def handle(x):
answer = champion.predict_proba(x[:3].reshape(1, -1))[0, 1]
try: # the shadow must never break the answer
shadow = challenger.predict_proba(x.reshape(1, -1))[0, 1]
log.append((answer, shadow))
except Exception as error:
log.append((answer, None))
print("shadow failed:", error)
return answer # only the champion's score is used
for x in X[3000:]: # 3,000 mirrored production requests
handle(x)
a = np.array([p for p, _ in log])
s = np.array([q for _, q in log])
print(f"requests mirrored: {len(log)}")
print(f"decisions that differ at 0.5: {np.mean((a >= 0.5) != (s >= 0.5)):.1%}")
print(f"mean absolute score difference: {np.mean(np.abs(a - s)):.3f}")
# Days later the outcomes are known, and only then can you say which model is better.
truth = y[3000:]
print(f"accuracy once outcomes arrive: champion {np.mean((a >= 0.5) == truth):.3f}, "
f"challenger {np.mean((s >= 0.5) == truth):.3f}")python shadow.pyrequests mirrored: 3000
decisions that differ at 0.5: 0.9%
mean absolute score difference: 0.019
accuracy once outcomes arrive: champion 0.793, challenger 0.792The challenger would have changed 0.9% of the decisions, and its scores differ by 0.019 on average. Those numbers say how much the release would change, not whether the change is good: that needs outcomes, which here arrive later and show the two models as equal. Shadow mode is therefore a safety and sanity step. It also costs real compute, because every mirrored request is scored twice.
03. Canary: a small slice of real users, with rules
In a canary release the new model serves a small share of real users, for example 5%, while everyone else stays on the stable version. If it misbehaves, only that slice is affected and you roll back. Two details make a canary trustworthy. First, assignment should be sticky: the same user should get the same model on every request, or their experience flips back and forth and the metrics mix both models. Hashing a stable user id gives that without storing anything. Second, the decision to widen or roll back should follow rules written before the release.
"""Sticky canary routing: a user's hash bucket decides which model serves them."""
import hashlib
def bucket(user_id: str, salt="churn-v8-rollout") -> int:
digest = hashlib.sha256(f"{salt}:{user_id}".encode()).hexdigest()
return int(digest, 16) % 100 # 0..99, fixed for this user
def route(user_id: str, canary_percent: int) -> str:
return "canary" if bucket(user_id) < canary_percent else "stable"
users = [f"user-{i}" for i in range(10_000)]
at_5 = {u for u in users if route(u, 5) == "canary"}
at_25 = {u for u in users if route(u, 25) == "canary"}
print(f"canary at 5%: {len(at_5)} of {len(users)} users")
print(f"canary at 25%: {len(at_25)} of {len(users)} users")
print("everyone from the 5% group is still in the canary:", at_5 <= at_25)
print("same answer on every call:", all(route("user-42", 5) == route("user-42", 5)
for _ in range(3)))python router.pycanary at 5%: 501 of 10000 users
canary at 25%: 2563 of 10000 users
everyone from the 5% group is still in the canary: True
same answer on every call: TrueThe hash spreads users evenly, so 5% gives about 500 of 10,000. Because a user's bucket never changes and widening only raises the threshold, everyone already in the canary stays there at 25%. The salt is specific to this rollout, so the next release puts a different 5% of users first. Then check the canary against stable traffic on three kinds of signal: system health (error rate), speed (p95 latency) and the business metric the model exists to move, here click-through. The script below applies such rules to one hour of monitoring data, using a two-proportion z-test so that ordinary noise in a 5,000-request slice is not mistaken for a drop.
"""Canary analysis: compare the canary slice with stable traffic, then decide."""
import math
# One hour of traffic. In production these numbers come from your monitoring.
stable = {"requests": 95_000, "errors": 95, "p95_ms": 41, "clicks": 9_310}
canary = {"requests": 5_000, "errors": 6, "p95_ms": 43, "clicks": 420}
RULES = {"max_error_rate_increase": 0.002, "max_p95_ratio": 1.2, "alpha": 0.05}
def one_sided_p(stable_hits, stable_n, canary_hits, canary_n):
"""Two-proportion z-test: how surprising is a canary rate this much lower?"""
p1, p2 = stable_hits / stable_n, canary_hits / canary_n
pooled = (stable_hits + canary_hits) / (stable_n + canary_n)
se = math.sqrt(pooled * (1 - pooled) * (1 / stable_n + 1 / canary_n))
z = (p2 - p1) / se
return 0.5 * math.erfc(-z / math.sqrt(2)), p1, p2
checks = {}
def rate(group, key):
return group[key] / group["requests"]
error_gap = rate(canary, "errors") - rate(stable, "errors")
checks["error rate"] = error_gap <= RULES["max_error_rate_increase"]
checks["p95 latency"] = canary["p95_ms"] <= RULES["max_p95_ratio"] * stable["p95_ms"]
p, ctr_stable, ctr_canary = one_sided_p(stable["clicks"], stable["requests"],
canary["clicks"], canary["requests"])
checks["click-through"] = p >= RULES["alpha"]
print(f"click-through: stable {ctr_stable:.2%}, canary {ctr_canary:.2%}, p = {p:.4f}")
for name, ok in checks.items():
print(f" {name:14} {'pass' if ok else 'FAIL'}")
print("decision:", "widen to 25%" if all(checks.values()) else "roll back the canary")python canary.pyclick-through: stable 9.80%, canary 8.40%, p = 0.0006
error rate pass
p95 latency pass
click-through FAIL
decision: roll back the canaryThe service is healthy, but users in the canary click less, and a drop this large is very unlikely to be noise at this sample size, so the rules roll it back. A canary that only watched errors and latency would have been widened.
04. A/B tests: sized in advance, read once
A canary asks "is it safe?". An A/B test asks "is it better, and by how much?". Users are split at random into arms, usually 50/50, and you compare a business metric after a fixed number of users. The number matters: small improvements need large samples to stand out from chance. The power of a test is the probability of detecting a real effect of a given size; 80% power and a 5% significance level (the risk of declaring a win that is not real) are common choices. The script computes the sample size for detecting a lift from 10% to 11% conversion, then shows what happens when people peek: they check the result repeatedly and stop as soon as it looks significant. It simulates 200 A/A tests, in which both arms run the same model, so every "win" is false.
"""How many users per arm does an A/B test need, and what does an early peek show?"""
import math
import random
from statistics import NormalDist
z = NormalDist().inv_cdf
base, target = 0.10, 0.11 # conversion now, and the lift worth detecting
alpha, power = 0.05, 0.80
p_bar = (base + target) / 2
n = ((z(1 - alpha / 2) * math.sqrt(2 * p_bar * (1 - p_bar))
+ z(power) * math.sqrt(base * (1 - base) + target * (1 - target))) ** 2
/ (target - base) ** 2)
print(f"users needed per arm: {math.ceil(n):,}")
# Two identical models (both convert at 10%), checked after every 500 users per arm.
random.seed(1)
false_wins = 0
for trial in range(200):
a = b = 0
for users in range(500, 15_001, 500):
a += sum(random.random() < base for _ in range(500))
b += sum(random.random() < base for _ in range(500))
pooled = (a + b) / (2 * users)
se = math.sqrt(2 * pooled * (1 - pooled) / users)
if abs(b - a) / users / se > z(1 - alpha / 2): # "significant" at this peek
false_wins += 1
break
print(f"A/A tests that looked significant at some peek: {false_wins} of 200")python ab_sample_size.pyusers needed per arm: 14,751
A/A tests that looked significant at some peek: 56 of 200Detecting a one-point lift needs about 14,750 users per arm. With 30 peeks, 56 of 200 identical comparisons looked like a win at some point, about 28% instead of the 5% the test promises. So fix the sample size and the metric before you start and read the result once, or use a method designed for repeated looks, such as a sequential test. Also watch guard-rail metrics, such as complaints, latency and results for important customer groups, which must not get worse even if the main metric improves.
05. Rollback, and choosing the strategy
Every step needs a way back that takes seconds, not a new build. Keep the previous model version deployed or quick to load, and make "which version serves" a pointer: a registry alias such as models:/churn@production (see the model registry lesson), a router setting such as the canary percentage, or the previous revision of a Kubernetes Deployment (kubectl rollout undo). Rolling back then means moving the pointer and confirming with the /version endpoint that every instance serves the old model again. Practise it before you need it.
Choosing between the strategies comes down to the requirements you met in the inference-patterns lesson:
- Shadow first when a wrong prediction is costly (fraud, credit, medical triage) or the model is new to production. It needs extra compute and a way to mirror traffic.
- A canary for almost every online release, because it limits the harm of surprises to a small slice and a short time.
- An A/B test when you need to know the business effect, and you have enough traffic to reach the sample size in reasonable time.
- For batch scoring, a cheaper path often works: score with both models, compare the outputs and switch the table that consumers read.
06. Check your understanding
07. Apply it
For the service of your project, write a release plan before you change anything. Name the stages (shadow, canary at 5%, 25%, 100%), how long each lasts, and the written rules that widen or roll back each stage: error rate, p95 latency and one business or model metric. Add sticky routing by user id to your API, and rehearse a rollback by moving your production pointer back and checking /version on every instance.
08. Review prompt
Without looking back, answer in your own words:
- What does shadow mode reveal, and what can it not tell you?
- Why should canary assignment be sticky, and how does hashing provide it?
- Which three kinds of signal should a canary rule check?
- Why does an A/B test need its sample size fixed in advance, and what does peeking do to it?
- What makes a rollback fast, and how do you confirm it worked?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.