StackPractices
advanced By Mathias Paulenko

Canary Deployments with Istio Service Mesh

How to use Istio traffic splitting to perform safe canary deployments by gradually shifting user traffic between application versions

Overview

A canary deployment sends a small slice of real traffic to a new version while the old version keeps serving everyone else. If the canary looks healthy — error rate, latency, business metrics — you widen the slice until it owns all the traffic; if it misbehaves, you snap the weight back to zero and nobody else notices.

The name borrows from coal mining: miners carried caged canaries underground because the birds collapsed at dangerous gas levels before the humans felt anything. Same deal here — a tiny, cheap slice of traffic hits the risky version first, and its death warns you before the blast reaches everyone.

Plain Kubernetes can’t do this: a second Deployment splits traffic by replica count, which is nowhere near precise enough for “5% for ten minutes.” That’s the gap Istio fills. Two resources do the work — DestinationRule names the version subsets, VirtualService weights them down to the exact percentage — and the same machinery routes specific users by header or mirrors production traffic to a hidden version, all without touching pod counts.

StrategyTraffic controlRollback speedInfra costBest for
Rolling updateReplica-pacedSlow (re-roll)None extraRoutine releases
Blue-greenAll-or-nothing switchInstant2× capacityBig-bang cutovers
Canary (Istio)Exact % weightsInstant (weight → 0)Small canary poolRisky changes, real-user validation
Flagger canarySame + auto-analysisAutomatic+FlaggerHands-off progressive delivery

If you’re already running Istio, weighted routing is free — it’s configuration, not a new system. If you aren’t, Argo Rollouts or plain Ingress-weight annotations get you most of the way without a mesh.

When to Use This

  • You deploy to Kubernetes and need progressive traffic shifting — see Blue-Green Deployment for the all-or-nothing alternative
  • A release carries real risk (schema changes, new dependencies, pricing logic) and needs validation with live users before full rollout
  • You want to shrink the blast radius of a bad deploy to single-digit percentages of traffic
  • You already run Istio, or the feature set justifies installing it

Skip it when the service is internal-only with tolerant consumers, when the change is trivially revertible anyway, or when you lack the metrics to tell “healthy” from “broken” — a canary you can’t measure is just a slower rollout.

Prerequisites

  • A Kubernetes cluster running Istio — sidecar injection needs to be on for the namespace
  • Two versions of your app already deployed, tagged with distinct labels
  • kubectl access to the cluster

Solution

1. Deploy Both Versions

The stable version runs at production scale; the canary starts small — it only needs enough capacity to serve its traffic percentage.

# deployment-v1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-v1
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
      version: v1
  template:
    metadata:
      labels:
        app: api
        version: v1
    spec:
      containers:
      - name: api
        image: myapp:1.0.0
        ports:
        - containerPort: 8080
# deployment-v2.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-v2
spec:
  replicas: 1
  selector:
    matchLabels:
      app: api
      version: v2
  template:
    metadata:
      labels:
        app: api
        version: v2
    spec:
      containers:
      - name: api
        image: myapp:1.1.0
        ports:
        - containerPort: 8080

2. Create a Destination Rule for Subsets

The DestinationRule maps pod labels to named subsets (v1, v2) that the VirtualService can target. The traffic policy here also adds outlier detection — a pod that returns 5 consecutive 5xx errors gets ejected from the load-balancing pool for 30s, which protects the canary itself from a single bad pod skewing your metrics.

# destination-rule.yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: api
spec:
  host: api
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 30s
      baseEjectionTime: 30s
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2

3. Configure Traffic Splitting

The canary lives in the VirtualService: weight: 90 / weight: 10 sends one request in ten to v2. Across all destinations of a host, the weights have to add up to 100.

# virtual-service-canary.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api
spec:
  hosts:
  - api
  http:
  - route:
    - destination:
        host: api
        subset: v1
      weight: 90
    - destination:
        host: api
        subset: v2
      weight: 10

4. Progressive Rollout Script

The manual loop: set a weight, wait, look at metrics, decide. set_weight takes the v1 share, so 90 means “10% to canary” and 0 means “fully promoted.”

#!/bin/bash
# canary-rollout.sh

set -e

function set_weight() {
  local v1_weight=$1
  local v2_weight=$((100 - v1_weight))

  cat <<EOF | kubectl apply -f -
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api
spec:
  hosts:
  - api
  http:
  - route:
    - destination:
        host: api
        subset: v1
      weight: ${v1_weight}
    - destination:
        host: api
        subset: v2
      weight: ${v2_weight}
EOF
}

