Learning path: Monitor and Improve a Model in Production · Step 3 of 8
Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
Release a new ticket model step by step: shadow on 250 tickets, a canary at 10% and 50% with a guard, then a bad model pushed on purpose and rolled back with one pointer move, checked prediction by prediction.
What you will learn
- Run a new model in shadow mode, where it sees every request but nobody gets its answer
- Send a stable share of traffic to a canary with a hash bucket and a guard at each step
- Explain why a small canary slice can catch a disaster but can't measure an improvement
- Roll back with one pointer move and confirm the old predictions really came back
Before you start
- Save and Load Models with joblib
- MLflow Model Registry Aliases
Our model flags high priority support tickets, and a better version is ready. How do you switch without putting everyone at risk?
Think about a restaurant changing a recipe. The chef cooks the new version in the back and tastes it beside the old one. No customer gets it: that's shadow. Then it goes to one table in ten, and the chef watches those plates: that's a canary. Then half the room, and only after that, everyone. And the old recipe card never leaves the kitchen. If plates start coming back, the chef switches over that same evening: that's rollback.
One dial
All three are one question: what share of tickets does the new model actually answer?
Shadow is 0%: the new model sees every ticket, but nobody gets its answer. Canary is 10%, then 50%: now its answers reach people, so a mistake costs something, but only on a small part. Promotion is 100%. Between the marks there's a gate that can say stop.
The project: three versions
The tickets are synthetic and come from a file. release.py train builds three models and saves each one to the registry:
- v1: trained on the old tickets. This is live.
- v2: old tickets plus half of a newer batch. The candidate.
- v3: just 30 new tickets. A bad model we'll push on purpose later.
trained v1 (old tickets), v2 (old + new),
trained v3 (30 new tickets only)
live model: v1
Every check below runs on the other half of the newer batch: 250 tickets with known answers.
Shadow: nobody affected
Here's serve in router.py. It returns what was served, what the candidate said, and which tickets the candidate answered:
import zlib
import numpy as np
MAX_DROP = 0.02
def bucket(ticket_id):
"""Same ticket, same bucket, 0 to 99."""
return zlib.crc32(str(ticket_id).encode()) % 100
def serve(live, cand, X, ids, mode, share=0):
"""Return (served, candidate_preds, canary_mask)."""
old = live.predict(X)
none = np.zeros(len(old), dtype=bool)
if mode == "live":
return old, old, none
new = cand.predict(X)
if mode == "shadow":
return old, new, none
pick = np.array([bucket(i) < share for i in ids])
return np.where(pick, new, old), new, pick
In shadow mode both models predict, but only old goes out as served. new is kept for comparing.
tickets scored : 250
served by live : all 250
v2 agrees with v1 : 0.856
v1 accuracy : 0.628
v2 accuracy : 0.644
All 250 tickets were served by v1. v2 agrees on 0.856 of them, which is 214 tickets, so 36 differ. On accuracy, 0.628 against 0.644. That gap is four tickets. So shadow tells you the new model isn't broken, and not a lot more than that.
Canary: turn the dial
Canary mode is the same function plus one line. bucket hashes the ticket ID into a number from 0 to 99, so the same ticket always lands in the same place. Anything under the share goes to the new model. Raise the share from 10 to 50, and every ticket that was in stays in while more join.
At each step a guard decides whether to go on:
def guard(base, cand):
"""Reasons to stop; empty means go on."""
fails = []
if cand < base - MAX_DROP:
fails.append(f"accuracy {cand:.3f} below "
f"{base:.3f} minus {MAX_DROP}")
return fails
release.py canary loops over the shares (10, 50), scores both models on the canary tickets only, and promotes v2 if both gates pass:
10% canary: 34 tickets, v1 0.559, v2 0.765, go on
50% canary: 128 tickets, v1 0.648, v2 0.688, go on
promoted: live is now v2
Don't trust the small slice
Don't get excited about that first number. At 10% the gap looks like 0.2, but count the tickets:
| Slice | Tickets | v1 | v2 | Gap in tickets |
|---|---|---|---|---|
| 10% canary | 34 | 0.559 | 0.765 | 7 |
| 50% canary | 128 | 0.648 | 0.688 | 5 |
| All (shadow) | 250 | 0.628 | 0.644 | 4 |
The bigger the slice, the smaller the gap. A small canary is noisy: use it to catch a disaster, not to measure an improvement. Measuring the improvement is the job of an A/B test (A/B Tests for Models).
And look at what the guard asks: did accuracy drop by more than 0.02? So passing means no harm seen, and that's all it means.
We could check accuracy because the answers were sitting in our file. In production they often come late, so a canary gate usually watches faster signals as well, like errors and speed.
Versions and one pointer
So how does switching work? registry.py is a tiny registry: one file per version, and one small state.json holding two names. (Excerpt: the file also has a reset() helper that clears the folder.)
import json
import shutil
from pathlib import Path
import joblib
ROOT = Path(__file__).parent / "registry"
def save(name, model):
joblib.dump(model, ROOT / f"{name}.joblib")
def load(name):
return joblib.load(ROOT / f"{name}.joblib")
def state():
path = ROOT / "state.json"
if not path.exists():
return {"live": None, "previous": None}
return json.loads(path.read_text())
def _write(live, previous):
data = {"live": live, "previous": previous}
(ROOT / "state.json").write_text(json.dumps(data))
return data
def promote(name):
return _write(name, state()["live"])
def rollback():
now = state()
if now["previous"] is None:
raise RuntimeError("nothing to roll back to")
return _write(now["previous"], now["live"])["live"]
promote writes a new name and slides the old one into previous; rollback swaps them back.If there's no previous version, rollback raises an error instead of pretending. Rolling back is one pointer move, because the old model never left the disk. The same idea scales up to MLflow aliases (MLflow Model Registry Aliases). A prompt for a language model can be versioned the same way: one file each, one pointer.
The rollback drill
Now we push a bad model on purpose and take it back. Here is rollback in release.py:
def rollback():
_, X_check, _, y_check = live_split()
good = registry.state()["live"]
before = registry.load(good).predict(X_check)
base = acc(y_check, before)
registry.promote("v3")
now = registry.load("v3").predict(X_check)
bad = acc(y_check, now)
fails = guard(base, bad)
print(f"{good} {base:.3f}, v3 {bad:.3f}:", fails[0])
back = registry.rollback()
after = registry.load(back).predict(X_check)
same = bool((before == after).all())
print("rolled back to :", back)
print("same predictions :", same)
v2 0.644, v3 0.600: accuracy 0.600 below 0.644 minus 0.02
rolled back to : v2
same predictions : True
- Save what v2 predicts on the 250 check tickets.
- Promote v3. It scores 0.600. The floor is 0.644 − 0.02 = 0.624, so the guard prints the reason.
registry.rollback()moves the pointer, and we're on v2 again.- Load that model, predict again, compare with what we saved: same predictions,
True. We checked the result, not just the command.
This step always rolls back, because it's a rehearsal. To make it automatic in production, you'd connect the guard's answer to this same call, and that part isn't built here. The project's six pytest tests check the release code (routing, the guard, the registry), not the model's scores.
Common mistakes
- Random routing per request. Hash a stable ID so the same ticket or customer always lands on the same side.
- Celebrating a 10% canary result. Seven tickets out of 34 is noise. A canary finds disasters.
- Overwriting the old model file on release. Then rollback means retraining. Keep versions, move a pointer.
- Trusting the rollback command. Check the predictions after it, as the drill does.
Recap
| Step | Share answered | What happened here |
|---|---|---|
| Shadow | 0% | v2 ran on 250 tickets, nobody affected; 0.628 vs 0.644 |
| Canary | 10%, then 50% | Guard passed at both; small slices are noisy |
| Promote | 100% | One pointer: live is now v2 |
| Rollback | back to v2 | Bad v3 (0.600) caught; same predictions confirmed |
Try it yourself
In release.py, change the canary shares from (10, 50) to (5, 50) and see how few tickets that first gate is really judging.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
Next →A/B Tests for Models: Did the New Model Make Things Better for People?
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.