Sub topic 7
Canary release: exposing a small share of users in stages
This chapter assumes you can serve a model behind an HTTP or RPC endpoint, read short Python and YAML snippets, and interpret error rate, latency, and proportions. It builds on traffic splitting, prediction logging, and guardrail metrics from earlier chapters, and it comes after shadow deployment.
What a canary release answers
A canary release sends a small share of real traffic to the candidate model and lets users receive its responses. The share grows in stages while you watch the metrics. The name comes from the canary in the coal mine: a small, exposed group warns you before everyone is harmed.
A shadow deployment already showed that the candidate runs on live inputs without crashing. It cannot show what happens when the candidate's output reaches a user, or what the candidate costs under real load as a primary service. A canary answers this question: is the candidate safe to serve to users, and does it hold up as its traffic share grows?
A canary limits blast radius, which is the number of users hurt by a bad release. If the candidate is broken and receives 5% of traffic, at most about 5% of requests are affected, and only until you roll back. A canary is not a controlled experiment about business value. Its groups are not necessarily randomized per user, and you usually stop watching after a few hours or days. Use an A/B test when you need to prove an improvement.
| Strategy | Users see candidate output? | Main risk removed | Question answered |
|---|---|---|---|
| Shadow | No | Crashes, latency, and output drift on live inputs | Does it run correctly on real traffic? |
| Canary | Yes, a small and growing share | Harm at full scale | Is it safe to serve? |
| A/B test | Yes, a fixed randomized share | Wrong conclusions about value | Is it better on the business outcome? |
Staged exposure
A typical canary uses stages such as 1%, 5%, 25%, 50%, and 100%. Each stage has a hold period, and the candidate advances only if its guardrails pass.
The stage sizes are a trade-off:
- Early stages are small because their purpose is to catch loud failures: errors, timeouts, memory growth, and malformed outputs. These show up within a few hundred requests.
- Later stages are larger because subtle problems need volume. A 0.5 percentage point rise in error rate is invisible at 200 requests and obvious at 20,000.
- Hold times must cover the traffic cycle. If your traffic has a daily peak, a one-hour canary at 3 a.m. proves little about peak load. Hold at least one stage through a representative busy period.
Implementing the split
In a service mesh, a weighted route does the splitting. This Istio VirtualService sends 95% of requests to the stable subset and 5% to the candidate:
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: fraud-model
spec:
hosts:
- fraud-model
http:
- route:
- destination:
host: fraud-model
subset: stable
weight: 95
- destination:
host: fraud-model
subset: candidate
weight: 5The subsets must be defined in a matching DestinationRule. They select pods by label, so stable and candidate deployments need different version labels:
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: fraud-model
spec:
host: fraud-model
subsets:
- name: stable
labels:
version: v1
- name: candidate
labels:
version: v2Advancing a stage means changing the weights, for example to 75 and 25, and applying the manifest. Weights in a VirtualService must add up to 100.
Request-level versus user-level assignment
A weighted route assigns each request independently. One user might get the stable model on one click and the candidate on the next. For a stateless fraud score this is often acceptable. For a recommender or ranker it makes the experience inconsistent and makes per-user metrics hard to read.
If you need sticky assignment, hash a stable identifier with a salt, as in the earlier traffic-splitting chapter:
import hashlib
def bucket(unit_id: str, salt: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest()
return int(digest, 16) % buckets
def choose_variant(unit_id: str, salt: str, candidate_percent: float) -> str:
threshold = int(candidate_percent * 100) # percent of 10000 buckets
return "candidate" if bucket(unit_id, salt) < threshold else "stable"
print(choose_variant("user-123", "ranker-v2-exp1", 5))Because the threshold only grows as the canary advances, a user who was in the 5% bucket stays in the candidate group at 25%. Nobody flips back to stable mid-rollout. Keep the same salt for the whole rollout, because changing it reshuffles everyone.
Guardrails that gate each stage
A guardrail is a metric with a threshold that the candidate must not violate. Choose guardrails from three groups:
- System metrics: error rate, timeouts, p95 and p99 latency, CPU and memory.
- Model metrics: prediction distribution, such as the share of positive predictions, score histograms, and the rate of null or out-of-range outputs. These work without labels.
- Business metrics: conversion, refunds, escalations to a human. These are often delayed, so use them as slower guardrails.
Compare the candidate against the stable model over the same time window, not against a historical baseline. Traffic mix changes by hour, and a simultaneous comparison cancels that out. This is a main advantage of running both versions side by side.
A simple gate compares error rate and p95 latency:
def canary_gate(stable: dict, candidate: dict,
max_error_increase: float = 0.005,
max_latency_ratio: float = 1.10) -> bool:
error_ok = candidate["error_rate"] <= stable["error_rate"] + max_error_increase
latency_ok = candidate["p95_latency_ms"] <= stable["p95_latency_ms"] * max_latency_ratio
return error_ok and latency_ok
stable = {"error_rate": 0.002, "p95_latency_ms": 120}
candidate = {"error_rate": 0.003, "p95_latency_ms": 128}
print(canary_gate(stable, candidate))This prints True: the error rate is 0.1 points above stable, within the 0.5 point allowance, and 128 ms is under the 132 ms limit.
Minimum sample size
The gate above has a flaw. With 20 requests and zero errors, the candidate passes, but 20 requests prove nothing. Add a minimum request count before any decision. The sketch below uses canary_gate and returns one of three actions:
STAGES = [1, 5, 25, 50, 100]
def canary_gate(stable, candidate, max_error_increase=0.005, max_latency_ratio=1.10):
error_ok = candidate["error_rate"] <= stable["error_rate"] + max_error_increase
latency_ok = candidate["p95_latency_ms"] <= stable["p95_latency_ms"] * max_latency_ratio
return error_ok and latency_ok
def next_action(stage_index, stable, candidate, min_requests=2000):
if candidate["requests"] < min_requests:
return "hold" # not enough data to decide
if not canary_gate(stable, candidate):
return "rollback"
if STAGES[stage_index] == 100:
return "promote"
return f"advance_to_{STAGES[stage_index + 1]}"
stable = {"error_rate": 0.002, "p95_latency_ms": 120}
candidate = {"error_rate": 0.003, "p95_latency_ms": 128, "requests": 3500}
print(next_action(1, stable, candidate))This prints advance_to_25. Setting requests to 500 would print hold. Raising error_rate to 0.02 would print rollback.
Common failure modes
- Healthy system metrics, bad predictions. A candidate can respond fast with no errors and still output garbage, for example from a feature-pipeline mismatch. Include prediction-distribution guardrails, not only system metrics.
- Noisy small stages. A 1% stage on a low-traffic service may take days to collect enough requests. Start at a larger share, or accept a longer hold.
- Unequal conditions. If the candidate pods are on cold caches or smaller instances, latency differences reflect infrastructure, not the model. Give both versions the same resources and warm the candidate first.
- Cached or sticky routing. Client-side caches and connection reuse can make the actual split differ from the configured weights. Verify the split from request logs and compare it with the configured weight.
- Slow rollback. If rollback requires a rebuild, the canary does not limit blast radius. Rollback should be a weight change back to 100/0, applied in seconds, with the stable version still running.
Canary versus A/B test
A canary and an A/B test look similar because both split traffic. The difference is purpose and rigor:
- A canary protects. It is judged by guardrails, advances in stages, and ends in a promote-or-rollback decision.
- An A/B test measures. It holds a fixed randomized split, uses a sample size computed in advance, and ends with a significance test on a business outcome.
A canary that passes its guardrails has shown the candidate is not worse on those metrics. It has not shown it is better. Teams often run a canary first for safety, then an A/B test at a fixed split to measure value.
Exercise
A new ranking model runs as a canary at 5% for two hours. Error rate and p95 latency match the stable model, so the team promotes it. A week later, click-through has dropped. Name two reasons the canary could not catch this, and one change that would help.
Show answer
First, the guardrails covered only system metrics, and click-through is a business outcome that needs enough data and time to measure. Second, two hours at 5% may be too short and too small to show a small drop in a delayed or noisy metric, and it may have missed the weekly traffic cycle. Adding a business guardrail (click-through compared with stable over the same window), a minimum sample size, and a hold that spans a representative period would help. Following the canary with an A/B test on click-through would also help.