StackPractices
intermediate By Mathias Paulenko

Canary Release Pattern

Route a small percentage of traffic to the new version while the rest stays on stable. Monitor health metrics and gradually increase or roll back based on results.

Overview

The Canary Release Pattern routes a small percentage of traffic to a new version while the majority keeps receiving the stable one. Coal miners carried canaries underground to detect dangerous gases, and the pattern borrows the idea: the canary version is your early warning system, exposed to a small group of users. If it fails, the blast radius stays inside that group instead of taking down the whole service.

The rollout happens in stages: you start at 1%, climb through 5%, 25% and 50%, and finish at 100%, with a health check gating each step to decide whether to advance or roll back. Unlike blue-green, which flips all traffic in one shot, canary shifts it gradually, so regressions that only show up under real load surface while they still affect few users. This page covers the rollout mechanics as a reusable design; for the full operational process (approval gates, runbooks, team workflow), see the Canary Deployment guide.

When to Use

Use the Canary Release Pattern when:

  • You want to validate a new version with real users before a full rollout
  • Issues may only appear under production traffic that staging tests never caught
  • You need finer control than blue-green’s all-or-nothing switch
  • Your infrastructure supports traffic splitting (load balancer weights, service mesh, feature flags)
  • Examples: API versioning, UI redesigns, performance-sensitive changes, database query changes

Skip it when:

  • The change breaks schema compatibility — old and new versions can’t safely share the same database, so a canary won’t save you. Use an expand-contract migration instead
  • Traffic is so low that a 1% slice produces no meaningful signal within a reasonable bake time
  • You can’t split traffic at all (single server, no load balancer or mesh) — fix that first
  • Session state can’t be pinned to one version and users would bounce between two different behaviors

If you flip traffic in one shot instead of gradually, use the Blue-Green Deployment Pattern. For a concrete service-mesh implementation, see the Istio canary deployment recipe.

Solution

Python

from dataclasses import dataclass, field
from typing import Callable, List, Optional, Dict
from enum import Enum
import time

class CanaryStatus(Enum):
    PENDING = "pending"
    RUNNING = "running"
    PROMOTED = "promoted"
    ROLLED_BACK = "rolled_back"

@dataclass
class HealthMetrics:
    error_rate: float
    p95_latency_ms: float
    success_rate: float

    def is_healthy(self, max_error_rate: float = 0.02, max_p95: float = 300) -> bool:
        return self.error_rate <= max_error_rate and self.p95_latency_ms <= max_p95

@dataclass
class CanaryStage:
    percentage: float
    bake_time_seconds: float
    metrics: Optional[HealthMetrics] = None
    passed: bool = False

class CanaryRelease:
    def __init__(self, version: str, stable_version: str,
                 health_check_fn: Callable[[], HealthMetrics],
                 stages: Optional[List[CanaryStage]] = None,
                 max_error_rate: float = 0.02, max_p95: float = 300):
        self.version = version
        self.stable_version = stable_version
        self.health_check_fn = health_check_fn
        self.max_error_rate = max_error_rate
        self.max_p95 = max_p95
        self.status = CanaryStatus.PENDING
        self.current_stage_idx = -1
        # Demo bake times; real stages run for minutes, not fractions of a second.
        self.stages = stages or [
            CanaryStage(percentage=1.0, bake_time_seconds=0.1),
            CanaryStage(percentage=5.0, bake_time_seconds=0.1),
            CanaryStage(percentage=25.0, bake_time_seconds=0.1),
            CanaryStage(percentage=50.0, bake_time_seconds=0.1),
            CanaryStage(percentage=100.0, bake_time_seconds=0.1),
        ]

    def _run_stage(self, stage: CanaryStage) -> bool:
        self.current_stage_idx += 1
        self.status = CanaryStatus.RUNNING
        print(f"  Canary at {stage.percentage}% -> stable={100 - stage.percentage}%")

        time.sleep(stage.bake_time_seconds)
        metrics = self.health_check_fn()
        stage.metrics = metrics
        stage.passed = metrics.is_healthy(self.max_error_rate, self.max_p95)

        print(f"    error_rate={metrics.error_rate:.2%}, p95={metrics.p95_latency_ms}ms, success={metrics.success_rate:.2%}")

        if stage.passed:
            print(f"    PASS - advancing to next stage")
            return True
        else:
            print(f"    FAIL - rolling back canary")
            self.status = CanaryStatus.ROLLED_BACK
            return False

    def execute(self) -> Dict:
        print(f"\n=== Canary Release: v{self.version} (stable: v{self.stable_version}) ===")
        for i, stage in enumerate(self.stages):
            if not self._run_stage(stage):
                return self._result(rolled_back=True, failed_stage=i)
        self.status = CanaryStatus.PROMOTED
        print(f"\nCanary promoted. v{self.version} is now at 100%.")
        return self._result(rolled_back=False, failed_stage=None)

    def _result(self, rolled_back: bool, failed_stage: Optional[int]) -> Dict:
        return {
            "version": self.version,
            "status": self.status.value,
            "rolled_back": rolled_back,
            "stages_passed": self.current_stage_idx if rolled_back else len(self.stages),
            "failed_stage": failed_stage,
            "max_percentage_reached": self.stages[self.current_stage_idx].percentage if rolled_back else 100.0,
        }