# Phase 1: 10% traffic to v2
set_weight 90
echo "Deployed v2 at 10%. Monitoring for 5 minutes..."
sleep 300

# Phase 2: 50% traffic to v2
set_weight 50
echo "Deployed v2 at 50%. Monitoring for 5 minutes..."
sleep 300

# Phase 3: 100% traffic to v2
set_weight 0
echo "Deployed v2 at 100%. Canary complete."

In production you don’t sleep — you check dashboards between phases. The script encodes the cadence; the judgment stays human unless you automate step 5.

5. Automated Analysis via Flagger

Flagger turns the manual loop into a controller. It bumps stepWeight (10%) every interval (1m), evaluates the metrics against your thresholds, and either promotes the canary to 100% or rolls it back after threshold consecutive failures — with a load-test webhook generating traffic so the metrics aren’t sparse.

# canary-analysis.yaml
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: api
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  service:
    port: 8080
  analysis:
    interval: 1m
    threshold: 5
    maxWeight: 50
    stepWeight: 10
    metrics:
    - name: request-success-rate
      thresholdRange:
        min: 99
      interval: 1m
    - name: request-duration
      thresholdRange:
        max: 500
      interval: 1m
    webhooks:
    - name: load-test
      url: http://flagger-loadtester.test/
      timeout: 5s
      metadata:
        cmd: "hey -z 1m -q 10 -c 2 http://api:8080/health"

How Traffic Flows

graph diagram: Client

Every request hits the sidecar proxy first, which consults the VirtualService routing table — updated live by kubectl apply, no pod restarts. That’s why rollback is instant: you’re editing a routing rule, not redeploying anything.

How It Works

  1. DestinationRule maps pod labels to named subsets — the version: v1/v2 labels on the Deployments are the only thing linking pods to routing.
  2. VirtualService distributes requests by weight across those subsets; weights are percentages and must sum to 100.
  3. Progressive shifting is just repeated apply with bigger v2 weights — 10% → 50% → 100% is the classic cadence, but 1% → 5% → 25% → 100% is safer for high-traffic services.
  4. Outlier detection (in the DestinationRule) ejects pods that error out consecutively, independent of the canary — it protects both versions.
  5. Rollback is set_weight 100 (or Flagger doing it for you): traffic snaps back to v1 in seconds because v1 never went anywhere.

Variants

Header-Based Canary Routing

Percentage splitting is anonymous — you can’t choose who sees the canary. Header matching fixes that: internal testers (or a “canary cohort” of opted-in users) get v2 regardless of weight while everyone else stays on v1.

# Route internal testers to v2 regardless of weight
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api-header-routing
spec:
  hosts:
  - api
  http:
  - match:
    - headers:
        x-canary-test:
          exact: "true"
    route:
    - destination:
        host: api
        subset: v2
  - route:
    - destination:
        host: api
        subset: v1
      weight: 100

The match rule is evaluated first — header present → v2; otherwise → v1 at 100%. You can match on cookies and JWT claims the same way, which is how “employees see it first” programs work.

Traffic Mirroring (Shadow Traffic)

Mirroring sends a copy of every request to v2 in addition to v1, but discards v2’s responses. Users never see canary output — you get real production traffic patterns against the new version with zero user-visible risk.

# Mirror 100% of traffic to v2 without affecting responses
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api-mirror
spec:
  hosts:
  - api
  http:
  - route:
    - destination:
        host: api
        subset: v1
      weight: 100
    mirror:
      host: api
      subset: v2
    mirrorPercentage:
      value: 100.0

It’s the strongest validation available — real requests, real payloads, real load — but also the most dangerous operationally: mirrored writes will execute twice unless the canary is read-only or writes go to a separate store. Mirror before you canary, never instead of thinking.

Advanced: Circuit Breaking During the Rollout

A canary that’s too successful can drown itself: 10% of traffic on 1 pod may exceed its capacity before the rollout progresses. A dedicated DestinationRule with tighter connection limits and LEAST_REQUEST balancing protects the small canary pool:

apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: api-circuit-breaker
spec:
  host: api
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 50
      http:
        http1MaxPendingRequests: 20
        maxRequestsPerConnection: 10
    outlierDetection:
      consecutive5xxErrors: 3
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
    loadBalancer:
      simple: LEAST_REQUEST

