Sub topic 15
Shadow Deployments and Canary Releases
Earlier chapters showed how to prevent skew with shared transforms, bundled pipelines, and parity tests, and how to detect it by comparing logged serving features with training features. This chapter covers the last safeguard before a model reaches all users: releasing it gradually, so that any skew that slipped through shows up while the damage is still small.
This chapter assumes you can read basic Python, know what a model endpoint is, and have seen PSI or KS comparisons from the previous chapters.
Why a release strategy matters for skew
Parity tests and schema validation run on data you chose in advance. Production traffic contains inputs you did not anticipate: new categories, null patterns, unusual timestamps, upstream schema changes. A new model version can pass every offline check and still receive features that differ from its training data.
Replacing the old model everywhere at once means the first real evidence of skew arrives when all users are affected. Two techniques give you that evidence earlier:
- A shadow deployment runs the candidate model on real traffic, but its predictions are never returned to users.
- A canary release sends a small share of live traffic to the candidate and returns its predictions to those users.
Shadow mode costs users nothing if the candidate is wrong. A canary exposes a few users, but it tests the full path, including how downstream systems react to the predictions.
Shadow deployments
In a shadow deployment, every request (or a sample) goes to both models. The user receives the stable model's answer. The candidate's features and score are logged and analyzed later.
For skew, the most useful part is the candidate's feature log. Because the candidate runs its own preprocessing in the production environment, the logged features reveal whether its serving path produces the values the training path would. You can compare them against the training distribution using the PSI and KS checks from the previous chapter.
The sketch below shows the pattern. The two models are stubs so that the code runs as written.
import json
import logging
import uuid
from concurrent.futures import ThreadPoolExecutor
logging.basicConfig(level=logging.INFO, format="%(message)s")
shadow_log = logging.getLogger("shadow")
pool = ThreadPoolExecutor(max_workers=2)
def stable_predict(request: dict) -> float:
return 0.2 if (request.get("age") or 0) < 40 else 0.6
def candidate_features(request: dict) -> dict:
# The candidate's own serving-time feature code.
return {"age": request.get("age") if request.get("age") is not None else 40.0}
def candidate_predict(features: dict) -> float:
return 0.2 if features["age"] < 40 else 0.6
def run_shadow(request_id: str, request: dict) -> None:
try:
features = candidate_features(request)
score = candidate_predict(features)
shadow_log.info(json.dumps(
{"request_id": request_id, "features": features, "score": score}
))
except Exception:
# A failing shadow must never affect the user-facing response.
shadow_log.exception("shadow failure for %s", request_id)
def handle(request: dict) -> float:
request_id = str(uuid.uuid4())
pool.submit(run_shadow, request_id, request) # asynchronous, result ignored
return stable_predict(request)
print(handle({"age": 30}))
print(handle({"age": None}))
pool.shutdown(wait=True)Three design points matter here:
- The shadow call runs asynchronously. If it ran inline, a slow candidate would add latency for every user.
- Exceptions in the shadow path are caught and logged. Exception rates are themselves a skew signal, since a new categorical value or a null in an unexpected field often shows up first as a crash.
- Each record carries a
request_id, so you can join the candidate's log to the stable model's log for the same request.
What to compare in shadow mode
| Comparison | What it reveals | Typical check |
|---|---|---|
| Candidate serving features vs. training features | Skew in the candidate's own serving path | PSI or KS per feature |
| Candidate features vs. stable model features, same request | Differences between two implementations of the same feature | Exact or tolerance-based match |
| Candidate scores vs. stable scores, same request | Unexpected behavior change | Score difference distribution, rank correlation |
| Candidate error and null rates | Schema and missing-value problems | Rate compared with a threshold |
A score difference is not automatically a problem. A better model should disagree with the old one on some requests. Large disagreement that traces back to one feature with a shifted distribution is the skew pattern to look for.
Limits of shadow mode
Shadow mode cannot tell you whether the candidate's predictions are good, only whether its inputs and outputs look plausible. Labels usually arrive later, and the user never acted on the candidate's score. Feedback loops are also untested. If the model's output influences which items users see, the data it will see after launch differs from the data it sees in shadow. You also pay for double compute while the shadow runs.
Canary releases
A canary sends a small share of real traffic to the candidate and returns its predictions. That makes outcome metrics measurable: click-through, conversion, error rate, or whatever the product tracks. It also tests the real serving path end to end.
Routing users consistently
Route by a stable key such as the user ID, not by random choice per request. Otherwise the same user flips between models, which makes metrics noisy and the experience inconsistent. A hash gives a deterministic assignment.
import hashlib
def bucket(user_id: str, buckets: int = 100) -> int:
digest = hashlib.sha256(user_id.encode("utf-8")).hexdigest()
return int(digest, 16) % buckets
def route(user_id: str, canary_percent: int) -> str:
return "candidate" if bucket(user_id) < canary_percent else "stable"
assignments = [route(f"user-{i}", canary_percent=5) for i in range(10_000)]
print(assignments.count("candidate") / len(assignments)) # close to 0.05Raising canary_percent from 5 to 20 keeps the original 5 percent of users in the candidate group, because they remain below the new threshold.
Choosing a canary size and duration
The canary must be large enough to produce a stable estimate of each feature distribution and metric, and long enough to cover the traffic cycles that matter. A canary that runs only during weekday daytime misses weekend behavior and batch jobs that run overnight. A common progression is 1 percent, 5 percent, 25 percent, then 100 percent, with a hold at each step long enough to see a full daily cycle.
Gates that stop the rollout
Define the stop conditions before the canary starts, not after you see the numbers. Useful gates for skew include:
- Per-feature PSI against the training data stays below your agreed threshold (0.2 is a common alarm level; see the previous chapter).
- Null rate and out-of-vocabulary rate per feature stay within a margin of the training values.
- Request error rate and latency are no worse than the stable model.
- Prediction score distribution is close to the offline validation score distribution.
- Outcome metrics, once labels or proxies arrive, are not worse than the stable model by more than a stated margin.
Combining the two
Most teams use both stages in sequence. Shadow first, because it exposes feature and schema problems with zero user impact. Then a canary, because only live traffic can show how the predictions affect outcomes. Keep the earlier chapters' tools running through both stages: the same serving-feature log and the same PSI and KS checks apply to the shadow and canary groups.
Keep the rollback path simple. The stable model should stay deployed and warm until the candidate has run at full traffic for a full cycle. Rolling back should be a routing change (set canary_percent to 0), not a redeploy.
Common mistakes
- Shadow traffic that is not representative. If the shadow receives only a sample biased toward certain endpoints or regions, the feature log misses the skew that affects the rest.
- Candidate reading from a different feature source. If the shadow path reads features from a staging store, you test the staging pipeline, not production. Point it at the same source the model will use.
- Shared mutable state. If candidate and stable code share a cache or a feature-store write path, the shadow can change what the stable model sees.
- No gate defined in advance. Without thresholds, a borderline result becomes an argument instead of a decision.
- Logging only scores. Scores alone cannot localize skew to a feature. Log the features the candidate received, as the earlier logging chapter requires.
Exercise
Your candidate model passed offline parity tests. In shadow mode for two days, the logged feature income for the candidate has a PSI of 0.45 against the training data, while the stable model's logged income has a PSI of 0.03 against its own training data. Request volumes and user mix are the same for both. What does this suggest, and what should you do before starting a canary?
Show answer
The PSI difference under identical traffic points to skew in the candidate's serving path for income, not to real-world drift, since the stable model sees the same population without a shift. Compare the candidate's logged income with the stable model's value for the same request_id to find the difference, such as a different unit, currency, null fill, or data source. Fix the feature code or source, rerun the parity test with a case that reproduces the problem, and repeat the shadow stage until PSI is acceptable. Do not start the canary yet, because it would send the faulty predictions to real users.