# Usage
call_count = 0
def mock_health_check() -> HealthMetrics:
    global call_count
    call_count += 1
    if call_count == 3:
        return HealthMetrics(error_rate=0.05, p95_latency_ms=400, success_rate=0.95)
    return HealthMetrics(error_rate=0.005, p95_latency_ms=80, success_rate=0.995)

canary = CanaryRelease(
    version="3.0.0", stable_version="2.9.0",
    health_check_fn=mock_health_check,
    max_error_rate=0.02, max_p95=300,
)

result = canary.execute()
print(f"\nResult: {result}")

JavaScript

class CanaryRelease {
  constructor(version, stableVersion, healthCheckFn, options = {}) {
    this.version = version;
    this.stableVersion = stableVersion;
    this.healthCheckFn = healthCheckFn;
    this.maxErrorRate = options.maxErrorRate ?? 0.02;
    this.maxP95 = options.maxP95 ?? 300;
    this.status = "pending";
    this.currentStageIdx = -1;
    // Demo bake times; real stages run for minutes, not milliseconds.
    this.stages = options.stages ?? [
      { percentage: 1.0, bakeTimeMs: 100 },
      { percentage: 5.0, bakeTimeMs: 100 },
      { percentage: 25.0, bakeTimeMs: 100 },
      { percentage: 50.0, bakeTimeMs: 100 },
      { percentage: 100.0, bakeTimeMs: 100 },
    ];
  }

  async _runStage(stage) {
    this.currentStageIdx++;
    this.status = "running";
    console.log(`  Canary at ${stage.percentage}% -> stable=${100 - stage.percentage}%`);
    await new Promise(r => setTimeout(r, stage.bakeTimeMs));
    const m = this.healthCheckFn();
    const healthy = m.errorRate <= this.maxErrorRate && m.p95LatencyMs <= this.maxP95;
    console.log(`    error_rate=${(m.errorRate * 100).toFixed(2)}%, p95=${m.p95LatencyMs}ms`);
    if (healthy) { console.log(`    PASS - advancing`); return true; }
    console.log(`    FAIL - rolling back`);
    this.status = "rolled_back";
    return false;
  }

  async execute() {
    console.log(`\n=== Canary Release: v${this.version} (stable: v${this.stableVersion}) ===`);
    for (let i = 0; i < this.stages.length; i++) {
      if (!await this._runStage(this.stages[i])) {
        return { version: this.version, status: this.status, rolledBack: true,
                 stagesPassed: this.currentStageIdx, failedStage: i,
                 maxPercentage: this.stages[this.currentStageIdx].percentage };
      }
    }
    this.status = "promoted";
    console.log(`\nCanary promoted. v${this.version} is now at 100%.`);
    return { version: this.version, status: this.status, rolledBack: false,
             stagesPassed: this.stages.length, maxPercentage: 100 };
  }
}

