Columns › 6. Deploying the system › Part 32
Blue-Green and Canary Releases: Doing Them Right and What to Watch For
藍綠部署與灰度發布:怎麼做才對、要注意什麼
A rolling update puts every user on the new version at once. This article uses diagrams to show when rolling updates, blue-green, canary (grey) and shadow releases fit, how metrics decide whether to continue or abort, how to implement them with Argo Rollouts and the Gateway API, and what to watch for in databases, events, consumers and payments while two versions run side by side.
In this article
- What this article solves
- Step 1: Tell deploying and releasing apart
- Step 2: Rolling updates — what the defaults can and cannot do
- Step 3: Blue-green — two environments, one switch
- Step 4: Canary (grey release) — a small group first
- Step 5: Let metrics decide whether to continue or abort
- Step 6: Shadow traffic — watch, never answer
- Step 7: Feature flags — separating going live from opening up
- Step 8: Implementing it on Kubernetes with Argo Rollouts
- Step 9: Using it with Argo CD
- Step 10: What to watch while old and new run side by side
- Step 11: Rollback, cost and a pre-release checklist
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “GitOps with Argo CD: Let the Cluster Follow git on Its Own”, made the cluster follow git: CI changes the image tag, Argo CD syncs it to the cluster, and rolling back is a git revert. But what happens after the sync is still the Deployment's default rolling update: within a few minutes every pod runs the new version, and every user meets it at the same time. This article is about handing a new version to users one step at a time.
What this article solves
Here is how one of the shop's releases went wrong. A new version of the order service changed how it read an order's total. The unit tests passed, /readyz returned 200, and the rolling update finished in three minutes. Then the checkout error rate jumped from 0.1% to 30%. The on-call engineer saw the alert, confirmed it was the new version, reverted the commit in the config repository, waited for Argo CD to sync and for another rolling update to finish: more than ten minutes in all, and every user who tried to check out in that window was affected.
Looking back, the problem was not that the tests were too thin. It was how the release was done:
- Everyone got the new version at once: there was no buffer of "a small group first".
- A health check is not business health: a readiness probe answers "is the process up?", not "does checkout still work?".
- Rollback was slow:
rollout undoand a git revert are both another rolling update, pulling images and waiting for pods to become ready. - Nobody was watching the right numbers: the error rate waited for an alert, and the alert thresholds were designed for normal days, not for releases.
This article answers, in order:
- The difference between deploying and releasing; what rolling updates, blue-green, canary (also called gradual or "grey" releases) and shadow traffic are, and which situation calls for which.
- What the rolling update settings can and cannot do.
- How to do blue-green: two environments, a switch, rollback in seconds, and its costs and traps.
- How to do a canary: how to order the percentages, how long each stage lasts, and whether to split by weight or by user.
- How metrics can decide automatically whether to continue or abort, including how a Go service puts its version into metrics and how many samples are enough.
- How to use shadow traffic, and its biggest danger: duplicated side effects.
- How feature flags and deployment strategies divide the work.
- Implementing it on Kubernetes with Argo Rollouts, working together with Argo CD.
- What to watch for while old and new versions run side by side (database, APIs and events, consumers, scheduled jobs, caches and payments), and a pre-release checklist.
Step 1: Tell deploying and releasing apart
The two words are usually used interchangeably, but separating them makes many techniques obvious:
- Deploy: get the new version of the code running in production.
- Release: let users start experiencing the new version's behaviour.
A rolling update ties the two together: once the pods are replaced, users are on the new code. Every strategy in this article is, at heart, a way of pulling them apart: deploy first, let only part of the traffic (or none) reach the new version, and widen it once it looks fine.
Figure: a rolling update replaces pods in batches; blue-green switches everything at once; a canary gives the new version a small share first; shadow traffic copies requests to the new version but throws away its responses.
In Chinese-speaking teams, a "grey release" usually means this canary family of techniques: give it to some users first, then widen gradually. Blue-green is sometimes called a blue-green release. The names matter less than what each one controls:
| Strategy | How traffic moves | Rollback speed | Extra resources | Old and new together | Fits | Does not fit |
|---|---|---|---|---|---|---|
| Rolling update | Batch by batch, following pod counts | Slow (roll again) | Little (a few extra pods) | Throughout the update | Most compatible small changes, internal services | High-risk changes, precise control of the share |
| Blue-green | All at once | Seconds (switch the selector back) | About double around the switch | At the switch, plus in the data layer | Full verification before going live, instant rollback | Tight resources, incompatible database schemas |
| Canary | Widened step by step, by weight or user cohort | Fast (weight back to zero) | A few canary pods | Throughout the release (longer) | Enough traffic, validation with real traffic, high-risk core services | Too little traffic to see a difference, changes that cannot coexist |
| Shadow traffic | Requests copied, responses dropped | Not needed (no user saw it) | Double load on the mirrored path | Yes, but the new version never answers | Rewritten read-only paths, comparing performance and results | Any path with writes or outbound calls, payments above all |
A common misunderstanding is that blue-green or canary lets an incompatible change go out safely. The opposite is true: apart from shadow traffic, every strategy has a period in which old and new versions run at the same time, sharing the same database and the same event stream. A strategy decides how many users meet the new version; it does not make data or message compatibility problems go away. Step 10 deals with that in detail.
Step 2: Rolling updates — what the defaults can and cannot do
The Deployment in “Deploying a Microservice System on Kubernetes” already set the rolling update parameters. Here are just the fields that matter for releases:
# deploy/k8s/base/order/deployment.yaml (only the fields that matter for releases)
apiVersion: apps/v1
kind: Deployment
metadata:
name: order
spec:
minReadySeconds: 10 # count as available only after 10 s of readiness, catching crash-right-after-ready
progressDeadlineSeconds: 300 # mark as failed after 5 minutes without progress; rollout status returns an error
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25% # at most 25% extra new pods
maxUnavailable: 0 # never fewer available pods than desiredmaxSurgeandmaxUnavailablecontrol how much changes per batch. With 4 replicas,maxSurge: 25%andmaxUnavailable: 0mean: start 1 extra new pod, wait until it is ready, stop 1 old pod, repeat.maxUnavailable: 0guarantees capacity never drops, at the cost of one extra pod's resources during the update. Setting both to 0 is invalid, because the update could never move.- The readiness probe decides when a new pod starts receiving traffic. It is the rolling update's only quality check, so
/readyzshould at least confirm the database is reachable and the configuration was read, not just return 200. minReadySecondsrequires a pod to stay ready for a while before it counts as available, catching the "started fine, crashed on the first request" case.progressDeadlineSecondsis the deadline for a stuck update; after it,kubectl rollout statusfails, so CI or Argo CD knows something is wrong. It does not roll back automatically; it only marks the failure.
Note also that a PodDisruptionBudget does not govern rolling updates: a PDB limits evictions (for example during node maintenance), while the pace at which a Deployment replaces its own pods is set by the two parameters above.
What a rolling update cannot do is exactly why the other strategies in this article exist:
- It cannot set a traffic share. The new version gets roughly the share of pods it has, and only briefly while the update runs. Long-lived connections such as gRPC make it even less precise, because a connection sticks to one pod once established.
- It does not look at metrics. As long as readiness passes it keeps going, however high the error rate.
kubectl rollout pausecan stop it halfway by hand, but nobody watches every release and presses pause at the right moment. - Rollback is not instant.
rollout undois another rolling update in the opposite direction. - The same user's requests bounce between old and new versions.
So rolling updates suit most everyday changes: backward compatible, low risk, for services where rolling back a few minutes late is acceptable. The shop's inventory is normally released this way. They do not suit checkout and payment, where every extra minute of errors costs real money.
Step 3: Blue-green — two environments, one switch
Scenario: a new version of payment switches to a new SDK from the payment provider. The team wants to run a full authorisation and void with a test merchant account before any real traffic touches it, and if anything looks wrong after going live, to go back within seconds rather than wait for another rolling update. That is what blue-green solves: deploy the new version completely, verify it completely, then switch all at once; keep the old version so you can switch back at any time.
On Kubernetes, the simplest blue-green needs no extra tooling: two Deployments distinguished by a colour label, and a Service whose selector decides which colour gets traffic.
# order-green: differs from order-blue only in the color label and the image tag
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-green
spec:
replicas: 4
selector:
matchLabels:
app.kubernetes.io/name: order
shop.example.com/color: green
template:
metadata:
labels:
app.kubernetes.io/name: order
shop.example.com/color: green
spec:
containers:
- name: app
image: registry.example.com/shop/order:9f2c1e7a4b30
args: ['serve']
ports:
- name: http
containerPort: 8080
- name: grpc
containerPort: 9090
readinessProbe:
httpGet:
path: /readyz
port: http
---
# The internal Service: its selector decides which colour gets traffic
apiVersion: v1
kind: Service
metadata:
name: order
spec:
selector:
app.kubernetes.io/name: order
shop.example.com/color: blue
ports:
- name: http
port: 8080
targetPort: http
- name: grpc
port: 9090
targetPort: grpc
---
# A Service for testing: always points at the colour that is not live yet
apiVersion: v1
kind: Service
metadata:
name: order-preview
spec:
selector:
app.kubernetes.io/name: order
shop.example.com/color: green
ports:
- name: http
port: 8080
targetPort: http
- name: grpc
port: 9090
targetPort: grpcSwitching and rolling back are just changes to the Service's selector:
# 1. Deploy green and wait until it is fully ready (no production traffic yet)
kubectl -n shop apply -f order-green.yaml
kubectl -n shop rollout status deployment/order-green --timeout=5m
# 2. Verify green through the preview Service (run inside the cluster)
kubectl -n shop run smoke --rm -i --restart=Never --image=curlimages/curl -- \
curl -fsS http://order-preview:8080/version
# 3. Switch: all new connections go to green
kubectl -n shop patch service order --type merge \
-p '{"spec":{"selector":{"shop.example.com/color":"green"}}}'
# 4. If something goes wrong, switch back to blue
kubectl -n shop patch service order --type merge \
-p '{"spec":{"selector":{"shop.example.com/color":"blue"}}}'Figure: deploy green without traffic; change the Service selector to switch over at once; if trouble appears, change the selector back and blue is serving again within seconds. Both colours share one database.
With GitOps, steps 3 and 4 should not be manual patch commands, or Argo CD's selfHeal will put the selector back to the value in git. Either make the switch a commit (change the Service's color) or hand it to Argo Rollouts in Step 8, which manages the selector for you.
Blue-green looks simple, but a few things must be thought through:
- It costs double. Both environments need full capacity around the switch, or green is crushed the moment traffic lands on it. Scale blue down only after the switch and a period of observation; that observation period is the price you pay for rollback in seconds.
- Warm-up. New pods have empty connection pools and cold local caches, and the HPA has not yet scaled for the load. Give green the same replica count blue has right now, not the HPA minimum; for services with local caches, send some warm-up requests through preview before switching.
- Long-lived connections do not move. Changing the selector affects only new connections. api-gateway's gRPC connections to
orderare long-lived HTTP/2 connections and stay on blue's pods after the switch until they close. So blue cannot be deleted right after switching; on the server side, gRPC'sMaxConnectionAgemakes clients reconnect periodically, so the switch completes within a predictable time. - Background work ignores the Service. This is the easiest one to miss: a Service governs only incoming requests. The moment green's pods start, their NATS consumers, outbox relay and scheduled jobs are already processing real data, without waiting for any switch. Step 10 returns to this.
- The database is shared. Both colours read and write the same database, so green's schema changes must keep blue working; and when you switch back to blue, the data green has written does not disappear.
When not to use blue-green: the cluster cannot run two full environments; the change itself is incompatible, so switching back would not help (the data format has already changed, for example); or the service is stateful (databases, message brokers), whose upgrades follow their own procedures.
Step 4: Canary (grey release) — a small group first
Scenario: api-gateway has rewritten its authentication and routing middleware, which touches every request. It is fine in the test environment, but the mix of production traffic (all sorts of client versions, all sorts of odd headers) cannot be reproduced there. A change that only real traffic can validate is a good fit for a canary: send 5% of requests to the new version, check whether it is any worse than the old one, widen to 25%, 50% and 100% if not, and set the weight back to zero if it is, so only that 5% was affected.
The name comes from the canary miners took into the pit: it reacted to gas before people did. The point is not only that the share is small, but that someone is watching its reaction, and watching it in comparison with the old version.
Figure: each stage sets a weight, pauses to collect samples, then runs an analysis, and only a pass moves it on; any failed analysis sets the weight back to 0.
How to order the percentages. A common sequence is "internal → 1% or 5% → 25% → 50% → 100%". What matters most in the first stage is a small blast radius; later stages give more kinds of traffic a chance to show up. Before the first stage, you can route only internal staff or QA to the new version by header, so real users are not affected at all.
How long each stage lasts. Shorter is not better, and neither is longer. Three things decide it:
- Enough samples. Step 5 does the arithmetic: at 5% during off-peak hours, it can take more than ten minutes to collect a thousand requests.
- Covering the right periods. Some problems appear only at peak (a connection pool that is too small), some only at certain times (an hourly job). The last stage can be longer so it spans a peak.
- Slow problems need time. Memory leaks and connections that are never released often take tens of minutes or more to show.
Split by weight or by user? This is the most overlooked design choice in a canary:
Figure: by weight, one user's consecutive requests may land on different versions; by header or user cohort, each person stays on one version, and staff can go first.
- By weight: every request draws its own lot. It is the easiest to do: set two backend weights at the edge. The downside is that a user flips between v1 and v2: if v2 changed a response format or a page flow, the user sees inconsistent screens.
- By header or cookie: only requests carrying a particular header go to the new version. Good for QA and internal testing; real users are untouched.
- By user cohort: hash the user ID into buckets 0–99; users in buckets below N go to the new version. The same person always lands on the same side, and widening just raises N. This needs a layer that knows who the user is: the cluster edge usually does not (authentication happens in api-gateway's code), so this kind of cohort has to be chosen by api-gateway when it decides which group of
orderto call, or by a service mesh. - By region or tenant: open it to one region or a small set of merchants first. This is usually done with separate clusters or deployment units rather than within one route.
With the Gateway API, a manual canary that gives the header priority and splits the rest by weight looks like this:
# deploy/k8s/base/httproute.yaml: a manual canary
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop
spec:
parentRefs:
- name: public
namespace: gateway-system
hostnames:
- shop.example.com
rules:
# Rule 1: requests with x-shop-canary: always always go to the new version (QA, internal testing)
- matches:
- path:
type: PathPrefix
value: /
headers:
- type: Exact
name: x-shop-canary
value: always
backendRefs:
- name: api-gateway-canary
port: 8080
# Rule 2: everything else is split by weight
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: api-gateway-stable
port: 8080
weight: 95
- name: api-gateway-canary
port: 8080
weight: 5weightis a relative proportion, not a percentage: 95 and 5 behave the same as 19 and 1; it defaults to 1 if omitted.- When two rules have the same path, the Gateway API gives precedence to the rule with more header matches, so a request with
x-shop-canary: alwaysalways takes rule 1. api-gateway-stableandapi-gateway-canaryare two Services, each selecting one group of pods (distinguished by atracklabel, for example).
Note that this HTTPRoute hangs off the public Gateway, so it only governs traffic coming in from outside towards api-gateway. For services inside the cluster that api-gateway calls, such as order and payment, precise shares or user cohorts need a service mesh, or an implementation of the Gateway API's mesh mode (GAMMA, which attaches an HTTPRoute directly to a Service). Without those, a canary for an internal service can only approximate the share through pod counts, and it needs the client-side load balancing from “Service Discovery and Load Balancing for Go Microservices”, or long-lived gRPC connections will distort the share.
When not to use a canary: there is too little traffic, say a few dozen requests an hour at 5%, so no difference can be seen (blue-green with a thorough smoke test is more useful then); or the change makes it impossible for old and new to coexist, for example the two versions interpret the same data differently.
Step 5: Let metrics decide whether to continue or abort
A canary that nobody judges is just a slower rolling update. A person can judge it, but people get tired, hesitate, and think "it's probably fine" at six on a Friday evening. Better to write the judgement as rules and let a controller apply them at every stage:
Figure: set the weight, pause to collect samples, query metrics comparing both versions, apply the rules. Too few samples pauses for a human; a failure aborts and resets the weight to zero.
Which metrics. Start from the RED metrics in “Observability in Go: Logs, Metrics and Tracing” and add business metrics:
| Category | Examples | Why watch it |
|---|---|---|
| Errors | Share of 5xx; gRPC Internal, Unavailable | The most direct sign that something broke |
| Unusual 4xx | A sudden rise in 422 or 400 | When validation is wrong in the new version, errors look like 4xx |
| Latency | p99, p999 | An average hides the few very slow requests |
| Resources | Memory growth, goroutine count, CPU | Leaks and performance regressions |
| Business | Checkout success rate, payment authorisation rate, orders per minute | The code reports no errors but the flow cannot finish (a button sends the wrong request format, say) |
Compare with stable, not with last week. The canary and stable run over the same period and the same traffic, so comparing them rules out outside factors such as "today is a sale day". Fixed thresholds (error rate < 1%) are still needed to catch obvious breakage, but subtle regressions need a comparison.
To compare, the metrics must tell versions apart. There are two ways, and it is best to have both:
- The application reports its version: every metric carries a
versionlabel, and there is a/versionendpoint and anX-App-Versionresponse header. However traffic is split and pods are labelled, queries cansum by (version); when investigating, a quick look at the response header with curl tells you which version served the request. - The platform labels it: Argo Rollouts adds a
rollouts-pod-template-hashlabel to pods, Prometheus's scrape config turns it into a metric label, and the analysis uses it to tell versions apart (Step 8).
On the Go side it looks like this. prometheus.WrapRegistererWith returns a wrapped Registerer, and every metric registered through it automatically gets the fixed labels, so you do not have to add version to every metric's label list:
// Package release lets each service say which version it is, and provides the canary decision.
package release
import (
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promauto"
)
// Version and Commit are injected at build time, for example:
//
// go build -ldflags "-X example.com/shop/internal/release.Version=v1.8.0 \
// -X example.com/shop/internal/release.Commit=$(git rev-parse --short=12 HEAD)"
var (
Version = "dev"
Commit = "unknown"
)
// NewRegistry returns the Registry for /metrics and a Registerer that adds the version label automatically.
// Application metrics register through the latter; Go runtime metrics need no version and go straight on the Registry.
func NewRegistry() (*prometheus.Registry, prometheus.Registerer) {
reg := prometheus.NewRegistry()
reg.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
versioned := prometheus.WrapRegistererWith(prometheus.Labels{"version": Version}, reg)
// build_info is always 1; dashboards use it to show which versions are running and on how many pods.
promauto.With(versioned).NewGauge(prometheus.GaugeOpts{
Name: "shop_build_info",
Help: "Build information; always 1.",
ConstLabels: prometheus.Labels{"commit": Commit},
}).Set(1)
return reg, versioned
}
// HTTPMetrics are the RED metrics: request counts (with status code) and latency.
type HTTPMetrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
}
func NewHTTPMetrics(reg prometheus.Registerer) *HTTPMetrics {
f := promauto.With(reg)
return &HTTPMetrics{
requests: f.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "HTTP requests by route and status code.",
}, []string{"method", "route", "code"}),
duration: f.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency in seconds.",
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5},
}, []string{"method", "route", "code"}),
}
}
type statusRecorder struct {
http.ResponseWriter
code int
}
func (r *statusRecorder) WriteHeader(code int) {
r.code = code
r.ResponseWriter.WriteHeader(code)
}
// Middleware records metrics and puts the version in a response header, so you can see at a glance which version served a request.
func (m *HTTPMetrics) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-App-Version", Version)
rec := &statusRecorder{ResponseWriter: w, code: http.StatusOK}
start := time.Now()
next.ServeHTTP(rec, r)
code := strconv.Itoa(rec.code)
m.requests.WithLabelValues(r.Method, r.Pattern, code).Inc()
m.duration.WithLabelValues(r.Method, r.Pattern, code).Observe(time.Since(start).Seconds())
})
}
// VersionHandler serves GET /version.
func VersionHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"version": Version, "commit": Commit})
}Wiring it up in main:
// fragment: cmd/order/main.go
reg, versioned := release.NewRegistry()
httpMetrics := release.NewHTTPMetrics(versioned)
mux := http.NewServeMux()
mux.HandleFunc("GET /version", release.VersionHandler)
mux.Handle("GET /metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
// ... business routes ...
srv := &http.Server{Addr: ":8080", Handler: httpMetrics.Middleware(mux)}Inject the git SHA at build time (in this series the image tag is already the git SHA, so the two match):
SHA="$(git rev-parse --short=12 HEAD)"
go build -trimpath \
-ldflags "-X example.com/shop/internal/release.Version=$SHA -X example.com/shop/internal/release.Commit=$SHA" \
-o bin/order ./cmd/orderThe value of version changes only once per release, so it does not blow up label cardinality; old versions' time series stop updating once their pods are gone.
How many samples are enough. This is the most neglected part of canaries. Suppose stable's error rate is 0.1%: if the canary handles 1,000 requests, you expect a single error, and seeing 3 may just be bad luck. A rough rule: to see an error rate, you need enough samples to expect about ten errors, that is n ≥ 10 / p. To see a 1% error rate takes about 1,000 requests; to tell 0.1% from 0.3% takes several thousand.
For the shop: at off-peak, api-gateway receives 40 requests a second; 5% of that is 2 a second, so 1,000 requests take over eight minutes. Two conclusions follow:
- The early, small stages can only catch obvious breakage (an error rate far above the threshold, a flow that does not work at all), so they use absolute thresholds.
- Subtle regressions only show at 25% and 50%, when samples are plentiful, and those stages judge by the gap to stable.
Written as code, those rules become the function below. It is not a rigorous statistical test; it spells out three things (draw no conclusion without enough samples, stop waiting when errors are already overwhelming, compare with stable) so the rules can be reviewed and tested:
package release
import (
"fmt"
"time"
)
// Sample holds one version's numbers over a single time window.
type Sample struct {
Requests int64
Errors int64 // 5xx, or requests that failed in business terms
P99 time.Duration
}
func (s Sample) ErrorRate() float64 {
if s.Requests == 0 {
return 0
}
return float64(s.Errors) / float64(s.Requests)
}
// Policy holds the rules: written in config and reviewed, not decided by gut feeling during a release.
type Policy struct {
MinRequests int64 // both versions need at least this many requests before we conclude anything
MaxErrorRate float64 // absolute ceiling for the canary's error rate, e.g. 0.01
MaxErrorRateDiff float64 // how much worse than stable the canary may be, e.g. 0.002 (0.2 points)
MaxP99Ratio float64 // canary p99 may be at most this multiple of stable's, e.g. 1.2
}
type Verdict string
const (
Pass Verdict = "pass" // move to the next stage
Fail Verdict = "fail" // abort and go back to stable
Inconclusive Verdict = "inconclusive" // not enough data: keep waiting or let a human decide
)
// Decide compares the canary with stable: both versions over the same window, not the canary against last week.
func Decide(stable, canary Sample, p Policy) (Verdict, string) {
// Samples are not complete yet, but there are already so many errors that even all-successes from here on
// could not save it: no need to wait.
if canary.Requests < p.MinRequests && float64(canary.Errors) > p.MaxErrorRate*float64(p.MinRequests) {
return Fail, fmt.Sprintf("canary already has %d errors", canary.Errors)
}
if canary.Requests < p.MinRequests || stable.Requests < p.MinRequests {
return Inconclusive, fmt.Sprintf("not enough samples: stable=%d canary=%d, need %d",
stable.Requests, canary.Requests, p.MinRequests)
}
cr, sr := canary.ErrorRate(), stable.ErrorRate()
if cr > p.MaxErrorRate {
return Fail, fmt.Sprintf("canary error rate %.4f above limit %.4f", cr, p.MaxErrorRate)
}
if cr-sr > p.MaxErrorRateDiff {
return Fail, fmt.Sprintf("canary error rate %.4f vs stable %.4f", cr, sr)
}
if stable.P99 > 0 && float64(canary.P99) > float64(stable.P99)*p.MaxP99Ratio {
return Fail, fmt.Sprintf("canary p99 %v vs stable %v", canary.P99, stable.P99)
}
return Pass, "canary within limits"
}// fragment: the table test in release_test.go
func TestDecide(t *testing.T) {
p := Policy{MinRequests: 1000, MaxErrorRate: 0.01, MaxErrorRateDiff: 0.002, MaxP99Ratio: 1.2}
ms := time.Millisecond
stable := Sample{Requests: 20000, Errors: 20, P99: 200 * ms} // 0.1%
tests := []struct {
name string
canary Sample
stable Sample
want Verdict
}{
{"healthy", Sample{Requests: 1200, Errors: 1, P99: 210 * ms}, stable, Pass},
{"too few canary requests", Sample{Requests: 300, Errors: 0, P99: 190 * ms}, stable, Inconclusive},
{"too few stable requests", Sample{Requests: 1200, Errors: 0, P99: 190 * ms}, Sample{Requests: 10, P99: 200 * ms}, Inconclusive},
{"many errors fail fast", Sample{Requests: 40, Errors: 11, P99: 190 * ms}, stable, Fail},
{"above absolute limit", Sample{Requests: 2000, Errors: 30, P99: 190 * ms}, stable, Fail},
{"worse than stable", Sample{Requests: 2000, Errors: 8, P99: 190 * ms}, stable, Fail}, // 0.4% vs 0.1%
{"slower than stable", Sample{Requests: 2000, Errors: 2, P99: 300 * ms}, stable, Fail},
{"stable also bad, canary no worse", Sample{Requests: 2000, Errors: 16, P99: 200 * ms}, Sample{Requests: 20000, Errors: 160, P99: 200 * ms}, Pass},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, why := Decide(tt.stable, tt.canary, p)
if got != tt.want {
t.Fatalf("got %s (%s), want %s", got, why, tt.want)
}
})
}
}Note the first check: the samples are not complete, but the canary already has so many errors that even if every remaining request succeeded the error rate would still be over the limit, so there is no point waiting; abort straight away. That stops a completely broken version within a few dozen requests instead of after a thousand.
Argo Rollouts' AnalysisTemplate does the same thing, with the queries and conditions in YAML, as Step 8 shows. When you need a real statistical comparison, Argo Rollouts can also hand the judgement to a service built for canary statistics, such as Kayenta.
Step 6: Shadow traffic — watch, never answer
Scenario: product search is switching to a new ranking implementation. Old and new should return similar results for the same query, but "similar" can only be checked with real queries, and the new implementation's latency under real load needs to be known first. This is where shadow traffic helps: copy real requests to the new version; users still get the old version's response, and the new version's response is thrown away.
The Gateway API's RequestMirror filter does this:
# Shadow traffic: mirror only read-only product queries; the response comes from stable, shadow's is discarded
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-catalog-shadow
spec:
parentRefs:
- name: public
namespace: gateway-system
hostnames:
- shop.example.com
rules:
- matches:
- method: GET
path:
type: PathPrefix
value: /v1/products
filters:
- type: RequestMirror
requestMirror:
backendRef:
name: api-gateway-shadow
port: 8080
backendRefs:
- name: api-gateway-stable
port: 8080RequestMirror is an extended feature in the Gateway API, so check whether your implementation supports it; newer versions of the specification also offer percent or fraction to mirror only part of the requests. Mirrored responses are discarded, so comparing old and new results has to be done by the new version itself (write results and the version into logs or metrics, for example) and checked offline.
The biggest danger of shadow traffic is duplicated side effects. A mirror copies the whole request, so when the new version receives "create order", it really creates an order:
- It writes to the shared database, and the order appears twice;
- It reserves stock, and stock is taken twice;
- It publishes an
order.placedevent, and everything downstream processes it again; - It calls the payment provider, and the user is charged twice;
- It sends a confirmation email, and the user gets two.
So the rules for shadow traffic are strict:
- Mirror only read-only requests with no side effects, such as
GET /v1/productsabove. The route must name the method and path; never mirror a whole domain. - If a path with writes must be mirrored, the new version must run in isolation: its own copy of the database, all outbound calls faked, no events published. This usually means designing an explicit switch in the code, not relying on "it'll probably be fine".
- Never mirror payment paths. Even if the provider's API supports idempotency keys, do not send production requests into a second system; to validate a new payment integration, use blue-green with a test merchant account.
- Downstream load goes up: the mirrored path reads the database twice, so include that in capacity planning.
Step 7: Feature flags — separating going live from opening up
Deployment strategies control which pods and which requests run the new code; feature flags control, within one version of the code, who a feature is switched on for. The two are often compared, but they complement each other:
| Aspect | Deployment strategy (blue-green, canary) | Feature flag |
|---|---|---|
| Unit of control | Pods, requests | Users, merchants, features |
| Rollback | Shift traffic or redeploy | Change one value, effective immediately |
| Catches | Code-level risk: memory, dependencies, performance | Product-level risk: new flows, new rules, pricing |
| Cost | Infrastructure and release time | Branches in code, combination testing, flags to clean up afterwards |
| Typical use | Every version update | Opening new features gradually, kill switches, A/B experiments |
Scenario: the shop is launching instalment payments. The code goes out as a canary with the flag off: the new code runs, but nobody can reach the instalment flow, so the canary only checks that the new version did not break existing features. Once it is fully rolled out, the flag is switched on for internal staff, then for 1% of users, then for everyone. If the instalment flow has a problem, switch the flag off; no need to roll back the whole version.
Things to watch with feature flags:
- Flags must be compatible across versions too. The old version does not know the new flag, so during a canary do not rely on "turning the flag on" to make old and new behave the same.
- The same user should get the same result, as with cohort-based canaries: decide by hashing the user ID, not randomly per request.
- Flags need an expiry. Once a feature is fully on, delete the flag and the old branch, or the code fills up with conditions nobody dares touch.
- The flag service can be an off-the-shelf product or something stored in your own database; the CNCF's OpenFeature provides a vendor-neutral standard interface, so changing implementations later does not change your code.
Step 8: Implementing it on Kubernetes with Argo Rollouts
Switching by hand with Services and HTTPRoutes makes the ideas clear, but every step needs someone to act, and someone to watch the analysis. Argo Rollouts is a Kubernetes controller that provides a Rollout resource in place of a Deployment and automates "set the weight, pause, analyse, abort or continue". “Automating Deployments and Troubleshooting with AI Workflows” already used it for a basic canary; here we add traffic routing, analysis that compares with stable, the blue-green strategy, and integration with Argo CD.
The field names and behaviour below were checked against the source of Argo Rollouts v1.10.2 (the type definitions in
pkg/apis/rollouts/v1alpha1and the controller), the Gateway API plugin v1.0.0, Gateway API v1.7.0 and Argo CD v3.6.2; all the YAML was strictly decoded into those versions' Go types. For other versions, follow the official documentation.
Argo Rollouts needs its controller installed (pin a version and follow the official docs) and the kubectl argo rollouts plugin. To split traffic with the Gateway API, the controller must also load the traffic router plugin:
# Make the Argo Rollouts controller load the Gateway API plugin (the name and namespace are fixed)
apiVersion: v1
kind: ConfigMap
metadata:
name: argo-rollouts-config
namespace: argo-rollouts
data:
trafficRouterPlugins: |-
- name: "argoproj-labs/gatewayAPI"
location: "https://github.com/argoproj-labs/rollouts-plugin-trafficrouter-gatewayapi/releases/download/<version>/gateway-api-plugin-linux-amd64"Replace location with the download URL of a pinned version from the plugin's releases page; restart the Argo Rollouts controller afterwards so it loads the plugin. The controller also needs RBAC permission to modify HTTPRoutes; the plugin's documentation has an example.
Canary: api-gateway. Hand the manual canary from Step 4 to Argo Rollouts:
# deploy/k8s/base/api-gateway/rollout.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: api-gateway
spec:
# No replicas: the HPA's scaleTargetRef now points at this Rollout
revisionHistoryLimit: 5
# Going back to one of the last 3 revisions skips all steps and goes straight to full (see Step 9)
rollbackWindow:
revisions: 3
selector:
matchLabels:
app.kubernetes.io/name: api-gateway
# Reuse the existing Deployment's pod template; scale the Deployment towards 0 as Rollout pods come up
workloadRef:
apiVersion: apps/v1
kind: Deployment
name: api-gateway
scaleDown: progressively
strategy:
canary:
stableService: api-gateway-stable
canaryService: api-gateway-canary
canaryMetadata:
labels:
shop.example.com/track: canary
stableMetadata:
labels:
shop.example.com/track: stable
trafficRouting:
plugins:
argoproj-labs/gatewayAPI:
httpRoute: shop
namespace: shop
steps:
- setWeight: 5
- pause:
duration: 15m
- analysis:
templates:
- templateName: http-canary-vs-stable
args:
- name: service
value: api-gateway
- name: canary-hash
valueFrom:
podTemplateHashValue: Latest
- name: stable-hash
valueFrom:
podTemplateHashValue: Stable
- setWeight: 25
- pause:
duration: 15m
- analysis:
templates:
- templateName: http-canary-vs-stable
args:
- name: service
value: api-gateway
- name: canary-hash
valueFrom:
podTemplateHashValue: Latest
- name: stable-hash
valueFrom:
podTemplateHashValue: Stable
- setWeight: 50
- pause:
duration: 30m
- analysis:
templates:
- templateName: http-canary-vs-stable
args:
- name: service
value: api-gateway
- name: canary-hash
valueFrom:
podTemplateHashValue: Latest
- name: stable-hash
valueFrom:
podTemplateHashValue: Stable
---
apiVersion: v1
kind: Service
metadata:
name: api-gateway-stable
spec:
selector:
app.kubernetes.io/name: api-gateway # Argo Rollouts adds rollouts-pod-template-hash
ports:
- name: http
port: 8080
targetPort: http
---
apiVersion: v1
kind: Service
metadata:
name: api-gateway-canary
spec:
selector:
app.kubernetes.io/name: api-gateway
ports:
- name: http
port: 8080
targetPort: http
---
# The route that pointed at api-gateway now has two backends; Argo Rollouts rewrites the weights
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop
spec:
parentRefs:
- name: public
namespace: gateway-system
hostnames:
- shop.example.com
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: api-gateway-stable
port: 8080
weight: 100
- name: api-gateway-canary
port: 8080
weight: 0Item by item:
workloadReflets the Rollout use an existing Deployment's pod template directly instead of copying the whole template over; it is the least effort way to migrate from a Deployment.scaleDown: progressivelymeans the original Deployment is scaled down by as much as the Rollout's pods scale up, until it reaches 0 (the other two values areneverandonsuccess). Later releases still change the Deployment's pod template, so the CI flow that changes the image tag with kustomize stays the same. When migrating, let the Rollout run alongside the Deployment first and then scale the Deployment down; do not delete it outright, or there will be a period with no pods serving.- Replicas are left to the HPA, but the HPA's target must change to the Rollout, or the HPA will scale the Deployment that was scaled to 0 back up:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: payment
spec:
scaleTargetRef:
apiVersion: argoproj.io/v1alpha1
kind: Rollout # previously apps/v1 Deployment
name: payment
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70stableServiceandcanaryService: the controller addsrollouts-pod-template-hashto both Services' selectors so that each selects only stable or only canary pods. The selectors in git only containapp.kubernetes.io/name.canaryMetadataandstableMetadata: labels added to pods while they act as canary or stable, so dashboards can usetrackdirectly.trafficRouting.plugins: the Gateway API plugin changes the weights on the HTTPRouteshop. The HTTPRoute must list both backends, with initial weights of 100 and 0. Without traffic routing,setWeightcan only approximate with pod counts.steps:setWeight,pause(durationaccepts15m;pause: {}pauses indefinitely until someone runs promote) andanalysis. Every analysis passes two hashes,podTemplateHashValue: Latest(canary) andStable, so the queries can compare them.rollbackWindow: explained in Step 9.- By default, stable keeps full capacity during the canary (
dynamicStableScaleis off by default), so on abort, when the weight goes back, stable can take the load immediately. The price is the extra canary pods during the release.
If QA should try the canary first via a header, Rollout steps also offer setHeaderRoute (with the route names declared in trafficRouting.managedRoutes), and the Gateway API plugin then needs the httpRoutes list with useHeaderRoutes: true. Support varies between plugins, so check before relying on it.
Analysis: comparing with stable. This AnalysisTemplate consists of three metrics:
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: http-canary-vs-stable
spec:
args:
- name: service
- name: canary-hash
- name: stable-hash
metrics:
# 1. Sample size: too few means Inconclusive and the Rollout pauses for a human, rather than pass or fail
- name: canary-requests
successCondition: len(result) > 0 && result[0] >= 1000
failureCondition: 'false'
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
sum(increase(http_requests_total{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.canary-hash}}"}[10m]))
# 2. Error rate: canary minus stable, over the same window
- name: error-rate-diff
successCondition: len(result) > 0 && result[0] <= 0.002
failureCondition: len(result) > 0 && result[0] > 0.002
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
(
(sum(rate(http_requests_total{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.canary-hash}}", code=~"5.."}[10m])) or vector(0))
/
sum(rate(http_requests_total{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.canary-hash}}"}[10m]))
)
-
(
(sum(rate(http_requests_total{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.stable-hash}}", code=~"5.."}[10m])) or vector(0))
/
sum(rate(http_requests_total{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.stable-hash}}"}[10m]))
)
# 3. Latency: canary p99 divided by stable p99
- name: p99-ratio
successCondition: len(result) > 0 && result[0] <= 1.2
failureCondition: len(result) > 0 && result[0] > 1.2
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.canary-hash}}"}[10m])))
/
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{namespace="shop", service="{{args.service}}", rollouts_pod_template_hash="{{args.stable-hash}}"}[10m])))- Every metric sets both
successConditionandfailureCondition. Under Argo Rollouts' evaluation logic, when neither condition holds the measurement is Inconclusive, and when an analysis ends Inconclusive the Rollout pauses for a human. With onlysuccessCondition, anything that does not satisfy it counts as a failure. canary-requestsdeliberately has'false'as its failure condition: too few samples is not a failure but "too early to tell", and a person decides whether to extend or continue.or vector(0)handles a classic PromQL trap: when the canary has no 5xx at all, thecode=~"5.."query returns an empty set, the whole division becomes empty, and the analysis never gets a result. Addingvector(0)turns "no errors" into 0.len(result) > 0 &&handles the empty result returned when there is no traffic at all, sending it to Inconclusive instead of an error while evaluating the condition.- There is no
intervalorcount, so each metric is measured once in that step; the[10m]window matches the precedingpause. To watch continuously throughout the release, put the analysis instrategy.canary.analysis(background analysis) and usestartingStepto choose the step it starts from.
The namespace, service and rollouts_pod_template_hash labels used in the queries have to be copied from pod metadata by Prometheus's scrape config:
# fragment: prometheus.yml scrape config, only the part that turns pod labels into metric labels
scrape_configs:
- job_name: shop-pods
kubernetes_sd_configs:
- role: pod
namespaces:
names: [shop]
relabel_configs:
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]
target_label: service
- source_labels: [__meta_kubernetes_pod_label_rollouts_pod_template_hash]
target_label: rollouts_pod_template_hash
- source_labels: [__meta_kubernetes_pod_label_shop_example_com_track]
target_label: trackBlue-green: payment. Hand Step 3's blue-green to Argo Rollouts, which then manages both Services' selectors:
# deploy/k8s/base/payment/rollout.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: payment
spec:
revisionHistoryLimit: 5
selector:
matchLabels:
app.kubernetes.io/name: payment
workloadRef:
apiVersion: apps/v1
kind: Deployment
name: payment
scaleDown: progressively
strategy:
blueGreen:
activeService: payment # other services already use this name, so no config changes
previewService: payment-preview # the new version sits here first; only tests connect
autoPromotionEnabled: false # even after analysis passes, a human runs promote to switch
prePromotionAnalysis:
templates:
- templateName: payment-smoke
args:
- name: target
value: payment-preview.shop.svc.cluster.local:8080
scaleDownDelaySeconds: 600 # keep the old version 10 minutes after switching; rollback is just a selector switch
---
apiVersion: v1
kind: Service
metadata:
name: payment-preview
spec:
selector:
app.kubernetes.io/name: payment
ports:
- name: http
port: 8080
targetPort: http
- name: grpc
port: 9090
targetPort: grpc
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: payment-smoke
spec:
args:
- name: target
metrics:
- name: smoke
provider:
job:
spec:
backoffLimit: 0
activeDeadlineSeconds: 300
template:
spec:
restartPolicy: Never
containers:
- name: smoke
# assumes the image has a smoke subcommand: authorise and void once with a test merchant account
image: registry.example.com/shop/payment:REPLACED_BY_KUSTOMIZE
args: ['smoke', '--target', '{{args.target}}']activeServiceis the Service that production traffic uses; it keeps the original namepayment, so no other service's configuration changes.previewServicepoints at the new version, and only tests connect to it.autoPromotionEnabled: false: once the new version is ready andprePromotionAnalysishas passed, the Rollout stops and waits for someone to promote it. The default istrue, which switches automatically after the analysis passes; for a service like payment, having a person make the final call is the safer choice.prePromotionAnalysisruns before the switch; here a Job-type metric runs a smoke test, and the Job succeeding counts as a pass. Its counterpartpostPromotionAnalysisruns after the switch, and on failure switches back to the old version.scaleDownDelaySeconds: how long the old version is kept after the switch (30 seconds by default). Within that time, rolling back is just switching the selector back; for rollback in seconds, set it to the observation time you need and pay for double resources during it.
Day-to-day operation uses the kubectl plugin:
# See the current step, each version's pods and the analysis results
kubectl argo rollouts get rollout api-gateway -n shop --watch
# Move a paused Rollout to the next step; --full skips all remaining steps and analyses
kubectl argo rollouts promote api-gateway -n shop
kubectl argo rollouts promote api-gateway -n shop --full
# Abort: weight back to 0, all traffic back to stable
kubectl argo rollouts abort api-gateway -n shop
# After an abort (config fixed, or it was a false alarm), start this release again
kubectl argo rollouts retry rollout api-gateway -n shopStep 9: Using it with Argo CD
The division of labour is clear: Argo CD applies the state in git to the cluster; Argo Rollouts decides how a new pod template takes over traffic step by step. The flow from the previous article does not change: CI only changes the image tag, Argo CD syncs the Rollout, and Argo Rollouts sees that the pod template changed and starts the steps.
git holds the Rollout, the AnalysisTemplate, both Services and the HTTPRoute; the analysis thresholds therefore go through PR review and have a history, just like code.
Health status. Argo CD has a built-in health check for Rollouts: Progressing while steps run; Suspended while paused (pause: {}, waiting for promote, or an Inconclusive analysis); Degraded after an abort or once progressDeadlineSeconds is exceeded. Argo CD's UI also offers Rollout actions: resume, promote-full, abort, retry, skip-current-step, pause and restart, so on-call staff do not necessarily need the kubectl plugin.
Weights being reset. During a release, Argo Rollouts changes the HTTPRoute's weights; Argo CD sees the HTTPRoute differ from git and, with selfHeal on, sets the weights back to 100 and 0, and the two controllers fight. Tell the Application to ignore that field:
# The parts of the shop-prod Application that matter for Rollouts
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: shop-prod
namespace: argocd
spec:
ignoreDifferences:
# Argo Rollouts rewrites the weights during a release; stop selfHeal from resetting them to git's values
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: shop
jqPathExpressions:
- .spec.rules[].backendRefs[].weight
syncPolicy:
syncOptions:
- RespectIgnoreDifferences=trueRespectIgnoreDifferences=true applies the ignore rules during sync as well; otherwise every sync still writes git's weights back.
After an abort, git must change too. abort only moves traffic back to stable; the Rollout's spec (the new image tag in git) is unchanged, and Argo CD keeps showing Degraded. The proper finish is to revert the tag-changing commit in the config repository: once the pod template matches stable again, Argo Rollouts treats it as "back to stable" and completes immediately, skipping all steps, without another round of canary.
What if the problem appears after full promotion? By then stable is the faulty new version, and to Argo Rollouts the reverted old version is "a new change", which by default goes through every step again, so the rollback takes over an hour. rollbackWindow.revisions: 3 makes going back to one of the last 3 revisions skip all steps and analyses and go straight to full (if the old version's pods were already scaled down they still have to start, but there is no stage-by-stage wait), which is what that field in Step 8 is for.
Migrations still come first. The previous article used a Sync hook with sync waves so the migration Job runs before the services update. That order stays with Rollouts, but its meaning matters more: when the migration finishes, the old version keeps serving for a long time (the whole canary), so a migration may only ever "expand", as the next step explains.
Step 10: What to watch while old and new run side by side
This is the most important step in the article. Blue-green, canary and even rolling updates all have a period in which v1 and v2 run together, sharing one database, one event stream and one cache. A release strategy controls traffic; it cannot control any of these shared things.
Database migrations: expand and contract. There is one rule: never make a breaking schema change while both versions might be running. Renaming, dropping a column, changing a type and adding a NOT NULL column the old version does not fill are all breaking. To change something, split it across several releases:
Figure: replacing orders.total with total_minor in five steps; each step is compatible with the previous version and can be rolled back. Only the final column drop cannot be undone, so it comes last, once the previous version is certainly no longer needed.
Take replacing orders.total with total_minor (an int64 in minor currency units):
- Expand: a migration adds
total_minor, nullable. The old code does not know it exists and is unaffected. - Dual write: v2 writes both columns and still reads
total. While v1 and v2 coexist, both readtotal, so they agree. - Backfill, read the new column: a batch job fills
total_minorfor old rows (small batches, interruptible, like the approach to large tables in “Adding Indexes Safely: Indexing Large Tables Without an Outage”); then v3 readstotal_minorbut still writes both, because v2 still readstotalduring the release. - Write only the new column: v4 stops writing
total. Only v3 and v4 are live now, and both readtotal_minor. - Contract: once there is no chance of going back to v3, drop
total, and maketotal_minorNOT NULL if needed.
Each step can be undone by exactly one version, and the previous version always works on the schema of the moment. That is why the earlier article said database migrations are usually not rolled back: rather than writing down-migrations, keep the schema compatible with the previous version at all times.
API and event compatibility: both directions.
Figure: order v1 and v2 publish events in different formats to the same stream; inventory v1 and v2 share one durable consumer, and each message goes to only one pod.
- Backward compatibility: the new version must handle requests and events produced by the old version.
- Forward compatibility: the old version must handle events and data produced by the new one, because during the canary and after a rollback, v1 reads what v2 wrote. In practice: ignore fields you do not recognise. Do not decode JSON with
DisallowUnknownFields; Protobuf already preserves unknown fields, but never change a field's number or type (“gRPC and Protocol Buffers in Go”). - Enum values are a trap: v2 adds an order status
partially_refunded; what does v1 do when it reads one? Either release a v1 that recognises the new status but does not yet produce it, or only start using the new status once v2 is fully rolled out and will not be rolled back (a feature flag can control this).
A canary's consumers process real messages. The services in this series consume events through NATS JetStream durable consumers: every pod with the same durable name shares the messages, and each message goes to only one of them. A canary pod is one of them, so from the moment it starts it is processing real stock deductions, and the share it gets depends on how fast it pulls messages, not on the 5% you set. Three consequences:
- HTTP weights do not control it; a 5% canary may process 30% of the messages.
- When the canary is aborted, messages it has already handled are not redone; wrong results are already in the database.
- Kafka consumer groups work the same way: a canary pod that joins the group is assigned partitions.
The safer approach is to split consumers into their own deployment: the same image, with subcommands separating serve (handling requests) from worker (consuming events, running scheduled jobs). Release the request path as a canary; release the worker after the request path is fully rolled out, with a rolling update or a small-replica canary of its own, watching its own metrics (processing failure rate, dead letters, processing delay, also with the version label). With blue-green, take even more care: green's worker starts consuming as soon as it starts, without waiting for the selector switch.
Scheduled jobs run twice. A Kubernetes CronJob is a separate resource and does not run twice because of blue-green. But scheduled work written into the service (releasing expired stock reservations every minute, reconciling every hour) runs in every pod: once per environment during blue-green, once per version during a canary. Either move it to a CronJob, or use the locks in “Idempotency and Distributed Locks” or a database advisory lock so only one runner executes it, and make the job itself idempotent. An outbox relay implemented with SKIP LOCKED as in “Distributed Transactions: Sagas and the Outbox Pattern” can already run as several instances.
Caches and sessions. When splitting by weight, one user's consecutive requests jump between old and new:
- If v2 changes the format of cached data but keeps the same cache key, v1 fails to decode what v2 wrote. Put a data format version (not the code version) in cache keys, such as
product:v3:{id}, and change the prefix whenever the format changes. - The same goes for server-side session data. Stateless tokens are less affected, but the fields inside a token must also be forward compatible.
- Front-end assets: if a page rendered by v2 references static files and the request for them lands on v1, it returns 404. Name static files by content hash and keep both versions' files available.
- When a person must stay on one version, use the user cohorts from Step 4 rather than the load balancer's sticky sessions, which also move when pods scale.
Observability must be split by version. Logs, metrics and traces all need the version: metrics through the version label from Step 5, logs through a fixed field on the logger, traces through the service.version resource attribute. The first question in an incident is often "which version handled the failing requests?", and without version information you can only guess.
Payment flows. Payments are where running two versions is riskiest:
- The way idempotency keys are generated must not change between versions. A user presses pay on v1, the retry lands on v2, and if v2 builds the idempotency key differently, the provider treats it as a new payment and the user is charged twice. Idempotency design is covered in “Idempotency and Distributed Locks”.
- Provider callbacks can land on either version. A payment created by v2 may have its callback handled by v1 (especially after a rollback), so v1 must recognise every state and field v2 writes.
- An in-flight payment must be finishable by the other version. Do not let the new version introduce intermediate states that only it knows how to complete, or a rollback leaves stuck payments behind.
- Payment analysis metrics should include the authorisation success rate and callback processing failures, and reconciliation should run after the release; “Payment Pitfalls: Double Charges, Callbacks and Reconciliation” covers this fully.
Step 11: Rollback, cost and a pre-release checklist
You roll back code, not data. Setting the weight to zero or switching the selector back only means later requests are handled by the old version. Everything that happened during the canary is still there:
- Data written to the database (possibly wrong);
- Events published and already processed downstream;
- Notifications sent, external APIs called, payments taken.
So for every high-risk release, decide in advance how wrong data will be found and fixed: record the handling version in an audit column or in logs, so affected orders can be filtered by version; the fix is usually a compensating action or a data repair script (the compensation idea from “Distributed Transactions: Sagas and the Outbox Pattern”), not an expectation that rollback will undo them. Often a better choice than rolling back is to fix forward: ship a corrected version quickly, especially once data has already been written in the new format.
Cost. Every strategy spends money to buy safety:
- Blue-green: double capacity during observation;
- Canary: the extra canary pods, and longer releases (over an hour each, so only a few releases a day);
- Shadow: double compute and database reads on the mirrored path;
- People: writing analysis rules, maintaining metrics and dashboards.
Grading by risk is a sensible approach: low-risk services such as inventory use rolling updates; api-gateway and order use canaries with steps tuned to their traffic; payment uses blue-green with a smoke test and a human confirmation. One service's settings can also vary with the size of the change; for example, a release that only changes copy can use shorter steps.
Pre-release checklist:
- The change is compatible while old and new run together: the database only expands, events and APIs only add, enum values are handled.
- After rolling back to the previous version, it correctly reads data and events written by this version.
- Metrics, logs and traces all carry the version; dashboards show canary and stable side by side.
- Analysis rules are in git: error rate, latency, business metrics, minimum sample size, with thresholds that have a reason.
- Each stage's duration has been worked out: at current traffic it collects enough samples.
- The behaviour of consumers, scheduled jobs and the outbox relay in the canary or green environment has been thought through: will anything run twice, will it process real messages?
- Cache keys, sessions and static files are compatible between the two versions.
- For payments: idempotency keys unchanged, callbacks handled by both versions, no state only the new version can finish.
- Abort and rollback steps are in the runbook, with the right commands (a Rollout is not a Deployment), including the git revert afterwards.
- How to find and fix affected data has been worked out in advance.
- The release avoids times when nobody is available to handle problems.
Common pitfalls
Believing blue-green or canary makes incompatible changes safe. Old and new will coexist and share the database and messages; the strategy only controls traffic, and compatibility is your job.
Dropping or renaming a column while both versions may run. The old version starts failing immediately, and rollback does not help because the column is gone.
Watching only the canary's own error rate without comparing with stable. On a sale day the overall error rate rises and the canary is wrongly failed; or the normal error rate is 0.5% and a canary at 0.9% is waved through.
Concluding with too few samples. Five minutes at 5% is a few hundred requests, and zero errors proves nothing; set a minimum sample size in the analysis and let it go Inconclusive when it is not met.
PromQL returns an empty set when there are no errors. Without or vector(0) in the error rate query, a healthy canary never gets an analysis result.
Assuming HTTP weights also control consumers. JetStream or Kafka consumers in canary pods share real messages anyway, at a rate set by how fast they pull.
Green's background work starts the moment it does. Before the selector switches, green's workers and scheduled jobs are already processing production data.
Mirroring requests with side effects. The shadow environment created orders, took stock and called the payment provider; mirror only read-only requests, and never mirror payments.
Switching the selector with a manual kubectl patch, and Argo CD putting it back. Put the switch in git, or let Argo Rollouts manage it.
Argo CD resetting the weights Argo Rollouts set. Configure ignoreDifferences for the HTTPRoute weights and enable RespectIgnoreDifferences=true.
Forgetting to revert git after an abort. The Rollout stays Degraded, and when someone next changes other settings, the broken version starts rolling out again.
Finding the problem after full promotion, and the revert taking another hour. Set rollbackWindow so going back to recent revisions skips the steps.
The HPA still pointing at the Deployment. After switching to workloadRef, the HPA scales the Deployment that was scaled to 0 back up; change scaleTargetRef to the Rollout.
Rolling back a Rollout with kubectl rollout undo. That is a Deployment command; a Rollout uses kubectl argo rollouts abort or undo.
The new version changing how idempotency keys are generated. A retry lands on the other version, the provider sees a new transaction, and the user is charged twice.
Key takeaways
- Deploying gets new code running; releasing lets users meet it. Every strategy pulls the two apart to control how many people meet the new version, and when.
- Rolling updates suit most compatible, low-risk changes, but cannot control the share, ignore metrics, and do not roll back instantly.
- Blue-green: two full environments, one switch, rollback in seconds; the price is double capacity, plus care with warm-up, long-lived connections, background work and the shared database.
- Canary (grey release): a small share first, widened step by step; percentages and stage durations follow from sample sizes and peak periods; weights are simplest, and pinning a person to one version needs user cohorts chosen by the layer that knows the user.
- Leave the judgement to rules in git: compare with stable over the same period, set a minimum sample size, abort at once when errors are overwhelming; small stages catch obvious breakage, large stages catch subtle regressions.
- Services should report their own version: a
versionlabel on metrics, a/versionendpoint and a response header. - Shadow traffic watches and never answers, and only suits read-only paths; mirroring a request with side effects means executing it twice, and payments are never mirrored.
- Feature flags control who a feature is on for, and complement deployment strategies: deploy as a canary with the flag off, then open it up with the flag.
- Argo Rollouts automates canary and blue-green with Rollouts, AnalysisTemplates and traffic router plugins; with Argo CD, ignore the weight differences, revert git after an abort and set
rollbackWindow. - Old and new running together is normal: expand and contract the database, keep events and APIs compatible both ways, split consumers into their own deployment, make scheduled jobs exclusive or idempotent, put a format version in cache keys, and keep payment idempotency keys and states consistent across versions.
- You roll back code, not data; decide in advance how affected data will be found and fixed, and often fixing forward beats rolling back.
References
- BlueGreenDeployment (Martin Fowler): two environments, switching the router and fast rollback, the original description behind step 3.
- CanaryRelease (Martin Fowler): rolling out to a small subset of users first, the original description behind step 4.
- Deployments (official Kubernetes documentation): the rolling update fields
maxSurge,maxUnavailable,minReadySecondsandprogressDeadlineSecondsin step 2. - HTTP traffic splitting (official Gateway API documentation): shifting traffic with HTTPRoute weights, used for the manual canary in step 4.
- HTTP request mirroring (official Gateway API documentation):
RequestMirrorresponses being ignored, the basis of shadow traffic in step 6. - Canary (official Argo Rollouts documentation):
setWeight,pauseanddynamicStableScale, used for the canary in step 8. - BlueGreen (official Argo Rollouts documentation):
autoPromotionEnabled,prePromotionAnalysisand the 30-second defaultscaleDownDelaySeconds, used in step 8. - Analysis & Progressive Delivery (official Argo Rollouts documentation):
successCondition,failureConditionand Inconclusive runs, behind the AnalysisTemplate in step 8.
Next
The shop can now deploy declaratively on Kubernetes, release step by step and abort automatically when something goes wrong. All of this assumes there is somewhere to run it, with enough capacity. The next three articles put the system in the cloud. The next one, “Deploying on AWS: Running Container Services on ECS Fargate”, starts with the option that needs neither servers nor Kubernetes to manage: running containers on AWS with ECS Fargate, wired to the network, load balancing, secrets and automatic deployment.