Sub topic 6
Shadow deployment: testing on live traffic with no user impact
This chapter assumes you can read short Python and YAML snippets. It also assumes you know how a model is served behind an HTTP or RPC endpoint, and that you know basic metrics such as accuracy, precision, recall, and latency. Earlier chapters covered offline evaluation, traffic routing, and prediction logging. Here they come together in the first rollout stage that uses live traffic.
What a shadow deployment is
A shadow deployment runs a candidate model on a copy of real production requests. The user still receives the stable model's response. The candidate's response is logged and never returned.
Offline evaluation uses historical data. Shadowing uses today's traffic, with its real input distribution, malformed payloads, traffic spikes, and upstream quirks. Since no user sees the candidate's output, the risk to users is close to zero.
Shadowing answers these questions:
- Does the candidate run on production inputs without crashing or timing out?
- Does it meet latency and resource targets at real request rates?
- How often does it disagree with the stable model, and on which kinds of requests?
- Do its input features match what it saw in training?
Shadowing cannot answer whether users or the business are better off. No user acts on the candidate's output, so there is no behavioral outcome to measure. That question needs a canary or an A/B test.
Where to mirror traffic
You can copy requests in three places. Each trades simplicity against control.
| Mirror point | How it works | Strength | Weakness |
|---|---|---|---|
| Service mesh or proxy | The mesh duplicates the request and discards the mirror's response | No application code changes | Pairing outputs needs a shared request ID, and you have little control over sampling |
| Application code | The serving code calls the candidate in a background task | Full control over sampling, timeouts, and logging | You must write and maintain it, and a bug can affect the stable path |
| Log replay | A consumer reads logged requests and sends them to the candidate | Zero effect on live latency, and you can replay old traffic | Not real time, and features that depend on current state may be stale |
In Istio, mirroring is a mirror field on the route, as in this example.
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: fraud-model
spec:
hosts:
- fraud-model
http:
- route:
- destination:
host: fraud-model
subset: stable
mirror:
host: fraud-model
subset: candidate
mirrorPercentage:
value: 10.0The subsets stable and candidate must be defined in a matching DestinationRule. The proxy sends the mirrored request without waiting for its response, and it discards that response. The mirrored request is sent with the host name changed to the shadow name, so it is recognizable in logs.
Shadowing in application code
When you need control over timeouts and logging, mirror inside the service. The key rule is that the user's response never waits on the candidate.
import asyncio
import logging
log = logging.getLogger("shadow")
_background = set()
async def handle(request, stable, candidate):
response = await stable.predict(request)
task = asyncio.create_task(shadow(request, response, candidate))
_background.add(task)
task.add_done_callback(_background.discard)
return response
async def shadow(request, stable_response, candidate):
try:
candidate_response = await asyncio.wait_for(candidate.predict(request), timeout=0.5)
log.info("shadow_pair", extra={"stable": stable_response, "candidate": candidate_response})
except Exception:
log.warning("shadow_failed", exc_info=True)Several details in this code matter.
- The stable response is awaited first, then returned. The candidate task starts after the stable prediction finishes, so it cannot delay the user.
- The task set holds references. The event loop keeps only weak references to tasks. Without
_background, a task can be garbage collected before it finishes. wait_forbounds the candidate. A hung candidate cannot accumulate unbounded work.- Failures are logged and swallowed. A candidate exception must never propagate to the caller.
Ways shadowing can still hurt users
"No user impact" is a goal. You have to engineer it, because several failure modes can leak the candidate's effects into production.
- Shared resources. The candidate competes for CPU, memory, a GPU, a feature store, or a database. A slow candidate can starve the stable path. Give it separate replicas and rate limits, and watch the shared dependencies.
- Side effects. If the candidate's code path writes to a database, sends a notification, charges a card, or updates a counter, each mirrored request repeats that action. Shadow only read-only prediction paths, or use a sandboxed backend for any writes.
- Stateful features. Features such as "number of requests in the last hour" can be updated by the request itself. A mirrored request that updates state double counts it.
- Load amplification. Mirroring 100% of traffic doubles the request volume to shared upstreams. Start with a sample, such as 1% to 10%, and raise it as you confirm capacity.
- Privacy and data handling. Logged pairs contain request data. Apply the same retention, access, and masking rules as for production prediction logs.
What to compare
A shadow run produces paired records: the stable output and the candidate output for the same request. Each pair needs a shared request ID, a model version for each side, a timestamp, the input features or a reference to them, and the latency of each call. Chapter on prediction logging covers the schema. What matters here is how you read the pairs.
System metrics
These need no labels and are available immediately.
- Candidate error rate and timeout rate.
- Latency percentiles (p50, p95, p99) under real load, compared with the stable model.
- Memory, CPU, or GPU use per request.
- Rate of invalid outputs, such as NaN scores or values outside the expected range.
Agreement and distribution metrics
These also need no labels. They show where the two models differ, not which one is right.
- Agreement rate. For a classifier, the share of requests where both models predict the same class. For a regressor, the distribution of the difference or ratio.
- Score distribution shift. Compare the histograms of the two models' scores. A candidate that outputs far more high scores than the stable model changes downstream behavior even if its accuracy is similar.
- Disagreement slices. Break disagreement down by segment, such as region, device, or input length. A high overall agreement rate can hide a segment where the candidate behaves very differently.
- Input feature drift. Check that the live feature distributions match training. A candidate that looks bad in shadow may have a feature pipeline mismatch, not a modeling problem.
A minimal comparison over logged pairs might look like this.
def summarize(pairs):
total = len(pairs)
agree = sum(1 for p in pairs if p["stable"] == p["candidate"])
return {"pairs": total, "agreement": agree / total if total else None}
pairs = [
{"stable": "approve", "candidate": "approve"},
{"stable": "approve", "candidate": "review"},
{"stable": "decline", "candidate": "decline"},
{"stable": "approve", "candidate": "approve"},
]
print(summarize(pairs))Label-based metrics
If ground truth arrives later, you can join it to the logged pairs and compute accuracy, precision, and recall for both models on the same real requests. This is a strong result, because both models are scored on the identical sample. Labels often arrive late or only for some outcomes, and a later chapter covers that problem. One caveat applies even here. If the stable model's decisions influence which labels exist, for example only approved loans produce repayment data, the labels are biased toward the stable model's choices.
Reading disagreement
Disagreement is a prompt to investigate. It is not a verdict. The candidate may be fixing the stable model's errors, or introducing new ones. To tell the difference, sample disagreeing pairs and review them by hand or with labels. Pay attention to the direction. If the candidate moves 3% of requests from "approve" to "review", ask what that does to review workload and to the approval rate.
Set expectations before the run. Decide what agreement range you consider plausible for the change. A small retrain should agree with the stable model on the vast majority of requests. A new architecture may differ more. A surprisingly high agreement rate for a model that was supposed to change behavior can mean the candidate is misconfigured, for example pointing at the same artifact.
How long to run and what exit looks like
Run the shadow long enough to cover the cycles in your traffic, such as weekday and weekend patterns, and enough requests for rare segments to appear. A few hours of weekday traffic will miss weekend behavior.
Define exit criteria before you start. For example:
- Candidate error and timeout rates at or below the stable model's, within an agreed tolerance.
- p95 latency within the target budget at production request rates.
- No invalid outputs, and no unexplained disagreement in key segments.
- Feature distributions match expectations.
When the criteria hold, move to a canary release, where a small share of users receives the candidate's output. If they do not hold, fix the candidate and shadow again.
Common mistakes
- Treating agreement as quality. Two models can agree and both be wrong. Agreement shows consistency, not correctness.
- Mirroring requests without a shared ID. You cannot pair outputs, so you cannot compare them.
- Running the candidate on a different feature path. If the shadow gets features from a different pipeline, the results do not describe what a real release would do.
- Ignoring the candidate's cost. Shadowing a large model at full traffic can be expensive. Sample deliberately.
- Letting the shadow run indefinitely. It consumes resources and the logs accumulate. Set an end date.
Exercise
Your team shadows a new recommendation model at 100% of traffic. Agreement with the stable model is 97%, and p95 latency of the candidate is within budget. A colleague says the model is therefore safe to release to all users and better than the stable one. Name two claims in that statement that the shadow run does not support, and say what each needs.
Show answer
First, "safe to release to all users" is not shown, because shadow traffic does not expose users to the candidate's output, so it cannot reveal user-facing or business harm. Guardrail metrics on real exposure need a canary release. Second, "better than the stable one" is not shown, because 97% agreement only says the models are similar. It says nothing about which is correct, and no user acted on the candidate's recommendations. Labels joined to the pairs, or an A/B test against a business outcome, are needed. The 3% disagreement should also be sliced by segment, since it may be concentrated in one group.