// Usage
let callCount = 0;
const mockHealthCheck = () => {
  callCount++;
  if (callCount === 3) return { errorRate: 0.05, p95LatencyMs: 400, successRate: 0.95 };
  return { errorRate: 0.005, p95LatencyMs: 80, successRate: 0.995 };
};

(async () => {
  const canary = new CanaryRelease("3.0.0", "2.9.0", mockHealthCheck, { maxErrorRate: 0.02, maxP95: 300 });
  console.log("\nResult:", await canary.execute());
})();

Java

import java.util.*;

public class CanaryRelease {

    record HealthMetrics(double errorRate, double p95LatencyMs, double successRate) {
        boolean isHealthy(double maxError, double maxP95) {
            return errorRate <= maxError && p95LatencyMs <= maxP95;
        }
    }

    record Stage(double percentage, long bakeTimeMs) {}

    private final String version, stableVersion;
    private final java.util.function.Supplier<HealthMetrics> healthCheckFn;
    private final double maxErrorRate, maxP95;
    private String status = "pending";
    private int currentStageIdx = -1;
    private final List<Stage> stages;

    public CanaryRelease(String version, String stableVersion,
                         java.util.function.Supplier<HealthMetrics> healthCheckFn,
                         double maxErrorRate, double maxP95) {
        this.version = version; this.stableVersion = stableVersion;
        this.healthCheckFn = healthCheckFn; this.maxErrorRate = maxErrorRate; this.maxP95 = maxP95;
        // Demo bake times; real stages run for minutes, not milliseconds.
        this.stages = List.of(
            new Stage(1.0, 100), new Stage(5.0, 100), new Stage(25.0, 100),
            new Stage(50.0, 100), new Stage(100.0, 100)
        );
    }

