Sub topic 6
Canary and blue-green releases make rollback cheap
This chapter assumes you know how a model is served behind an HTTP endpoint, how a Kubernetes Deployment and Service work, and what a registry alias is (covered in the previous chapters). It also assumes you can read short Python and YAML. The goal here is to show how the way you release a model version determines how fast and how safely you can undo it.
Release strategy sets the cost of rollback
A rollback is only as fast as the mechanism you built before the incident. If a new model version replaces the old one in place, undoing it means redeploying the old version while users are already seeing errors. If the old version is still running next to the new one, undoing it means changing where traffic goes. That change takes seconds.
Canary and blue-green releases both keep the previous version alive during the release. They differ in how much traffic the new version receives and how quickly.
| Property | Rolling update (in place) | Canary | Blue-green |
|---|---|---|---|
| Old version running during release | Partly, then removed | Yes, serves most traffic | Yes, serves all traffic until the switch |
| Share of users exposed to a bad version | Grows quickly to 100% | Small and controlled | 0% before the switch, 100% after |
| Rollback action | Redeploy old version | Send canary traffic to zero | Move traffic back to the old environment |
| Extra capacity needed | Small | Small | Roughly double during the release |
| Main risk | Blast radius | Slow or noisy signals | Cost, and a bad version affecting everyone at once |
Canary releases
A canary release sends a small share of live traffic to the new version while the current version serves the rest. You watch the canary's metrics. If they stay healthy, you raise the share in stages. If they do not, you set the share back to zero.
The rollback is cheap for two reasons. Only a small share of requests ever reached the bad version, so the damage is limited. And the stable version never stopped running, so no restart or model load is needed.
A typical canary progression
- Deploy the new version with no traffic and confirm it loads and passes a health check.
- Send 5% of traffic. Hold until enough requests have arrived to compare metrics.
- If the gate passes, move to 25%, then 50%, then 100%.
- After 100%, keep the old version available for a defined period, so a late-appearing problem is still a traffic change and not a redeploy.
Compare against a live baseline
A canary gate should compare the canary against the stable version over the same time window, not against last week's numbers. Traffic mix changes by hour and by day. A fixed threshold such as "error rate under 2%" can pass while the new version is clearly worse than the old one on the same traffic. The rule from the earlier chapter on triggers applies here: use a relative limit against the baseline and an absolute limit for service-level objectives.
Splitting traffic in Kubernetes
The simplest way to get a canary is two Deployments behind one Service. The Service selects only on app, so it sends requests to pods from both Deployments. The traffic share is roughly the ratio of pod counts.
apiVersion: v1
kind: Service
metadata:
name: model-server
spec:
selector:
app: model-server
ports:
- port: 80
targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-server-stable
spec:
replicas: 9
selector:
matchLabels:
app: model-server
track: stable
template:
metadata:
labels:
app: model-server
track: stable
spec:
containers:
- name: server
image: registry.example.com/fraud-detector:3
ports:
- containerPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-server-canary
spec:
replicas: 1
selector:
matchLabels:
app: model-server
track: canary
template:
metadata:
labels:
app: model-server
track: canary
spec:
containers:
- name: server
image: registry.example.com/fraud-detector:4
ports:
- containerPort: 8080With 9 stable pods and 1 canary pod, about 10% of requests reach version 4. Rolling back is one command:
kubectl scale deployment/model-server-canary --replicas=0The stable pods were never touched, so there is nothing to wait for except the removal of the canary pods from the Service endpoints.
Limits of replica-ratio canaries
- The split is approximate. Kubernetes Services balance across connections, not requests, so long-lived HTTP/2 or gRPC connections can skew the share a lot.
- You cannot send 1% of traffic unless you run 100 pods. For finer control, use an ingress controller, service mesh, or gateway that supports weighted routing.
- A user can see answers from both versions in one session unless you add sticky routing, for example by hashing a user or account ID. This matters when the new model changes scores users compare, such as prices or risk labels.
- Autoscalers change pod counts, which changes the ratio. Pin the canary replicas, or use weights that do not depend on pod counts.
Edge cases: a canary can pass and still be wrong
- Too few requests. At 5% of a low-traffic service, the canary may see a handful of requests per hour. Error rates from tiny samples are noise. Set a minimum request count before a gate may pass.
- Delayed labels. Accuracy, precision, and similar metrics need ground truth, which can arrive days later in fraud or churn use cases. During a canary you can usually see only service health (errors, latency) and proxy signals such as prediction distribution. A canary proves the version is not broken. It does not prove the version is better.
- Segment effects. An overall metric can hide a regression for one region, language, or customer type. Check the segments that matter for your product.
- Cache and warm-up. A freshly started pod has cold caches and a model that may still be loading, so its first minutes can show high latency that is not a model defect. Exclude a warm-up period from the gate, but do not make it so long that real problems hide.
A canary gate in Python
The gate below extends the rollback rule from earlier. It returns one of three decisions, because "wait for more data" is a valid answer. It takes request counts and metrics for the canary and the baseline, collected from the same window.
def canary_decision(canary, baseline, min_requests=500,
max_error_increase=0.02, p95_limit_ms=250):
"""Return 'wait', 'promote', or 'rollback' for one canary stage."""
if canary["requests"] < min_requests:
return "wait"
error_regressed = (
canary["error_rate"] - baseline["error_rate"]
) > max_error_increase
too_slow = canary["p95_ms"] > p95_limit_ms
if error_regressed or too_slow:
return "rollback"
return "promote"
stages = [
("5%", {"requests": 120, "error_rate": 0.030, "p95_ms": 140}),
("5%", {"requests": 640, "error_rate": 0.031, "p95_ms": 150}),
("25%", {"requests": 3100, "error_rate": 0.070, "p95_ms": 160}),
]
baseline = {"requests": 12000, "error_rate": 0.030, "p95_ms": 135}
for stage, canary in stages:
print(stage, canary_decision(canary, baseline))Running this prints wait for the first sample (too few requests), promote for the second, and rollback for the third, where the error rate is 4 percentage points above the baseline.
Blue-green releases
A blue-green release runs two complete environments. Blue is the version currently serving users. Green is the new version, deployed and tested but receiving no production traffic. When green is ready, you switch all traffic from blue to green in one step. Blue stays running and idle, ready to take traffic back.
Rollback is the same switch in reverse. Because blue is still warm, with the model loaded and caches populated, recovery does not depend on image pulls, scheduling, or model loading.
Blue-green with a Service selector
In Kubernetes, the Service selector is the pointer. Two Deployments carry a track label, blue and green, and the Service selects one of them.
# Switch traffic from blue to green
kubectl patch service model-server \
-p '{"spec":{"selector":{"app":"model-server","track":"green"}}}'
# Roll back: point the Service at blue again
kubectl patch service model-server \
-p '{"spec":{"selector":{"app":"model-server","track":"blue"}}}'
# Confirm which pods are behind the Service
kubectl get endpoints model-serverThis assumes the Service and both Deployments already exist with matching labels, as in the canary manifests above but with track: blue and track: green.
Costs and edge cases
- Double capacity. Both environments need enough pods to carry full traffic. For GPU-backed models this is expensive. Teams often keep blue for a fixed window, such as an hour or a day, and then scale it down. Decide that window in advance, because it is also the window in which rollback is a one-line change.
- All-or-nothing exposure. After the switch, every user sees the new version. Blue-green gives fast recovery, not a limited blast radius. You can combine it with a canary: send a small share to green first, then switch fully.
- Shared state. Both environments often use the same feature store, database, or message queue. If green writes data in a new format, blue may not read it after a rollback. The next chapter covers compatibility checks in detail. For release design, the rule is that anything shared must be backward compatible for as long as blue might become live again.
- Connection draining. On switch, in-flight requests to the old environment must finish. Set a termination grace period on the pods, and do not scale blue down until its connections are drained.
- Stateful or streaming clients. Clients holding long connections stay on the old environment after a switch. Check how your clients reconnect, or the "switch" will take effect slowly.
Choosing a strategy
- Choose a canary when you want to limit how many users a bad model can affect, and your traffic is high enough to produce meaningful metrics in minutes. It suits models whose failures show up in service signals.
- Choose blue-green when you need an instant, complete cutover and an instant way back, for example when the model change is coupled to a schema change, or the service has too little traffic for a canary to be informative.
- Use both for high-risk changes: pre-test green with synthetic or replayed traffic, send a small canary share, then switch fully while blue remains on standby.
There is a related technique, shadow deployment, where the new version receives a copy of live requests but its responses are discarded. It carries no user risk and is useful before a canary, but it cannot show how users respond to the new version's outputs.
Where this fits with the deployment pointer
Both strategies are ways of operating the pointer from the earlier chapter. In a canary, the pointer is a set of weights. In blue-green, it is a single selector. Keep the pointer's change history, so that during an incident you can see which version each environment was running and what the last known good state was.
Exercise
A fraud model's canary receives 5% of traffic. After 30 minutes it has handled 90 requests with a 0% error rate, while the stable version shows 3% errors on its 1,800 requests. The team wants to promote to 25% because the canary looks better. What is wrong with that decision, and what should the gate do?
Show answer
The canary has too few requests for its error rate to mean anything. With 90 requests and a true error rate of 3%, seeing zero errors is quite likely by chance. The gate should return "wait" until the canary reaches a minimum request count, for example 500, and only then compare it with the baseline. The team should also remember that error rate says nothing about fraud detection quality, which needs labels that arrive later, so promotion based on service metrics proves only that the version is not broken.
Exercise
You run blue-green with the Service selector patched from blue to green. Twenty minutes later, error rates spike. You patch the selector back to blue, but errors continue for a few minutes, and some of them look like they come from data written by green. Name two reasons recovery may not be immediate, and one release-design rule that would have prevented the data problem.
Show answer
First, in-flight requests and long-lived client connections stay on green until they finish or reconnect, so the switch takes effect gradually. Second, shared state written by green, such as features or records in a new format, may be unreadable by blue. The prevention rule is that anything shared between environments must stay backward compatible for as long as blue could become live again, so green must not write formats that blue cannot read.