Post-Promotion Cleanup

Once v2 owns all the traffic, v1 is dead weight — scale it down, remove it, and drop the subset so the config doesn’t mislead the next deploy.

#!/bin/bash
# cleanup-old-version.sh

# After full canary promotion to v2:
# 1. Remove old VirtualService weights
kubectl apply -f virtual-service-v2-only.yaml

# 2. Scale down v1 deployment
kubectl scale deployment api-v1 --replicas=0

# 3. Wait for pods to terminate
kubectl wait --for=delete pods -l app=api,version=v1 --timeout=60s

# 4. Remove v1 deployment
kubectl delete deployment api-v1

# 5. Remove v1 subset from DestinationRule
kubectl apply -f destination-rule-v2-only.yaml

echo "Cleanup complete. Only v2 is running."

Verifying the Canary

Between phases, confirm the split is real — not just configured. The routing table, the pod distribution, and the metrics should all agree:

# Current weights in effect
kubectl get virtualservice api -o jsonpath='{.spec.http[0].route[*].weight}'

# Where requests actually landed (sidecar access logs show the cluster name)
kubectl logs -l app=api -c istio-proxy --tail=50 | grep "cluster_name"

# Per-version success rate (Prometheus)
istio_requests_total{destination_workload="api-v2",response_code=~"2.."}

If observed traffic doesn’t match configured weights, the usual suspects are a missing subset label on the pods, an older VirtualService shadowing yours, or sidecar caches taking a few seconds to converge.

Best Practices

  • Use Flagger for automated analysis once you’ve run a few manual canaries — it removes the “watch the dashboard for 10 minutes” toil and codifies your thresholds.
  • Monitor latency, error rate, and throughput per version independently; an aggregate dashboard hides a 10% canary that’s 100% broken.
  • Keep the canary pool small but not starved — 1 pod at 10% of high traffic is a load test, not a validation. Scale the canary to roughly match its expected share.
  • Combine with feature flags for dark launches: the canary ships the code off, the flag turns it on for specific users.
  • Pre-warm the canary (1-2% for a couple of minutes) before the real phases so JIT compilation and caches don’t make cold-start latency look like a regression.
  • Keep Istio telemetry lean during high-traffic canaries — full access logs on every sidecar add measurable overhead.

Common Mistakes

  • Sending canary traffic to internal admin endpoints that users never hit — you’ll validate nothing.
  • Not monitoring business metrics (checkout rate, signup conversion). A 200 response proves the pod answered, not that the feature works.
  • Forgetting to scale down or delete the old version after full promotion — orphaned v1 keeps consuming resources and confuses the next rollback decision.
  • Judging the canary too early: 10% of low traffic is a handful of requests, statistically meaningless. Wait for volume or extend the window.
  • Making the canary too big too fast — if your second step is already 50%, you skipped the point of the exercise.
  • Leaving the canary weight in place “just for now” — a stale 10% weight on a long-forgotten v2 becomes a mystery bug source weeks later.

Further Reading

Frequently Asked Questions

How is a canary different from a rolling update?

Rolling updates replace pods in place over time — traffic splits roughly by replica count and you get no percentage control. A canary routes an exact share of traffic you choose, holds it while you measure, and rolls back instantly by resetting a weight instead of redeploying.

Can I target specific users instead of a random percentage?

Yes. Istio matches on headers, cookies, or JWT claims before evaluating weights — route x-canary-test: true (or a cohort cookie) to v2 for "internal users first" rollouts, shown in the header-routing variant above.

When should I use Flagger instead of manual weights?

After two or three canaries run by hand. Flagger automates the weight-bump/measure/decide loop with metric thresholds and webhooks — worth it once the cadence is proven, overkill while you're still learning your service's baseline.

What metrics should gate the rollout?

At minimum: success rate per version (≥99%), p95/p99 latency within ~10% of baseline, and one business metric that matters for this service. HTTP-layer metrics reveal broken code; business metrics reveal broken behavior.

Is traffic mirroring safer than a canary?

For users, yes — mirrored responses get discarded, so nothing user-facing changes. For your data it's the opposite — mirrored writes actually execute. Use mirroring for read-heavy or idempotent paths, then canary for the full validation.

How long should each canary phase last?

However long it takes to see meaningful traffic — usually 5-30 minutes per step, longer at low request volume. The answer is statistical, not temporal: you need enough requests on v2 to tell signal from noise.