    private boolean runStage(Stage stage) {
        currentStageIdx++;
        status = "running";
        System.out.printf("  Canary at %.0f%% -> stable=%.0f%%%n", stage.percentage(), 100 - stage.percentage());
        try { Thread.sleep(stage.bakeTimeMs()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        HealthMetrics m = healthCheckFn.get();
        boolean healthy = m.isHealthy(maxErrorRate, maxP95);
        System.out.printf("    error_rate=%.2f%%, p95=%.0fms%n", m.errorRate() * 100, m.p95LatencyMs());
        if (healthy) { System.out.println("    PASS - advancing"); return true; }
        System.out.println("    FAIL - rolling back");
        status = "rolled_back";
        return false;
    }

    public Map<String, Object> execute() {
        System.out.printf("%n=== Canary Release: v%s (stable: v%s) ===%n", version, stableVersion);
        for (int i = 0; i < stages.size(); i++) {
            if (!runStage(stages.get(i))) {
                return Map.of("version", version, "status", status, "rolledBack", true,
                    "stagesPassed", currentStageIdx, "failedStage", i,
                    "maxPercentage", stages.get(currentStageIdx).percentage());
            }
        }
        status = "promoted";
        System.out.printf("%nCanary promoted. v%s is now at 100%%.%n", version);
        return Map.of("version", version, "status", status, "rolledBack", false,
            "stagesPassed", stages.size(), "maxPercentage", 100.0);
    }

    public static void main(String[] args) {
        int[] callCount = {0};
        var healthCheck = (java.util.function.Supplier<HealthMetrics>) () -> {
            callCount[0]++;
            if (callCount[0] == 3) return new HealthMetrics(0.05, 400, 0.95);
            return new HealthMetrics(0.005, 80, 0.995);
        };
        System.out.println("\nResult: " + new CanaryRelease("3.0.0", "2.9.0", healthCheck, 0.02, 300).execute());
    }
}

Explanation

The canary release moves through predefined stages, each one gated by a health check before traffic increases:

Mermaid flowchart LR diagram
  1. Route a percentage: configure the load balancer or service mesh to send a small slice of traffic to the canary version while everything else stays on stable, both versions serving requests side by side.
  2. Bake and measure: wait out the bake time so the canary accumulates enough requests, then pull its health metrics — error rate, p95/p99 latency, saturation — plus business KPIs like conversion or signup rate. In production this query usually hits Prometheus, Datadog, or whatever metrics backend you run, not a mock function like in the examples above (their sub-second bake times are demo values; real stages run 5-30 minutes).
  3. Advance or roll back: if metrics stay inside thresholds, bump the percentage to the next stage; if they degrade, send 100% back to stable and kill the canary. Automate it; a canary that depends on someone noticing and clicking “revert” at 3 a.m. only turns a bad deploy into a slightly slower outage.
  4. Promote: at 100% with healthy metrics, the canary becomes the new stable version and the old one can be decommissioned.

Thresholds matter more than the stage list itself — a common baseline is error rate under 1-2% and p95 latency within roughly 20-30% of stable, but the right numbers come from your own SLOs, not from a default.

Canary vs Blue-Green vs Deployment Rings

StrategyTraffic shiftBest forMain limitation
Canary releaseGradual, weighted percentageValidating with real users, early regression detectionNeeds metrics and traffic splitting
Blue-greenInstant 0→100%Simple rollouts with easy rollbackDouble infrastructure, no gradual signal
Deployment ringFixed cohorts (internal → beta → all users)User-segment rollouts, large SaaS fleetsSlower; needs cohort management

You don’t have to build the rollout loop yourself. Argo Rollouts and Flagger automate canary analysis on Kubernetes, Istio traffic shifting splits requests by weight inside the mesh, and AWS ALB comes with weighted target groups at the load balancer.

Variants

VariantDescriptionUse Case
User-based canaryRoute specific users (internal team, beta group) instead of a random percentageControlled testing with known users
Header-based canaryRoute by request attribute (cookie, header, region)Targeted client or geo testing
Shadow canaryMirror traffic to the canary but discard its responsesLoad testing with zero user impact
Auto-promote canaryAdvance stages automatically when metrics pass — Flagger and Argo Rollouts implement this on KubernetesLow-risk changes with strong monitoring

What Works

  • Start at 1% or less to minimize blast radius
  • Monitor both technical and business metrics (error rate, latency, conversion)
  • Set bake times long enough for statistically significant data
  • Define auto-rollback thresholds before starting the canary
  • Use sticky sessions so a user stays on the same version during the canary
  • Keep the stable version running until the canary reaches 100% and is confirmed healthy

Common Mistakes

  • Starting at too high a percentage (10% or more), defeating the early warning purpose
  • Not monitoring business metrics, only checking error rates
  • Bake times too short, advancing before enough data accumulates
  • No auto-rollback, requiring manual intervention during incidents
  • Users bouncing between versions due to lack of sticky sessions
  • Decommissioning the stable version before the canary is fully promoted

Frequently Asked Questions

How is a canary release different from blue-green deployment?

Blue-green swaps 100% of traffic between two environments in one shot. Canary shifts a percentage gradually while the old version keeps serving the rest — you trade a slower rollout for finer control and earlier regression detection.

What percentage should I start with?

1% is the standard starting point, and on high-traffic services that can already be thousands of users. On low-traffic services you'll want a higher slice or a longer bake time to get a meaningful signal.

How do I route a percentage of traffic to the canary?

Use load balancer weights (e.g., AWS ALB weighted target groups), service mesh rules (Istio, Linkerd), feature flags (LaunchDarkly, Unleash), or API gateway splitting — all of them adjust the percentage without redeploying. For a concrete Istio setup, see the Istio canary deployment recipe.

Is a canary release the same as an A/B test?

No. A/B tests compare variants to pick a winner on a business metric; a canary checks whether a new version is healthy enough to keep rolling out and rolls back when it isn't. One is experimentation, the other is deployment safety.

What if the canary passes technical metrics but users report issues?

Include user-facing signals in the health gate: support ticket rate, user-reported errors, session duration, bounce rate. Technical metrics catch crashes, but UX regressions don't always show up as errors.