Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 18 – Delivery, multi-region, disaster recovery and cost

Safe deployments: canaries, rollbacks and flags

Compare rolling, blue-green and canary deployments, judge a canary from its error counts, keep rollbacks safe and release features with flags.

  • Intermediate
  • 30 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 30 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Compare rolling, blue-green and canary deployments by exposure, extra capacity and rollback speed
  • Decide from error counts whether a canary should be promoted, kept waiting or rolled back
  • Design a change to stored data that can be rolled back at every step
  • Release a feature behind a flag with a percentage rollout that gives every user a stable answer
  • Track delivery with the five DORA metrics

Before you start

What you’ll learn · Before you start

What you will learn

  • Compare rolling, blue-green and canary deployments by exposure, extra capacity and rollback speed
  • Decide from error counts whether a canary should be promoted, kept waiting or rolled back
  • Design a change to stored data that can be rolled back at every step
  • Release a feature behind a flag with a percentage rollout that gives every user a stable answer
  • Track delivery with the five DORA metrics

Before you start

On this page

One bad build deployed to every server of a service that takes 2,000 requests a second fails 360,000 requests before it is undone; the same build on a 5% canary release: A release that first sends a small share of real traffic, often 1 % to 5 %, to the new version and compares it with the old version serving at the same time before every step up. fails 13,200. A safe deployment limits how many users a bad change can reach and how quickly it is undone. Three tools do most of the work. A canary sends a small share of traffic to the new version and compares it with the old one before going further. A rollback returns to the last version that worked, and it is safe only when the old and new versions can read each other’s data. A feature flag: A switch in configuration that code reads at run time to turn a behaviour on or off for some or all users, so that releasing a feature, or switching it off again, needs no deploy. lets you deploy code switched off and release it later, to a percentage of users, with a switch that turns it off again in seconds.

Below, each gets numbers: the requests a bad build fails under each strategy, how long a canary must run, and why some rollbacks make an incident worse.

A bad build’s damage is its share of traffic times its time

Changes are where most outages start. Google’s SRE book reports that roughly 70% of outages come from changes to a live system, and names three habits that limit the damage: roll out progressively, detect problems quickly and accurately, and roll back safely (SRE book, introduction). The damage is roughly the share of traffic a bad build serves times the time until it is gone. That share is the change’s blast radius: The share of customers or requests that one failure or one bad deploy can reach. Cells, zones and rollouts in waves exist to keep it small. More in “Cells, deployment stamps and blast radius”. The program below works it out for a build that fails 20% of its requests, deployed in five ways to a service taking 2,000 requests a second. Each strategy gets the same 10 minutes before someone notices, so only the exposure and the way back differ.

Failed requests for one bad build, five ways Python · blast/blast_radius.py
"""How many requests a bad build fails under five ways of deploying it.

Assumptions (change them and run again): the service takes 2,000 requests a second, the bad build fails
20% of the requests it serves, and the problem is noticed 10 minutes after the first users reach the new
version, whatever the strategy. Undoing it then takes as long as each strategy needs.
"""

RPS = 2_000
BAD_BUILD_FAILS = 0.20
NOTICED_AFTER_S = 10 * 60
SLO = 0.999                      # a 99.9% monthly availability objective
MONTH_S = 30 * 24 * 3600


def failed_requests(steps):
    """steps: (seconds, share of traffic on the new version) in order; returns failed requests."""
    return sum(RPS * BAD_BUILD_FAILS * share * seconds for seconds, share in steps)


def until_noticed(schedule):
    """Cut a rollout schedule of (seconds, share) at the moment the problem is noticed."""
    steps, elapsed = [], 0
    for seconds, share in schedule:
        take = min(seconds, NOTICED_AFTER_S - elapsed)
        if take <= 0:
            break
        steps.append((take, share))
        elapsed += take
    if elapsed < NOTICED_AFTER_S:          # the rollout finished before anyone noticed
        steps.append((NOTICED_AFTER_S - elapsed, schedule[-1][1]))
    return steps


rolling = [(150, 0.25), (150, 0.50), (150, 0.75), (10**9, 1.0)]   # a batch of 25% every 2.5 minutes
strategies = {
    "all at once, redeploy the old version (5 min)": until_noticed([(10**9, 1.0)]) + [(300, 1.0)],
    "rolling, rolled back the same way": until_noticed(rolling) + [(150, 0.75), (150, 0.50), (150, 0.25)],
    "blue-green, switch back (1 min)": until_noticed([(10**9, 1.0)]) + [(60, 1.0)],
    "canary on 5%, weight back to 0 (1 min)": until_noticed([(10**9, 0.05)]) + [(60, 0.05)],
    "canary on 1%, weight back to 0 (1 min)": until_noticed([(10**9, 0.01)]) + [(60, 0.01)],
}

budget = (1 - SLO) * RPS * MONTH_S
print(f"Monthly error budget at {SLO:.1%}: {budget:,.0f} failed requests")
print(f"{'strategy':<46} {'failed requests':>15} {'budget used':>11}")
for name, steps in strategies.items():
    failed = failed_requests(steps)
    print(f"{name:<46} {failed:>15,.0f} {failed / budget:>11.2%}")

Output

Monthly error budget at 99.9%: 5,184,000 failed requests
strategy                                       failed requests budget used
all at once, redeploy the old version (5 min)          360,000       6.94%
rolling, rolled back the same way                      240,000       4.63%
blue-green, switch back (1 min)                        264,000       5.09%
canary on 5%, weight back to 0 (1 min)                  13,200       0.25%
canary on 1%, weight back to 0 (1 min)                   2,640       0.05%

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 blast_radius.py

A milder bad build

Press Edit, set BAD_BUILD_FAILS to 0.02, a build that fails one request in fifty, and run it again. Every row falls tenfold, and the order of the five strategies stays the same, because the damage is a share times a time.

Against a 99.9% monthly service level objective (SLO): A target for a service level indicator over a stated period, such as 99% of redirects answered within 100 ms, measured at the server. More in “Turning a vague prompt into requirements”, whose error budget allows 5,184,000 failed requests at this traffic, a bad build deployed everywhere spends about 7% of the month’s budget in a quarter of an hour. blue-green deployment: A release onto a second full environment that is tested with no users and then made live by one switch of the router; the old environment stays ready, so switching back takes seconds. does better only because switching back takes a minute instead of a redeploy. A rolling update: A release that replaces a few instances at a time until all of them run the new version, so old and new versions serve side by side for the whole rollout. that nothing stops reaches every instance after 7.5 minutes, before anyone notices, and its way back takes as long. A 5% canary fails 13,200 requests, about a twenty-seventh of the damage: a twentieth of the traffic meets the bad build, for 11 minutes instead of 15.

Key idea

The damage of a bad build is the share of traffic it serves times the time until it is gone: canaries cut the share, and fast detection, automatic rollbacks and flags cut the time.

Checkpoint

Check: A bad build's damage

  1. One question A service takes 1,000 requests a second. A bad build that fails 10% of the requests it serves runs on a 5% canary for 10 minutes before the canary's share goes back to 0. How many requests fail?

    Type a number.

    A hint

    Work out the canary's requests a second, then the seconds, then the share that fails.

    Show the answer: One question

    Answer: 3000 requests

    The canary serves 5% of 1,000, or 50 requests a second, for 600 seconds: 30,000 requests. A tenth of them fail: 3,000. Deployed to everyone for the same 10 minutes, the same build would fail 60,000, twenty times as many, because the share of traffic it reaches is twenty times as large.

Rolling, blue-green or canary: what each risks and costs

The three common strategies differ first in how quickly the new version gets its traffic. The figure shows the share on the new version at each step of each one:

The share of traffic on the new version, step by step, for a rolling update, a blue-green switch and a canary.Rolling updateBlue-greenCanary25%50%75%100%0%tested,no users100%blue keptfor rollback1%check5%check25%check100%

How traffic moves to a new version under each strategy

Text description of the diagram

Three rows, one per strategy, each a sequence of steps joined by arrows from left to right. Each step gives the share of the traffic on the new version.

- Rolling update: 25%, 50%, 75%, then 100%, as batches of instances are replaced. - Blue-green: 0% while the new environment is tested with no users, then 100% after one switch of the router, with the old environment, blue, kept for rollback. - Canary: 1%, 5% and 25%, each followed by a check against the old version, then 100%.

A rolling update replaces instances a few at a time until all of them run the new version. It is the default strategy of a Kubernetes Deployment, which by default keeps at least 75% of the desired Pods available and runs at most 125% of them during an update (maxUnavailable and maxSurge of 25% each) (Kubernetes documentation). It needs only a few spare instances, but old and new versions serve side by side for the whole rollout, and going back is another rollout in the other direction (kubectl rollout undo). Kubernetes reports a Deployment that has made no progress for 600 seconds (progressDeadlineSeconds) and keeps retrying it, but leaves any rollback to a higher-level tool.

Recreate

Recreate, the other built-in strategy, stops every old Pod before starting new ones: a gap in service, but never two versions at once.

Blue-green keeps two full environments. The new version is deployed to the idle one, green, and tested with no users; then the router sends everyone to green, and switching back to blue, kept running, is a rollback in seconds (Fowler, BlueGreenDeployment). It costs a second environment, and everyone moves at once, so a defect the tests missed reaches every user until the switch back. The two environments usually share one database, so change its schema first, in a form both versions can use.

A canary sends a small share of traffic, often 1% to 5%, to the new version and compares it with the old one before every step up. Argo Rollouts, a Kubernetes controller, writes the plan as steps, such as a weight of 10%, a pause of an hour, then 20%, with an analysis running beside them; a failed analysis aborts the rollout and sets the canary’s weight back to zero (canary, analysis). Without a router that splits traffic, the weight is approximated by counting Pods: 10 replicas at 10% means one canary Pod, and with 12 instances the smallest canary is about 8% of the traffic.

Four questions about your service decide most of the choice. Answer them in the table: it marks the ways of deploying that fit and says why the others do not, with the numbers of the program above in its cells.

Interactive · answer and compare Which way of deploying fits your service? Answer four questions about your service. The table marks the ways of deploying that fit and says why the others do not.
Must the old version stop before the new one starts, as for a job that two copies would run twice?
Can your router send a set share of the traffic, such as 5 %, to the new version?
Can you pay for a second full copy of production for the length of a release?
Does the service take thousands of requests a minute, enough to judge a small share quickly?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Four ways of deploying against the four things that decide between them (numbers from the programs above)
Strategy A bad build reaches Extra capacity Versions side by side Going back
Rolling update Moves traffic by: replacing a batch of instances at a time Mixed every new batch: all instances after 7.5 minutes, 240,000 failed requests Good a few spare instances: at most 125 % of the Pods by default Poor old and new serve together for the whole rollout Poor another rollout the other way: 7.5 minutes in the program
Blue-green Moves traffic by: one switch of the router Poor everyone at once: 264,000 failed requests before the switch back Poor a second full environment for the whole release Good never in traffic; only the shared database meets both Good one switch of the router: a minute in the program
Canary Moves traffic by: a small share first, then steps Good its share only: 13,200 failed requests at 5 %, against 360,000 for all at once Good a few instances, or a weight on a router Mixed yes, on purpose: the comparison needs both versions Good weight back to zero: a minute in the program
Recreate Moves traffic by: stopping every old instance first Poor everyone, after a gap with no service at all Good none: the old instances stop before the new ones start Good never: the old version stops first Poor another recreate, with another gap
How the answers decide
  • “Must the old version stop before the new one starts, as for a job that two copies would run twice?” Yes, never two at once: rules out Rolling update, Blue-green and Canary. Each of them has a moment when two versions run at once. Recreate accepts a short gap in service instead.
  • “Must the old version stop before the new one starts, as for a job that two copies would run twice?” No, they may overlap: rules out Recreate. Recreate stops every old instance before the new ones start: a gap in service that nothing else here needs.
  • “Can your router send a set share of the traffic, such as 5 %, to the new version?” No, only by instance: adds a caveat to Canary. Without a traffic split, a canary's share is its count of instances: with 12 instances the smallest step is about 8 %.
  • “Can you pay for a second full copy of production for the length of a release?” No: rules out Blue-green. Blue-green keeps a second full environment running for the whole release.
  • “Does the service take thousands of requests a minute, enough to judge a small share quickly?” No, it is quiet: adds a caveat to Canary. Rare errors need many requests: at 200 requests a second a 5 % canary needs about 41 minutes to catch a doubled 0.1 % error rate.
  • “Does the service take thousands of requests a minute, enough to judge a small share quickly?” Yes, it is busy: adds a caveat to Rolling update. A rolling update that nothing stops reaches every instance before most problems are noticed: all of them after 7.5 minutes in the program.

The rule of thumb

A rolling update for low-risk stateless services, blue-green for a change all users must get at once and leave in seconds, a canary for busy services where failures are costly, and recreate when two versions must never run together.

Checkpoint

Check: Rolling, blue-green and canary

  1. Question 1 of 2 A nightly billing job runs as a single process. Two versions must never run at the same time, because both would charge the same customers, and a few minutes without the job are harmless. Which way of deploying fits?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Recreate, stopping the old version before the new one starts

    Every other strategy has a moment when two versions run side by side, which is exactly what this job cannot allow. Recreate accepts a short gap instead, and for a job that runs once a night the gap costs nothing.

  2. Question 2 of 2 A stateless thumbnail service runs on 12 instances with readiness checks, and its load balancer cannot split traffic by percentage. A bad build would make some thumbnails slow, nothing worse. Which way of deploying fits?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A rolling update that replaces a few instances at a time while readiness checks pass

    With 12 instances the smallest step is one instance, about 8% of traffic, so a 1% canary is not possible without a traffic router; a rolling update with health checks already gives a gradual swap. The risk is low, so a second full environment would cost more than it saves, and Recreate would take the service down for no reason.

A canary is judged against the old version, by its numbers

Compare the canary with the old version serving traffic during the same minutes, not with the whole fleet and not with the hour before the deploy. A fleet-wide error rate hides a small canary: one on 5% of traffic that fails 10% of its requests moves the fleet’s rate by half a percentage point. A before-and-after comparison mixes the release with everything else that changed, such as the time of day or a slow dependency. Google’s SRE workbook makes both points and advises a few metrics that show real problems, such as errors and latency (SRE workbook, canarying releases).

Whether the canary’s error rate is really higher is a question about two proportions, answered by the two-proportion z-test (NIST/SEMATECH e-Handbook, 7.3.3). With pcp_c and pbp_b the error rates of the canary and the baseline, ncn_c and nbn_b their requests, and pp the error rate of both groups together:

z=pc−pbp(1−p)(1nc+1nb)z = \frac{p_c - p_b}{\sqrt{p\,(1 - p)\left(\frac{1}{n_c} + \frac{1}{n_b}\right)}}

In words: z is the gap between the two error rates, measured in standard errors of that gap. The program below turns z into a decision. It rolls back at z of 3 or more, a strict limit because an automated check looks again every minute and each look is another chance of a false alarm. It never promotes a canary that has served fewer than 10,000 requests, and an absolute ceiling of 2% errors, which would come from the SLO, rolls back a badly broken build without waiting for statistics. Each tab holds the same program in another language, and all 14 printed the same four lines:

One program · 14 languages Promote, wait or roll back, from the error counts

Python 3.14 · main.py

from math import sqrt
from typing import NamedTuple

Z_LIMIT = 3.0
MIN_REQUESTS = 10_000
CEILING = 0.02


class Check(NamedTuple):
    name: str
    base_errors: int
    base_total: int
    canary_errors: int
    canary_total: int


def z_score(c: Check) -> float:
    # Two-proportion z statistic with the pooled error rate.
    pooled = (c.base_errors + c.canary_errors) / (c.base_total + c.canary_total)
    if pooled in (0, 1):
        return 0.0
    spread = 1 / c.base_total + 1 / c.canary_total
    gap = c.canary_errors / c.canary_total - c.base_errors / c.base_total
    return gap / sqrt(pooled * (1 - pooled) * spread)


def decide(c: Check) -> str:
    if c.canary_errors / c.canary_total > CEILING:
        return "roll back: over the ceiling"
    if z_score(c) >= Z_LIMIT:
        return "roll back: worse than baseline"
    if c.canary_total < MIN_REQUESTS:
        return "wait: too few requests"
    return "promote"


CHECKS = [
    Check("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
    Check("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
    Check("regressed, 30 s", 285, 57_000, 24, 3_000),
    Check("broken, 30 s", 285, 57_000, 750, 3_000),
]

for c in CHECKS:
    base = f"{c.base_errors / c.base_total:.2%}"
    canary = f"{c.canary_errors / c.canary_total:.2%}"
    z = z_score(c)
    print(f"{c.name}: baseline {base}, canary {canary}, z {z:.1f} -> {decide(c)}")

In Python: f-strings format the rates with :.2%, which multiplies by 100 and adds the % sign; a NamedTuple keeps the four counts of a check together.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

const Z_LIMIT = 3.0;
const MIN_REQUESTS = 10_000;
const CEILING = 0.02;

function zScore(c) {
  // Two-proportion z statistic with the pooled error rate.
  const pooled = (c.baseErrors + c.canaryErrors) / (c.baseTotal + c.canaryTotal);
  if (pooled === 0 || pooled === 1) return 0;
  const spread = 1 / c.baseTotal + 1 / c.canaryTotal;
  const gap = c.canaryErrors / c.canaryTotal - c.baseErrors / c.baseTotal;
  return gap / Math.sqrt(pooled * (1 - pooled) * spread);
}

function decide(c) {
  if (c.canaryErrors / c.canaryTotal > CEILING) return "roll back: over the ceiling";
  if (zScore(c) >= Z_LIMIT) return "roll back: worse than baseline";
  if (c.canaryTotal < MIN_REQUESTS) return "wait: too few requests";
  return "promote";
}

const check = (name, baseErrors, baseTotal, canaryErrors, canaryTotal) => ({
  name,
  baseErrors,
  baseTotal,
  canaryErrors,
  canaryTotal,
});

const checks = [
  check("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
  check("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
  check("regressed, 30 s", 285, 57_000, 24, 3_000),
  check("broken, 30 s", 285, 57_000, 750, 3_000),
];

const percent = (errors, total) => `${((errors / total) * 100).toFixed(2)}%`;

for (const c of checks) {
  const base = percent(c.baseErrors, c.baseTotal);
  const canary = percent(c.canaryErrors, c.canaryTotal);
  const z = zScore(c).toFixed(1);
  console.log(`${c.name}: baseline ${base}, canary ${canary}, z ${z} -> ${decide(c)}`);
}

In JavaScript: toFixed rounds to the given decimals; numbers are doubles, so every division here is a floating-point one.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.List;
import java.util.Locale;

public class Main {
  static final double Z_LIMIT = 3.0;
  static final int MIN_REQUESTS = 10_000;
  static final double CEILING = 0.02;

  record Check(String name, int baseErrors, int baseTotal, int canaryErrors, int canaryTotal) {}

  static double rate(int errors, int total) {
    return (double) errors / total;
  }

  static double zScore(Check c) {
    // Two-proportion z statistic with the pooled error rate.
    double pooled = rate(c.baseErrors() + c.canaryErrors(), c.baseTotal() + c.canaryTotal());
    if (pooled == 0 || pooled == 1) {
      return 0;
    }
    double spread = 1.0 / c.baseTotal() + 1.0 / c.canaryTotal();
    double gap = rate(c.canaryErrors(), c.canaryTotal()) - rate(c.baseErrors(), c.baseTotal());
    return gap / Math.sqrt(pooled * (1 - pooled) * spread);
  }

  static String decide(Check c) {
    if (rate(c.canaryErrors(), c.canaryTotal()) > CEILING) {
      return "roll back: over the ceiling";
    } else if (zScore(c) >= Z_LIMIT) {
      return "roll back: worse than baseline";
    } else if (c.canaryTotal() < MIN_REQUESTS) {
      return "wait: too few requests";
    }
    return "promote";
  }

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    List<Check> checks =
        List.of(
            new Check("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
            new Check("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
            new Check("regressed, 30 s", 285, 57_000, 24, 3_000),
            new Check("broken, 30 s", 285, 57_000, 750, 3_000));

    for (Check c : checks) {
      System.out.printf(
          "%s: baseline %.2f%%, canary %.2f%%, z %.1f -> %s%n",
          c.name(),
          100 * rate(c.baseErrors(), c.baseTotal()),
          100 * rate(c.canaryErrors(), c.canaryTotal()),
          zScore(c),
          decide(c));
    }
  }
}

In Java: printf formats numbers for the default locale, so main sets Locale.ROOT first; the cast to double keeps int division from dropping the fraction.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <cmath>
#include <print>
#include <string_view>
#include <vector>

constexpr double Z_LIMIT = 3.0;
constexpr int MIN_REQUESTS = 10'000;
constexpr double CEILING = 0.02;

struct Check {
  std::string_view name;
  int base_errors, base_total, canary_errors, canary_total;
};

double rate(int errors, int total) {
  return static_cast<double>(errors) / total;
}

double z_score(const Check &c) {
  // Two-proportion z statistic with the pooled error rate.
  const double pooled =
      rate(c.base_errors + c.canary_errors, c.base_total + c.canary_total);
  if (pooled == 0 || pooled == 1) {
    return 0;
  }
  const double spread = 1.0 / c.base_total + 1.0 / c.canary_total;
  const double gap =
      rate(c.canary_errors, c.canary_total) - rate(c.base_errors, c.base_total);
  return gap / std::sqrt(pooled * (1 - pooled) * spread);
}

std::string_view decide(const Check &c) {
  if (rate(c.canary_errors, c.canary_total) > CEILING) {
    return "roll back: over the ceiling";
  }
  if (z_score(c) >= Z_LIMIT) {
    return "roll back: worse than baseline";
  }
  if (c.canary_total < MIN_REQUESTS) {
    return "wait: too few requests";
  }
  return "promote";
}

int main() {
  const std::vector<Check> checks = {
      {"healthy, 10 min", 5'700, 1'140'000, 312, 60'000},
      {"regressed, 10 min", 5'700, 1'140'000, 480, 60'000},
      {"regressed, 30 s", 285, 57'000, 24, 3'000},
      {"broken, 30 s", 285, 57'000, 750, 3'000},
  };

  for (const auto &c : checks) {
    std::println("{}: baseline {:.2f}%, canary {:.2f}%, z {:.1f} -> {}", c.name,
                 100 * rate(c.base_errors, c.base_total),
                 100 * rate(c.canary_errors, c.canary_total), z_score(c),
                 decide(c));
  }
}

In C++: std::println takes Python-like format specs such as {:.2f}, and the cast to double keeps integer division from dropping the fraction.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

const double ZLimit = 3.0;
const int MinRequests = 10_000;
const double Ceiling = 0.02;

Check[] checks =
[
    new("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
    new("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
    new("regressed, 30 s", 285, 57_000, 24, 3_000),
    new("broken, 30 s", 285, 57_000, 750, 3_000),
];

foreach (var c in checks)
{
    double baseline = 100 * Rate(c.BaseErrors, c.BaseTotal);
    double canary = 100 * Rate(c.CanaryErrors, c.CanaryTotal);
    string rates = $"baseline {baseline:F2}%, canary {canary:F2}%";
    Console.WriteLine($"{c.Name}: {rates}, z {ZScore(c):F1} -> {Decide(c)}");
}

static double Rate(int errors, int total) => (double)errors / total;

static double ZScore(Check c)
{
    // Two-proportion z statistic with the pooled error rate.
    double pooled = Rate(c.BaseErrors + c.CanaryErrors, c.BaseTotal + c.CanaryTotal);
    if (pooled == 0 || pooled == 1)
    {
        return 0;
    }
    double spread = 1.0 / c.BaseTotal + 1.0 / c.CanaryTotal;
    double gap = Rate(c.CanaryErrors, c.CanaryTotal) - Rate(c.BaseErrors, c.BaseTotal);
    return gap / Math.Sqrt(pooled * (1 - pooled) * spread);
}

static string Decide(Check c) => true switch
{
    _ when Rate(c.CanaryErrors, c.CanaryTotal) > Ceiling => "roll back: over the ceiling",
    _ when ZScore(c) >= ZLimit => "roll back: worse than baseline",
    _ when c.CanaryTotal < MinRequests => "wait: too few requests",
    _ => "promote",
};

record Check(string Name, int BaseErrors, int BaseTotal, int CanaryErrors, int CanaryTotal);

In C#: CultureInfo.InvariantCulture keeps the decimal point a dot in every culture; F2 after a value in an interpolated string rounds it to two decimals.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <math.h>
#include <stddef.h>
#include <stdio.h>

static const double Z_LIMIT = 3.0;
static const int MIN_REQUESTS = 10000;
static const double CEILING = 0.02;

typedef struct {
  const char *name;
  int base_errors, base_total, canary_errors, canary_total;
} Check;

static double rate(int errors, int total) { return (double)errors / total; }

static double z_score(const Check *c) {
  // Two-proportion z statistic with the pooled error rate.
  const double pooled =
      rate(c->base_errors + c->canary_errors, c->base_total + c->canary_total);
  if (pooled == 0 || pooled == 1) {
    return 0;
  }
  const double spread = 1.0 / c->base_total + 1.0 / c->canary_total;
  const double gap = rate(c->canary_errors, c->canary_total) -
                     rate(c->base_errors, c->base_total);
  return gap / sqrt(pooled * (1 - pooled) * spread);
}

static const char *decide(const Check *c) {
  if (rate(c->canary_errors, c->canary_total) > CEILING) {
    return "roll back: over the ceiling";
  }
  if (z_score(c) >= Z_LIMIT) {
    return "roll back: worse than baseline";
  }
  if (c->canary_total < MIN_REQUESTS) {
    return "wait: too few requests";
  }
  return "promote";
}

int main(void) {
  static const Check checks[] = {
      {"healthy, 10 min", 5700, 1140000, 312, 60000},
      {"regressed, 10 min", 5700, 1140000, 480, 60000},
      {"regressed, 30 s", 285, 57000, 24, 3000},
      {"broken, 30 s", 285, 57000, 750, 3000},
  };

  for (size_t i = 0; i < sizeof checks / sizeof checks[0]; i++) {
    const Check *c = &checks[i];
    printf("%s: baseline %.2f%%, canary %.2f%%, z %.1f -> %s\n", c->name,
           100 * rate(c->base_errors, c->base_total),
           100 * rate(c->canary_errors, c->canary_total), z_score(c),
           decide(c));
  }
  return 0;
}

In C: printf's %.2f rounds to two decimals and %% prints the percent sign; the cast to double keeps int division from dropping the fraction.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

const Z_LIMIT = 3.0;
const MIN_REQUESTS = 10_000;
const CEILING = 0.02;

/** @param array{string, int, int, int, int} $c the name, then each side's errors and total */
function zScore(array $c): float
{
    [, $baseErrors, $baseTotal, $canaryErrors, $canaryTotal] = $c;
    // Two-proportion z statistic with the pooled error rate.
    $pooled = ($baseErrors + $canaryErrors) / ($baseTotal + $canaryTotal);
    if ($pooled == 0 || $pooled == 1) {
        return 0.0;
    }
    $spread = 1 / $baseTotal + 1 / $canaryTotal;
    $gap = $canaryErrors / $canaryTotal - $baseErrors / $baseTotal;
    return $gap / sqrt($pooled * (1 - $pooled) * $spread);
}

/** @param array{string, int, int, int, int} $c */
function decide(array $c): string
{
    return match (true) {
        $c[3] / $c[4] > CEILING => 'roll back: over the ceiling',
        zScore($c) >= Z_LIMIT => 'roll back: worse than baseline',
        $c[4] < MIN_REQUESTS => 'wait: too few requests',
        default => 'promote',
    };
}

$checks = [
    ['healthy, 10 min', 5_700, 1_140_000, 312, 60_000],
    ['regressed, 10 min', 5_700, 1_140_000, 480, 60_000],
    ['regressed, 30 s', 285, 57_000, 24, 3_000],
    ['broken, 30 s', 285, 57_000, 750, 3_000],
];

foreach ($checks as $c) {
    $rates = sprintf('baseline %.2F%%, canary %.2F%%', 100 * $c[1] / $c[2], 100 * $c[3] / $c[4]);
    printf("%s: %s, z %.1F -> %s\n", $c[0], $rates, zScore($c), decide($c));
}

In PHP: %F formats without the locale, unlike %f; dividing two ints with / gives a float unless the division is exact.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

const Z_LIMIT: f64 = 3.0;
const MIN_REQUESTS: u32 = 10_000;
const CEILING: f64 = 0.02;

struct Check {
    name: &'static str,
    base_errors: u32,
    base_total: u32,
    canary_errors: u32,
    canary_total: u32,
}

fn rate(errors: u32, total: u32) -> f64 {
    f64::from(errors) / f64::from(total)
}

fn z_score(c: &Check) -> f64 {
    // Two-proportion z statistic with the pooled error rate.
    let pooled = rate(
        c.base_errors + c.canary_errors,
        c.base_total + c.canary_total,
    );
    if pooled == 0.0 || pooled == 1.0 {
        return 0.0;
    }
    let spread = 1.0 / f64::from(c.base_total) + 1.0 / f64::from(c.canary_total);
    let gap = rate(c.canary_errors, c.canary_total) - rate(c.base_errors, c.base_total);
    gap / (pooled * (1.0 - pooled) * spread).sqrt()
}

fn decide(c: &Check) -> &'static str {
    if rate(c.canary_errors, c.canary_total) > CEILING {
        "roll back: over the ceiling"
    } else if z_score(c) >= Z_LIMIT {
        "roll back: worse than baseline"
    } else if c.canary_total < MIN_REQUESTS {
        "wait: too few requests"
    } else {
        "promote"
    }
}

fn main() {
    let checks = [
        ("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
        ("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
        ("regressed, 30 s", 285, 57_000, 24, 3_000),
        ("broken, 30 s", 285, 57_000, 750, 3_000),
    ]
    .map(
        |(name, base_errors, base_total, canary_errors, canary_total)| Check {
            name,
            base_errors,
            base_total,
            canary_errors,
            canary_total,
        },
    );

    for c in &checks {
        println!(
            "{}: baseline {:.2}%, canary {:.2}%, z {:.1} -> {}",
            c.name,
            100.0 * rate(c.base_errors, c.base_total),
            100.0 * rate(c.canary_errors, c.canary_total),
            z_score(c),
            decide(c)
        );
    }
}

In Rust: f64::from turns the u32 counts into floats without a lossy cast, and {:.1} rounds inside the format string.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

const Z_LIMIT = 3.0;
const MIN_REQUESTS = 10_000;
const CEILING = 0.02;

type Check = {
  name: string;
  baseErrors: number;
  baseTotal: number;
  canaryErrors: number;
  canaryTotal: number;
};

function zScore(c: Check): number {
  // Two-proportion z statistic with the pooled error rate.
  const pooled = (c.baseErrors + c.canaryErrors) / (c.baseTotal + c.canaryTotal);
  if (pooled === 0 || pooled === 1) return 0;
  const spread = 1 / c.baseTotal + 1 / c.canaryTotal;
  const gap = c.canaryErrors / c.canaryTotal - c.baseErrors / c.baseTotal;
  return gap / Math.sqrt(pooled * (1 - pooled) * spread);
}

function decide(c: Check): string {
  if (c.canaryErrors / c.canaryTotal > CEILING) return "roll back: over the ceiling";
  if (zScore(c) >= Z_LIMIT) return "roll back: worse than baseline";
  if (c.canaryTotal < MIN_REQUESTS) return "wait: too few requests";
  return "promote";
}

const check = (
  name: string,
  baseErrors: number,
  baseTotal: number,
  canaryErrors: number,
  canaryTotal: number,
): Check => ({ name, baseErrors, baseTotal, canaryErrors, canaryTotal });

const checks: Check[] = [
  check("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
  check("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
  check("regressed, 30 s", 285, 57_000, 24, 3_000),
  check("broken, 30 s", 285, 57_000, 750, 3_000),
];

const percent = (errors: number, total: number): string =>
  `${((errors / total) * 100).toFixed(2)}%`;

for (const c of checks) {
  const base = percent(c.baseErrors, c.baseTotal);
  const canary = percent(c.canaryErrors, c.canaryTotal);
  const z = zScore(c).toFixed(1);
  console.log(`${c.name}: baseline ${base}, canary ${canary}, z ${z} -> ${decide(c)}`);
}

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import (
	"fmt"
	"math"
)

const (
	zLimit      = 3.0
	minRequests = 10_000
	ceiling     = 0.02
)

type check struct {
	name                                             string
	baseErrors, baseTotal, canaryErrors, canaryTotal int
}

func rate(errors, total int) float64 { return float64(errors) / float64(total) }

func zScore(c check) float64 {
	// Two-proportion z statistic with the pooled error rate.
	pooled := rate(c.baseErrors+c.canaryErrors, c.baseTotal+c.canaryTotal)
	if pooled == 0 || pooled == 1 {
		return 0
	}
	spread := 1/float64(c.baseTotal) + 1/float64(c.canaryTotal)
	gap := rate(c.canaryErrors, c.canaryTotal) - rate(c.baseErrors, c.baseTotal)
	return gap / math.Sqrt(pooled*(1-pooled)*spread)
}

func decide(c check) string {
	switch {
	case rate(c.canaryErrors, c.canaryTotal) > ceiling:
		return "roll back: over the ceiling"
	case zScore(c) >= zLimit:
		return "roll back: worse than baseline"
	case c.canaryTotal < minRequests:
		return "wait: too few requests"
	default:
		return "promote"
	}
}

func main() {
	checks := []check{
		{"healthy, 10 min", 5_700, 1_140_000, 312, 60_000},
		{"regressed, 10 min", 5_700, 1_140_000, 480, 60_000},
		{"regressed, 30 s", 285, 57_000, 24, 3_000},
		{"broken, 30 s", 285, 57_000, 750, 3_000},
	}

	for _, c := range checks {
		fmt.Printf("%s: baseline %.2f%%, canary %.2f%%, z %.1f -> %s\n", c.name,
			100*rate(c.baseErrors, c.baseTotal), 100*rate(c.canaryErrors, c.canaryTotal),
			zScore(c), decide(c))
	}
}

In Go: A switch with no condition is Go's if-else chain, and float64 converts each count before the division, which would otherwise be on integers.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

let zLimit = 3.0
let minRequests = 10_000
let ceiling = 0.02

typealias Check = (
  name: String, baseErrors: Int, baseTotal: Int, canaryErrors: Int, canaryTotal: Int
)

func rate(_ errors: Int, _ total: Int) -> Double { Double(errors) / Double(total) }

func zScore(_ c: Check) -> Double {
  // Two-proportion z statistic with the pooled error rate.
  let pooled = rate(c.baseErrors + c.canaryErrors, c.baseTotal + c.canaryTotal)
  if pooled == 0 || pooled == 1 { return 0 }
  let spread = 1 / Double(c.baseTotal) + 1 / Double(c.canaryTotal)
  let gap = rate(c.canaryErrors, c.canaryTotal) - rate(c.baseErrors, c.baseTotal)
  return gap / (pooled * (1 - pooled) * spread).squareRoot()
}

func decide(_ c: Check) -> String {
  if rate(c.canaryErrors, c.canaryTotal) > ceiling { return "roll back: over the ceiling" }
  if zScore(c) >= zLimit { return "roll back: worse than baseline" }
  if c.canaryTotal < minRequests { return "wait: too few requests" }
  return "promote"
}

/// `x` rounded to `digits` decimals (the standard library has no number format).
func fixed(_ x: Double, _ digits: Int) -> String {
  var scale = 1
  for _ in 0..<digits { scale *= 10 }
  let units = Int((x * Double(scale)).rounded())
  let fraction = String(units % scale)
  return "\(units / scale)." + String(repeating: "0", count: digits - fraction.count) + fraction
}

let checks: [Check] = [
  ("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
  ("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
  ("regressed, 30 s", 285, 57_000, 24, 3_000),
  ("broken, 30 s", 285, 57_000, 750, 3_000),
]

for c in checks {
  let base = fixed(100 * rate(c.baseErrors, c.baseTotal), 2)
  let canary = fixed(100 * rate(c.canaryErrors, c.canaryTotal), 2)
  let z = fixed(zScore(c), 1)
  print("\(c.name): baseline \(base)%, canary \(canary)%, z \(z) -> \(decide(c))")
}

In Swift: Without Foundation the standard library has no fixed-decimal format, so fixed(_:_:) rounds and writes the digits; squareRoot() is the standard library's square root.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

Z_LIMIT = 3.0
MIN_REQUESTS = 10_000
CEILING = 0.02

Check = Data.define(:name, :base_errors, :base_total, :canary_errors, :canary_total) do
  def base_rate = base_errors.fdiv(base_total)
  def canary_rate = canary_errors.fdiv(canary_total)
  def pooled_rate = (base_errors + canary_errors).fdiv(base_total + canary_total)
  def spread = (1.0 / base_total) + (1.0 / canary_total)
end

# Two-proportion z statistic with the pooled error rate.
def z_score(check)
  pooled = check.pooled_rate
  return 0.0 if [0, 1].include?(pooled)

  (check.canary_rate - check.base_rate) / Math.sqrt(pooled * (1 - pooled) * check.spread)
end

def decide(check)
  return 'roll back: over the ceiling' if check.canary_rate > CEILING
  return 'roll back: worse than baseline' if z_score(check) >= Z_LIMIT
  return 'wait: too few requests' if check.canary_total < MIN_REQUESTS

  'promote'
end

CHECKS = [
  Check.new('healthy, 10 min', 5_700, 1_140_000, 312, 60_000),
  Check.new('regressed, 10 min', 5_700, 1_140_000, 480, 60_000),
  Check.new('regressed, 30 s', 285, 57_000, 24, 3_000),
  Check.new('broken, 30 s', 285, 57_000, 750, 3_000)
].freeze

CHECKS.each do |check|
  puts format('%<name>s: baseline %<base>.2f%%, canary %<canary>.2f%%, z %<z>.1f -> %<decision>s',
              name: check.name, base: 100 * check.base_rate, canary: 100 * check.canary_rate,
              z: z_score(check), decision: decide(check))
end

In Ruby: Data.define makes an immutable value type, and fdiv divides two integers as floats; format with named references keeps the line readable.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

import kotlin.math.roundToLong
import kotlin.math.sqrt

const val Z_LIMIT = 3.0
const val MIN_REQUESTS = 10_000
const val CEILING = 0.02

data class Check(
    val name: String,
    val baseErrors: Int,
    val baseTotal: Int,
    val canaryErrors: Int,
    val canaryTotal: Int,
)

infix fun Int.per(total: Int) = toDouble() / total

fun zScore(c: Check): Double {
    // Two-proportion z statistic with the pooled error rate.
    val pooled = (c.baseErrors + c.canaryErrors) per (c.baseTotal + c.canaryTotal)
    if (pooled == 0.0 || pooled == 1.0) return 0.0
    val spread = 1.0 / c.baseTotal + 1.0 / c.canaryTotal
    val gap = (c.canaryErrors per c.canaryTotal) - (c.baseErrors per c.baseTotal)
    return gap / sqrt(pooled * (1 - pooled) * spread)
}

fun decide(c: Check): String =
    when {
        c.canaryErrors per c.canaryTotal > CEILING -> "roll back: over the ceiling"
        zScore(c) >= Z_LIMIT -> "roll back: worse than baseline"
        c.canaryTotal < MIN_REQUESTS -> "wait: too few requests"
        else -> "promote"
    }

// This number rounded half up to the given decimals (String.format exists only on the JVM).
fun Double.fixed(digits: Int): String {
    var scale = 1L
    repeat(digits) { scale *= 10 }
    val units = (this * scale).roundToLong()
    return "${units / scale}." + (units % scale).toString().padStart(digits, '0')
}

fun main() {
    val checks =
        listOf(
            Check("healthy, 10 min", 5_700, 1_140_000, 312, 60_000),
            Check("regressed, 10 min", 5_700, 1_140_000, 480, 60_000),
            Check("regressed, 30 s", 285, 57_000, 24, 3_000),
            Check("broken, 30 s", 285, 57_000, 750, 3_000),
        )

    for (c in checks) {
        val base = (100 * (c.baseErrors per c.baseTotal)).fixed(2)
        val canary = (100 * (c.canaryErrors per c.canaryTotal)).fixed(2)
        val z = zScore(c).fixed(1)
        println("${c.name}: baseline $base%, canary $canary%, z $z -> ${decide(c)}")
    }
}

In Kotlin: String.format exists only on the JVM, so the extension fixed(digits) rounds with roundToLong; infix fun per reads as a rate: errors per total.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

import 'dart:math';

const zLimit = 3.0;
const minRequests = 10_000;
const ceiling = 0.02;

typedef Check = (String, int, int, int, int);

double rate(int errors, int total) => errors / total;

double zScore(Check c) {
  final (_, baseErrors, baseTotal, canaryErrors, canaryTotal) = c;
  // Two-proportion z statistic with the pooled error rate.
  final pooled = rate(baseErrors + canaryErrors, baseTotal + canaryTotal);
  if (pooled == 0 || pooled == 1) return 0;
  final spread = 1 / baseTotal + 1 / canaryTotal;
  final gap = rate(canaryErrors, canaryTotal) - rate(baseErrors, baseTotal);
  return gap / sqrt(pooled * (1 - pooled) * spread);
}

String decide(Check c) => switch (c) {
  (_, _, _, final errors, final total) when rate(errors, total) > ceiling =>
    'roll back: over the ceiling',
  _ when zScore(c) >= zLimit => 'roll back: worse than baseline',
  (_, _, _, _, final total) when total < minRequests =>
    'wait: too few requests',
  _ => 'promote',
};

void main() {
  const List<Check> checks = [
    ('healthy, 10 min', 5_700, 1_140_000, 312, 60_000),
    ('regressed, 10 min', 5_700, 1_140_000, 480, 60_000),
    ('regressed, 30 s', 285, 57_000, 24, 3_000),
    ('broken, 30 s', 285, 57_000, 750, 3_000),
  ];

  for (final c in checks) {
    final (name, baseErrors, baseTotal, canaryErrors, canaryTotal) = c;
    final base = (100 * rate(baseErrors, baseTotal)).toStringAsFixed(2);
    final canary = (100 * rate(canaryErrors, canaryTotal)).toStringAsFixed(2);
    final z = zScore(c).toStringAsFixed(1);
    print('$name: baseline $base%, canary $canary%, z $z -> ${decide(c)}');
  }
}

In Dart: int / int is always a double in Dart; ~/ would be integer division. toStringAsFixed rounds to the given decimals.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

healthy, 10 min: baseline 0.50%, canary 0.52%, z 0.7 -> promote
regressed, 10 min: baseline 0.50%, canary 0.80%, z 10.0 -> roll back: worse than baseline
regressed, 30 s: baseline 0.50%, canary 0.80%, z 2.2 -> wait: too few requests
broken, 30 s: baseline 0.50%, canary 25.00%, z 100.5 -> roll back: over the ceiling

Compare the two “regressed” lines. The same 0.80% against 0.50% gives z = 10.0 after 10 minutes, but only 2.2 after 30 seconds, when the canary has served 3,000 requests and 24 errors: that difference could still be chance, so the answer is to wait, not to promote.

How strict is a limit of 3? On a healthy canary, z behaves like a value drawn from a standard normal curve, so the chance that one look shows 3 or more by chance alone is the area above 3. The figure starts there; drag From (a) down to 2 and watch the area grow:

Interactive · change it and see How often chance alone gives a z this large Set the mean and the standard deviation, then the two ends of the range. The shaded area is the probability that a value falls between them.
The bell curve with the range shaded: density against x.−4−202400.10.20.30.40.5xdensitydensityμ

For a normal distribution with mean 0 and standard deviation 1, the probability of a value between 3 and 10 is 0.0013 (0.1 %), from z = 3.00 to z = 10.00.

P(3 ≤ X ≤ 10) 0.0013
z-score of a 3.00
z-score of b 10.00
The numbers as a table
Probability within k standard deviations of the mean
RangeProbability
μ ± 1σ0.6827
μ ± 2σ0.9545
μ ± 3σ0.9973

Above 3 the area is 0.0013, about one look in 740. Above 2 it is 0.0228, about one look in 44, and a check that looks every minute takes that chance sixty times an hour. How long, then, must a canary run? The next program finds the canary requests at which this rule catches a doubled error rate nine times in ten, and turns them into minutes at three traffic levels.

How long a 5% canary must run Python · bake/canary_bake.py
"""How long must a canary run before the canary check above can see a real regression?

For a canary on 5% of traffic whose error rate is twice the baseline's, find the canary requests at which
the z >= 3 rule catches it 9 times in 10 (normal approximation), then the minutes that takes at three
traffic levels.
"""
from math import sqrt
from statistics import NormalDist

Z_LIMIT = 3.0
SHARE = 0.05          # the canary's share of traffic
POWER = 0.90          # the chance of catching the regression


def chance_to_catch(p_base, p_canary, canary_n):
    base_n = canary_n * (1 - SHARE) / SHARE
    pooled = (1 - SHARE) * p_base + SHARE * p_canary
    se_no_change = sqrt(pooled * (1 - pooled) * (1 / canary_n + 1 / base_n))
    se_change = sqrt(p_canary * (1 - p_canary) / canary_n + p_base * (1 - p_base) / base_n)
    return 1 - NormalDist().cdf((Z_LIMIT * se_no_change - (p_canary - p_base)) / se_change)


def requests_needed(p_base, p_canary):
    low, high = 1, 1
    while chance_to_catch(p_base, p_canary, high) < POWER:
        low, high = high, high * 2
    while low < high:                      # the smallest count that reaches POWER
        mid = (low + high) // 2
        if chance_to_catch(p_base, p_canary, mid) >= POWER:
            high = mid
        else:
            low = mid + 1
    return high


def duration(seconds):
    return f"{seconds / 60:.1f} min" if seconds >= 60 else f"{seconds:.0f} s"


print(f"Canary on {SHARE:.0%} of traffic, error rate doubled, caught {POWER:.0%} of the time at z >= {Z_LIMIT:g}")
print(f"{'baseline errors':<16} {'canary requests':>15} {'at 200/s':>10} {'at 2,000/s':>10} {'at 20,000/s':>11}")
for p_base in (0.001, 0.005, 0.02):
    n = requests_needed(p_base, 2 * p_base)
    times = [duration(n / (rps * SHARE)) for rps in (200, 2_000, 20_000)]
    print(f"{p_base:<16.1%} {n:>15,} {times[0]:>10} {times[1]:>10} {times[2]:>11}")

Output

Canary on 5% of traffic, error rate doubled, caught 90% of the time at z >= 3
baseline errors  canary requests   at 200/s at 2,000/s at 20,000/s
0.1%                      24,866   41.4 min    4.1 min        25 s
0.5%                       4,946    8.2 min       49 s         5 s
2.0%                       1,211    2.0 min       12 s         1 s

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 canary_bake.py

Rare errors need many requests: at a 0.1% baseline the canary needs about 25,000, which takes 25 seconds on a service with 20,000 requests a second and 41 minutes on one with 200. So size the bake by requests as well as by the clock. The hands-off pipelines of the Amazon Builders’ Library do both, waiting a minimum time (at least an hour after each single-instance stage) and a minimum amount of traffic before promoting (automating safe, hands-off deployments).

A/B Test Significance Calculator Enter the baseline's and the canary's requests as visitors and their errors as conversions: it runs the same two-proportion test.

Key idea

Judge a canary against the old version in the same minutes, with a strict limit on z, a minimum number of requests and an absolute ceiling, and size the bake by requests as well as by the clock.

Checkpoint

Check: Judging a canary

  1. Question 1 of 2 Why compare a canary with the old version serving traffic during the same minutes, rather than with the service's error rate before the deploy?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Because traffic, time of day and dependencies change over time, and both groups see the same changes

    A comparison with the past mixes the release's effect with everything else that changed since: the time of day, the traffic mix, a slow dependency. A baseline running at the same time sees those changes too, so a difference between the two groups points at the release.

  2. Question 2 of 2 After 30 seconds a canary has served 3,000 requests with 24 errors (0.80%), against 0.50% on the baseline, and z = 2.2. What does the lesson's rule decide?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Wait, because z is below 3 and the canary has served fewer than 10,000 requests

    The program's third line is exactly this case: wait, too few requests. After 10 minutes the same 0.80% against 0.50% gives z = 10.0, and the rule rolls back.

A rollback is safe only if the old version reads the new data

Rolling back is the quickest repair for a bad release: put back the last version that worked, then investigate. It needs three things. The old build must still be deployable: Kubernetes keeps 10 old revisions by default, and a Deployment whose revisionHistoryLimit is 0 cannot be rolled back at all. Nothing irreversible may have happened, such as a dropped column. And the old version must read everything the new one wrote. An article in the Amazon Builders’ Library names a change of protocol as the most common reason a rollback is impossible (ensuring rollback safety): a release that changes a stored format or a message looks fine until you try to leave it. The program below shows it with shopping carts: version 1 stores a cart as a list of product IDs, the new version stores lines with quantities and reads both formats.

Carts that a rollback cannot read Python · carts/two_phase.py
"""Why a rollback can fail: shopping carts saved by one version and read by another.

The old format stores a cart as a list of product IDs; the new one stores each line with a quantity.
"""
import json


def write_old(cart):
    return json.dumps({"items": [pid for pid, qty in cart for _ in range(qty)]})


def write_new(cart):
    return json.dumps({"items": [{"id": pid, "qty": qty} for pid, qty in cart]})


def read_old_only(raw):
    """v1's reader: every item must be a product ID."""
    return ", ".join(json.loads(raw)["items"])


def read_both(raw):
    """The reader of the prepare and activate versions: understands both formats."""
    lines = {}
    for item in json.loads(raw)["items"]:
        pid, qty = (item, 1) if isinstance(item, str) else (item["id"], item["qty"])
        lines[pid] = lines.get(pid, 0) + qty
    return ", ".join(f"{pid} x{qty}" for pid, qty in lines.items())


VERSIONS = {  # name: (reader, writer)
    "v1": (read_old_only, write_old),
    "v1.5 (prepare)": (read_both, write_old),
    "v2 (activate)": (read_both, write_new),
    "v2 (one step)": (read_both, write_new),
}


def run(plan, rollback_to):
    """Each version in the plan saves its carts; then the fleet rolls back and reads every cart again."""
    stored = []
    for name, carts in plan:
        writer = VERSIONS[name][1]
        stored += [writer([(f"p{n % 7}", 1 + n % 3), ("p9", 1)]) for n in range(carts)]
    reader = VERSIONS[rollback_to][0]
    failures, first_error = 0, None
    for raw in stored:
        try:
            reader(raw)
        except TypeError as error:
            failures += 1
            first_error = first_error or error
    print(" -> ".join(name for name, _ in plan) + f", then roll back to {rollback_to}")
    print(f"  {failures:,} of {len(stored):,} carts cannot be read" + (f": TypeError: {first_error}" if first_error else ""))


run([("v1", 600), ("v2 (one step)", 400)], rollback_to="v1")
run([("v1", 600), ("v1.5 (prepare)", 200), ("v2 (activate)", 200)], rollback_to="v1.5 (prepare)")
run([("v1", 600), ("v1.5 (prepare)", 200), ("v2 (activate)", 200)], rollback_to="v1")

Output

v1 -> v2 (one step), then roll back to v1
  400 of 1,000 carts cannot be read: TypeError: sequence item 0: expected str instance, dict found
v1 -> v1.5 (prepare) -> v2 (activate), then roll back to v1.5 (prepare)
  0 of 1,000 carts cannot be read
v1 -> v1.5 (prepare) -> v2 (activate), then roll back to v1
  200 of 1,000 carts cannot be read: TypeError: sequence item 0: expected str instance, dict found

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 two_phase.py

In the one-step plan the rollback makes 400 carts unreadable, every cart the new version saved: the repair has become a second outage. The same article’s fix is a two-phase deployment: A change of a stored format shipped as two releases: first a version that reads both formats but still writes the old one, then one that writes the new format, so each step can be rolled back.. The prepare version reads both formats but keeps writing the old one, so rolling it back is harmless. Only when every server runs it does the activate version start writing the new format, and rolling that back is safe too, because the version you return to reads both. The third run shows the limit: two steps back at once fails on the 200 new carts, so each phase bakes before the next starts, and the old-format reader is removed only after every stored record has been rewritten. Step through both plans, with the carts the store holds after each step:

Interactive · step by step Carts saved by one version and read by another Step through the one-step plan and its rollback, then the two-phase plan and its two rollbacks. The store's label counts the carts in each format.
Carts saved by one version and read by another, step 7 of 7. Showing Servers (v1 everywhere), Cart store (800 old, 200 new).Serversv1 everywhereCart store800 old, 200 new200 of 1,000 fail

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Before the release. Every server runs v1, which stores a cart as a list of product IDs and reads only that format. The store holds 600 carts.
  2. One step to v2. The one-step plan deploys v2, which reads both formats but writes the new one, lines with quantities. It saves 400 carts in the new format.
  3. Roll back to v1. Errors rise and the fleet goes back to v1. It reads all 1,000 carts again and fails on the 400 that v2 saved, so the repair has become a second outage.
  4. Prepare first. Start again from the 600 old carts. v1.5 reads both formats but still writes the old one, and it goes to every server first. It saves 200 carts, all in the old format.
  5. Then activate. Only once every server runs v1.5 does v2 start writing the new format. It saves 200 carts in the new format.
  6. One step back is safe. Rolled back to v1.5, the fleet reads all 1,000 carts, because the version it returns to reads both formats.
  7. Two steps back is not. Straight back to v1, the 200 new carts fail again. So each phase bakes before the next, and the old reader goes only after every cart is rewritten.

The diagram puts the four versions in order, with the rollbacks that are safe:

Four versions of a two-phase deployment in order, with the rollbacks that are safe one step back and the one that is not.v1reads the old formatwrites the old formatv1.5, preparereads both formatswrites the old formatv2, activatereads both formatswrites the new formatv3, after the backfillreads and writesthe new format onlydeploy everywhere,check every serverafter a bakeafter every recordis rewrittensafe rollbacksafe rollbackunsafe: v1 cannotread new records

A two-phase deployment of a new stored format

Text description of the diagram

Four boxes from top to bottom, joined by arrows in the order the versions ship:

1. v1 reads and writes the old format. 2. v1.5, the prepare step, reads both formats and still writes the old one. The arrow to it says "deploy everywhere, check every server". 3. v2, the activate step, reads both formats and writes the new one. The arrow to it says "after a bake". 4. v3 reads and writes only the new format. The arrow to it says "after every record is rewritten".

Arrows labelled "safe rollback" lead back one step, from v2 to v1.5 and from v1.5 to v1. A dashed arrow from v2 straight back to v1 is labelled "unsafe: v1 cannot read new records".

Check that the prepare version reached every server, not a percentage of healthy ones: one server still running the old reader when the new format arrives is exactly the failure the phases exist to avoid. And test the way back before production: the article describes upgrade-downgrade testing, which deploys to about half of a production-like fleet, then all of it, then rolls back, each stage long enough for every API and batch job to run once. Schema changes need the same care: expand-and-contract migrations, the subject of the next lesson in this module, apply it to databases.

Make the rollback automatic. A person who must notice a graph, decide and act needs minutes; an alarm on the new version’s errors and latency that rolls back by itself needs seconds. The Builders’ Library pipelines deploy to a single instance first, then to waves of growing size, and roll back on alarms throughout each bake, so the rollback is often under way by the time the on-call engineer has been paged. Argo Rollouts aborts a canary whose analysis fails; a plain Kubernetes Deployment only reports that it is stuck.

Key idea

Readers before writers: ship a version that reads both formats to every server, then the one that writes the new format, and go back one step at a time.

Checkpoint

Check: Rollbacks that are safe

  1. Question 1 of 2 Which of these make rolling back to the previous version unsafe? Choose every one that does.

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • The release ran a migration that dropped a column the previous version reads
    • The new version writes records in a format the previous version cannot parse

    A rollback is safe when the version you return to can work with everything the new one left behind. New formats it cannot read and columns it needs that are gone both break it. A kept build is what makes a rollback possible, and code behind a flag that was never turned on has not written anything new.

  2. Question 2 of 2 In the two-phase plan, v2 (activate) has saved 200 carts in the new format and errors rise. Which rollback is safe?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Back to v1.5, which reads both formats

    The program's second run rolls back to v1.5 and every one of the 1,000 carts is read. Going two steps back at once fails on the 200 new carts, so each phase bakes before the next starts.

Feature flags: deploying is not releasing

Deploying puts a new version of the code on the servers; releasing lets users use a new behaviour. A feature flag separates them: the new code ships switched off, and the release is a change of configuration that the code reads at run time, which can be undone in seconds without a deploy. Pete Hodgson’s article on martinfowler.com sorts flags by how long they live and how quickly their answer must change (feature toggles):

  • Release toggles hide unfinished or unreleased features and should be gone within a week or two.
  • Experiment toggles split users between variants until an A/B test has a significant result.
  • Ops toggles let operators turn costly features off under load; a few stay for good as kill switches.
  • Permissioning toggles open features to some users only, and can live for years.

A percentage rollout needs every server to give a user the same answer without storing who is in it. Hash the flag’s key with the user’s ID, keep the remainder after dividing by 10,000, and switch the feature on for buckets below the percentage times 100. Step through three evaluations of one flag, with the buckets the program below computes:

Interactive · message by message One flag, three users and an outage of the flag service Step through the evaluations of new-checkout. The client computes every answer itself from the rule it was sent.
One flag, three users and an outage of the flag service, step 6 of 6. Messages so far: Flag service to Flag client: new-checkout: 10 %; App server to Flag client: user-42, default false; Flag client to App server: false; Flag client to App server: true; Flag service to Flag client: new-checkout: 25 %; Flag client to App server: false, the default.App serverFlag clientin the appFlag servicenew-checkout: 10 %user-42, default falsefalsetruenew-checkout: 25 %false, the default

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The rule arrives. The flag service sends the client the rule for new-checkout, on for 10 % of users. The client keeps it and answers every request itself, with no call to the service per request.
  2. A request for user-42. The app asks for new-checkout for user-42 and passes the default false, which means the old checkout.
  3. Hash, then compare. The client hashes new-checkout:user-42 to bucket 9,926. On means a bucket below 10 × 100 = 1,000, so user-42 gets the old checkout.
  4. user-12785 is in. The same hash puts user-12785 in bucket 999, the last bucket below 1,000, so the answer is true, on every server that hashes the same text.
  5. Raised to 25 %. The rule changes to 25 %, buckets below 2,500. user-12785 keeps the feature and user-42, at 9,926, still does not get it, so raising the share only adds users.
  6. Evaluation fails. When evaluation fails, for example because no rule could be fetched, an OpenFeature client returns the default the code passed in instead of throwing. That is why the default should be the old, safe path.

flagd, an open-source engine that follows the OpenFeature specification, splits users between variants by hashing the user’s key with the flag key (MurmurHash3), and calls the assignment sticky (flagd). The example uses FNV-1a, a hash that fits in a few lines (RFC 9923), and checks what a rollout needs, in 14 languages that all printed the same lines:

One program · 14 languages A percentage rollout from a hash, on 50,000 users

Python 3.14 · main.py

def fnv1a32(text: str) -> int:
    # FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    hash_ = 0x811C9DC5
    for byte in text.encode():
        hash_ ^= byte
        hash_ = (hash_ * 0x01000193) & 0xFFFFFFFF
    return hash_


def is_on(flags: dict[str, int], flag: str, user: str) -> bool:
    percent = flags.get(flag)
    if percent is None:
        return False  # an unknown flag gets the safe default: off
    # The bucket, 0 to 9,999, is the user's place in line for this flag.
    return fnv1a32(f"{flag}:{user}") % 10_000 < percent * 100


def yes_no(ok: bool) -> str:
    return "yes" if ok else "no"


users = [f"user-{i}" for i in range(50_000)]
flags = {"new-checkout": 10, "dark-mode": 10}
at_10 = [u for u in users if is_on(flags, "new-checkout", u)]
print(f"new-checkout at 10%: {len(at_10)} of {len(users)} users")
again = all(is_on(flags, "new-checkout", u) for u in at_10)
print(f"the same users on a second call: {yes_no(again)}")

flags["new-checkout"] = 25
at_25 = sum(is_on(flags, "new-checkout", u) for u in users)
kept = all(is_on(flags, "new-checkout", u) for u in at_10)
print(f"raised to 25%: {at_25} users; all {len(at_10)} kept: {yes_no(kept)}")

both = sum(is_on(flags, "dark-mode", u) for u in at_10)
print(f"also on for dark-mode at 10%: {both} of them, about one in ten")
unknown = is_on(flags, "no-such-flag", "user-1")
print(f"an unknown flag: {'on' if unknown else 'off'}")

In Python: Python's int never overflows, so & 0xFFFFFFFF keeps the low 32 bits after every multiply, which is FNV's arithmetic modulo 2³².

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

function fnv1a32(text) {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  let hash = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    hash ^= text.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193) >>> 0;
  }
  return hash;
}

function isOn(flags, flag, user) {
  const percent = flags.get(flag);
  if (percent === undefined) {
    return false; // an unknown flag gets the safe default: off
  }
  // The bucket, 0 to 9,999, is the user's place in line for this flag.
  return fnv1a32(`${flag}:${user}`) % 10_000 < percent * 100;
}

const yesNo = (ok) => (ok ? "yes" : "no");

const users = Array.from({ length: 50_000 }, (_, i) => `user-${i}`);
const flags = new Map([
  ["new-checkout", 10],
  ["dark-mode", 10],
]);
const at10 = users.filter((u) => isOn(flags, "new-checkout", u));
console.log(`new-checkout at 10%: ${at10.length} of ${users.length} users`);
const again = at10.every((u) => isOn(flags, "new-checkout", u));
console.log(`the same users on a second call: ${yesNo(again)}`);

flags.set("new-checkout", 25);
const at25 = users.filter((u) => isOn(flags, "new-checkout", u)).length;
const kept = at10.every((u) => isOn(flags, "new-checkout", u));
console.log(`raised to 25%: ${at25} users; all ${at10.length} kept: ${yesNo(kept)}`);

const both = at10.filter((u) => isOn(flags, "dark-mode", u)).length;
console.log(`also on for dark-mode at 10%: ${both} of them, about one in ten`);
const unknown = isOn(flags, "no-such-flag", "user-1");
console.log(`an unknown flag: ${unknown ? "on" : "off"}`);

In JavaScript: Math.imul multiplies as 32-bit integers and >>> 0 reads the result as unsigned; a plain * on doubles would lose the low bits.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.IntStream;

public class Main {
  static int fnv1a32(String text) {
    // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    int hash = 0x811c9dc5;
    for (int i = 0; i < text.length(); i++) {
      hash ^= text.charAt(i);
      hash *= 0x01000193;
    }
    return hash;
  }

  static boolean isOn(Map<String, Integer> flags, String flag, String user) {
    Integer percent = flags.get(flag);
    if (percent == null) {
      return false; // an unknown flag gets the safe default: off
    }
    // The bucket, 0 to 9,999, is the user's place in line for this flag.
    return Integer.toUnsignedLong(fnv1a32(flag + ":" + user)) % 10_000 < percent * 100;
  }

  static String yesNo(boolean ok) {
    return ok ? "yes" : "no";
  }

  public static void main(String[] args) {
    List<String> users = IntStream.range(0, 50_000).mapToObj(i -> "user-" + i).toList();
    Map<String, Integer> flags = new TreeMap<>(Map.of("new-checkout", 10, "dark-mode", 10));
    List<String> at10 = users.stream().filter(u -> isOn(flags, "new-checkout", u)).toList();
    System.out.println("new-checkout at 10%: " + at10.size() + " of " + users.size() + " users");
    boolean again = at10.stream().allMatch(u -> isOn(flags, "new-checkout", u));
    System.out.println("the same users on a second call: " + yesNo(again));

    flags.put("new-checkout", 25);
    long at25 = users.stream().filter(u -> isOn(flags, "new-checkout", u)).count();
    boolean kept = at10.stream().allMatch(u -> isOn(flags, "new-checkout", u));
    System.out.println(
        "raised to 25%: " + at25 + " users; all " + at10.size() + " kept: " + yesNo(kept));

    long both = at10.stream().filter(u -> isOn(flags, "dark-mode", u)).count();
    System.out.println("also on for dark-mode at 10%: " + both + " of them, about one in ten");
    boolean unknown = isOn(flags, "no-such-flag", "user-1");
    System.out.println("an unknown flag: " + (unknown ? "on" : "off"));
  }
}

In Java: int arithmetic wraps at 32 bits, which is exactly FNV's modulo 2³²; Integer.toUnsignedLong reads the hash as unsigned before the remainder, which would otherwise be negative.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <map>
#include <print>
#include <string>
#include <string_view>
#include <vector>

using Flags = std::map<std::string, int, std::less<>>;

std::uint32_t fnv1a32(std::string_view text) {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  std::uint32_t hash = 0x811c9dc5u;
  for (const unsigned char byte : text) {
    hash ^= byte;
    hash *= 0x01000193u;
  }
  return hash;
}

bool is_on(const Flags &flags, std::string_view flag, const std::string &user) {
  const auto found = flags.find(flag);
  if (found == flags.end()) {
    return false; // an unknown flag gets the safe default: off
  }
  // The bucket, 0 to 9,999, is the user's place in line for this flag.
  const auto bucket = fnv1a32(std::string(flag) + ":" + user) % 10'000u;
  return bucket < static_cast<std::uint32_t>(found->second * 100);
}

const char *yes_no(bool ok) { return ok ? "yes" : "no"; }

int main() {
  std::vector<std::string> users;
  for (int i = 0; i < 50'000; i++) {
    users.push_back("user-" + std::to_string(i));
  }
  Flags flags{{"new-checkout", 10}, {"dark-mode", 10}};
  const auto checkout = [&flags](const std::string &u) {
    return is_on(flags, "new-checkout", u);
  };
  std::vector<std::string> at10;
  std::ranges::copy_if(users, std::back_inserter(at10), checkout);
  std::println("new-checkout at 10%: {} of {} users", at10.size(),
               users.size());
  const bool again = std::ranges::all_of(at10, checkout);
  std::println("the same users on a second call: {}", yes_no(again));

  flags["new-checkout"] = 25;
  const auto at25 = std::ranges::count_if(users, checkout);
  const bool kept = std::ranges::all_of(at10, checkout);
  std::println("raised to 25%: {} users; all {} kept: {}", at25, at10.size(),
               yes_no(kept));

  const auto both = std::ranges::count_if(at10, [&flags](const std::string &u) {
    return is_on(flags, "dark-mode", u);
  });
  std::println("also on for dark-mode at 10%: {} of them, about one in ten",
               both);
  const bool unknown = is_on(flags, "no-such-flag", "user-1");
  std::println("an unknown flag: {}", unknown ? "on" : "off");
}

In C++: Unsigned arithmetic on std::uint32_t wraps by definition; the transparent std::less<> lets the map find a std::string_view key without building a std::string.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

var users = Enumerable.Range(0, 50_000).Select(i => $"user-{i}").ToList();
var flags = new Dictionary<string, int> { ["new-checkout"] = 10, ["dark-mode"] = 10 };
var at10 = users.Where(u => IsOn(flags, "new-checkout", u)).ToList();
Console.WriteLine($"new-checkout at 10%: {at10.Count} of {users.Count} users");
var again = at10.All(u => IsOn(flags, "new-checkout", u));
Console.WriteLine($"the same users on a second call: {YesNo(again)}");

flags["new-checkout"] = 25;
var at25 = users.Count(u => IsOn(flags, "new-checkout", u));
var kept = at10.All(u => IsOn(flags, "new-checkout", u));
Console.WriteLine($"raised to 25%: {at25} users; all {at10.Count} kept: {YesNo(kept)}");

var both = at10.Count(u => IsOn(flags, "dark-mode", u));
Console.WriteLine($"also on for dark-mode at 10%: {both} of them, about one in ten");
var unknown = IsOn(flags, "no-such-flag", "user-1");
Console.WriteLine($"an unknown flag: {(unknown ? "on" : "off")}");

static uint Fnv1a32(string text)
{
    // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    uint hash = 0x811c9dc5;
    foreach (var c in text)
    {
        hash ^= c;
        hash *= 0x01000193;
    }
    return hash;
}

static bool IsOn(Dictionary<string, int> flags, string flag, string user)
{
    if (!flags.TryGetValue(flag, out var percent))
    {
        return false; // an unknown flag gets the safe default: off
    }
    // The bucket, 0 to 9,999, is the user's place in line for this flag.
    return Fnv1a32($"{flag}:{user}") % 10_000 < percent * 100;
}

static string YesNo(bool ok) => ok ? "yes" : "no";

In C#: uint multiplication wraps unless it runs inside checked(…), and a char converts to uint without a cast, so the loop reads the text's characters directly.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

enum { USERS = 50000 };

typedef struct {
  const char *key;
  int percent;
} Flag;

static uint32_t fnv1a32(const char *text) {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  uint32_t hash = 0x811c9dc5u;
  for (const unsigned char *p = (const unsigned char *)text; *p != '\0'; p++) {
    hash ^= *p;
    hash *= 0x01000193u;
  }
  return hash;
}

static bool is_on(const Flag *flags, size_t count, const char *flag, int user) {
  for (size_t i = 0; i < count; i++) {
    if (strcmp(flags[i].key, flag) == 0) {
      // The bucket, 0 to 9,999, is the user's place in line for this flag.
      char text[64];
      snprintf(text, sizeof text, "%s:user-%d", flag, user);
      return fnv1a32(text) % 10000u < (uint32_t)(flags[i].percent * 100);
    }
  }
  return false; // an unknown flag gets the safe default: off
}

static const char *yes_no(bool ok) { return ok ? "yes" : "no"; }

int main(void) {
  Flag flags[] = {{"new-checkout", 10}, {"dark-mode", 10}};
  const size_t n = sizeof flags / sizeof flags[0];
  static bool had[USERS];
  int at10 = 0;
  for (int u = 0; u < USERS; u++) {
    had[u] = is_on(flags, n, "new-checkout", u);
    at10 += had[u];
  }
  printf("new-checkout at 10%%: %d of %d users\n", at10, USERS);
  bool again = true;
  for (int u = 0; u < USERS; u++) {
    again = again && (!had[u] || is_on(flags, n, "new-checkout", u));
  }
  printf("the same users on a second call: %s\n", yes_no(again));

  flags[0].percent = 25;
  int at25 = 0;
  bool kept = true;
  for (int u = 0; u < USERS; u++) {
    const bool on = is_on(flags, n, "new-checkout", u);
    at25 += on;
    kept = kept && (!had[u] || on);
  }
  printf("raised to 25%%: %d users; all %d kept: %s\n", at25, at10,
         yes_no(kept));

  int both = 0;
  for (int u = 0; u < USERS; u++) {
    both += had[u] && is_on(flags, n, "dark-mode", u);
  }
  printf("also on for dark-mode at 10%%: %d of them, about one in ten\n", both);
  const bool unknown = is_on(flags, n, "no-such-flag", 1);
  printf("an unknown flag: %s\n", unknown ? "on" : "off");
  return 0;
}

In C: uint32_t arithmetic wraps by definition, so the multiply needs no mask; a user is a number here, and snprintf writes the text user-<n> that the hash reads.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

function fnv1a32(string $text): int
{
    // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    $hash = 0x811C9DC5;
    foreach (str_split($text) as $char) {
        $hash ^= ord($char);
        $hash = ($hash * 0x01000193) & 0xFFFFFFFF;
    }
    return $hash;
}

/** @param array<string, int> $flags */
function isOn(array $flags, string $flag, string $user): bool
{
    if (!isset($flags[$flag])) {
        return false; // an unknown flag gets the safe default: off
    }
    // The bucket, 0 to 9,999, is the user's place in line for this flag.
    return fnv1a32("$flag:$user") % 10_000 < $flags[$flag] * 100;
}

/**
 * @param array<string, int> $flags
 * @param list<string> $users
 * @return list<string>
 */
function usersWith(array $flags, string $flag, array $users): array
{
    return array_values(array_filter($users, fn(string $u): bool => isOn($flags, $flag, $u)));
}

function yesNo(bool $ok): string
{
    return $ok ? 'yes' : 'no';
}

$users = array_map(fn(int $i): string => "user-$i", range(0, 49_999));
$flags = ['new-checkout' => 10, 'dark-mode' => 10];
$at10 = usersWith($flags, 'new-checkout', $users);
printf("new-checkout at 10%%: %d of %d users\n", count($at10), count($users));
$again = usersWith($flags, 'new-checkout', $at10) === $at10;
echo 'the same users on a second call: ', yesNo($again), "\n";

$flags['new-checkout'] = 25;
$at25 = count(usersWith($flags, 'new-checkout', $users));
$kept = usersWith($flags, 'new-checkout', $at10) === $at10;
printf("raised to 25%%: %d users; all %d kept: %s\n", $at25, count($at10), yesNo($kept));

$both = count(usersWith($flags, 'dark-mode', $at10));
printf("also on for dark-mode at 10%%: %d of them, about one in ten\n", $both);
$unknown = isOn($flags, 'no-such-flag', 'user-1');
echo 'an unknown flag: ', $unknown ? 'on' : 'off', "\n";

In PHP: PHP's 64-bit int holds the product before & 0xFFFFFFFF; the browser's 32-bit build turns it into a float, so this tab shows its record.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. To run it yourself: php main.php

Rust 1.99 · main.rs

use std::collections::BTreeMap;

fn fnv1a32(text: &str) -> u32 {
    // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    text.bytes().fold(0x811c_9dc5, |hash, byte| {
        (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
    })
}

fn is_on(flags: &BTreeMap<&str, u32>, flag: &str, user: &str) -> bool {
    match flags.get(flag) {
        None => false, // an unknown flag gets the safe default: off
        // The bucket, 0 to 9,999, is the user's place in line for this flag.
        Some(percent) => fnv1a32(&format!("{flag}:{user}")) % 10_000 < percent * 100,
    }
}

fn yes_no(ok: bool) -> &'static str {
    if ok { "yes" } else { "no" }
}

fn main() {
    let users: Vec<String> = (0..50_000).map(|i| format!("user-{i}")).collect();
    let mut flags = BTreeMap::from([("new-checkout", 10), ("dark-mode", 10)]);
    let at_10: Vec<&String> = users
        .iter()
        .filter(|u| is_on(&flags, "new-checkout", u))
        .collect();
    println!(
        "new-checkout at 10%: {} of {} users",
        at_10.len(),
        users.len()
    );
    let again = at_10.iter().all(|u| is_on(&flags, "new-checkout", u));
    println!("the same users on a second call: {}", yes_no(again));

    flags.insert("new-checkout", 25);
    let at_25 = users
        .iter()
        .filter(|u| is_on(&flags, "new-checkout", u))
        .count();
    let kept = at_10.iter().all(|u| is_on(&flags, "new-checkout", u));
    println!(
        "raised to 25%: {at_25} users; all {} kept: {}",
        at_10.len(),
        yes_no(kept)
    );

    let both = at_10
        .iter()
        .filter(|u| is_on(&flags, "dark-mode", u))
        .count();
    println!("also on for dark-mode at 10%: {both} of them, about one in ten");
    let unknown = is_on(&flags, "no-such-flag", "user-1");
    println!("an unknown flag: {}", if unknown { "on" } else { "off" });
}

In Rust: wrapping_mul makes the wrap explicit (a plain * stops a debug build on overflow), and fold walks the bytes in one expression.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

function fnv1a32(text: string): number {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  let hash = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    hash ^= text.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193) >>> 0;
  }
  return hash;
}

function isOn(flags: Map<string, number>, flag: string, user: string): boolean {
  const percent = flags.get(flag);
  if (percent === undefined) {
    return false; // an unknown flag gets the safe default: off
  }
  // The bucket, 0 to 9,999, is the user's place in line for this flag.
  return fnv1a32(`${flag}:${user}`) % 10_000 < percent * 100;
}

const yesNo = (ok: boolean): string => (ok ? "yes" : "no");

const users: string[] = Array.from({ length: 50_000 }, (_, i) => `user-${i}`);
const flags = new Map<string, number>([
  ["new-checkout", 10],
  ["dark-mode", 10],
]);
const at10 = users.filter((u) => isOn(flags, "new-checkout", u));
console.log(`new-checkout at 10%: ${at10.length} of ${users.length} users`);
const again = at10.every((u) => isOn(flags, "new-checkout", u));
console.log(`the same users on a second call: ${yesNo(again)}`);

flags.set("new-checkout", 25);
const at25 = users.filter((u) => isOn(flags, "new-checkout", u)).length;
const kept = at10.every((u) => isOn(flags, "new-checkout", u));
console.log(`raised to 25%: ${at25} users; all ${at10.length} kept: ${yesNo(kept)}`);

const both = at10.filter((u) => isOn(flags, "dark-mode", u)).length;
console.log(`also on for dark-mode at 10%: ${both} of them, about one in ten`);
const unknown = isOn(flags, "no-such-flag", "user-1");
console.log(`an unknown flag: ${unknown ? "on" : "off"}`);

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import "fmt"

func fnv1a32(text string) uint32 {
	// FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
	hash := uint32(0x811c9dc5)
	for i := range len(text) {
		hash ^= uint32(text[i])
		hash *= 0x01000193
	}
	return hash
}

func isOn(flags map[string]int, flag, user string) bool {
	percent, ok := flags[flag]
	if !ok {
		return false // an unknown flag gets the safe default: off
	}
	// The bucket, 0 to 9,999, is the user's place in line for this flag.
	return int(fnv1a32(flag+":"+user)%10_000) < percent*100
}

func usersWith(flags map[string]int, flag string, users []string) []string {
	var out []string
	for _, u := range users {
		if isOn(flags, flag, u) {
			out = append(out, u)
		}
	}
	return out
}

func yesNo(ok bool) string {
	if ok {
		return "yes"
	}
	return "no"
}

func main() {
	users := make([]string, 50_000)
	for i := range users {
		users[i] = fmt.Sprintf("user-%d", i)
	}
	flags := map[string]int{"new-checkout": 10, "dark-mode": 10}
	at10 := usersWith(flags, "new-checkout", users)
	fmt.Printf("new-checkout at 10%%: %d of %d users\n", len(at10), len(users))
	again := len(usersWith(flags, "new-checkout", at10)) == len(at10)
	fmt.Println("the same users on a second call:", yesNo(again))

	flags["new-checkout"] = 25
	at25 := len(usersWith(flags, "new-checkout", users))
	kept := len(usersWith(flags, "new-checkout", at10)) == len(at10)
	fmt.Printf("raised to 25%%: %d users; all %d kept: %s\n", at25, len(at10), yesNo(kept))

	both := len(usersWith(flags, "dark-mode", at10))
	fmt.Printf("also on for dark-mode at 10%%: %d of them, about one in ten\n", both)
	unknown := "off"
	if isOn(flags, "no-such-flag", "user-1") {
		unknown = "on"
	}
	fmt.Println("an unknown flag:", unknown)
}

In Go: uint32 arithmetic wraps by definition, and a Go string is indexed by bytes, so text[i] is the byte FNV-1a reads; usersWith filters with a plain loop and append, the usual way in Go.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

func fnv1a32(_ text: String) -> UInt32 {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  var hash: UInt32 = 0x811c_9dc5
  for byte in text.utf8 {
    hash ^= UInt32(byte)
    hash = hash &* 0x0100_0193
  }
  return hash
}

func isOn(_ flag: String, for user: String, in flags: [String: Int]) -> Bool {
  guard let percent = flags[flag] else {
    return false  // an unknown flag gets the safe default: off
  }
  // The bucket, 0 to 9,999, is the user's place in line for this flag.
  return Int(fnv1a32("\(flag):\(user)") % 10_000) < percent * 100
}

func yesNo(_ ok: Bool) -> String { ok ? "yes" : "no" }

let users = (0..<50_000).map { "user-\($0)" }
var flags = ["new-checkout": 10, "dark-mode": 10]
let at10 = users.filter { isOn("new-checkout", for: $0, in: flags) }
print("new-checkout at 10%: \(at10.count) of \(users.count) users")
let again = at10.allSatisfy { isOn("new-checkout", for: $0, in: flags) }
print("the same users on a second call: \(yesNo(again))")

flags["new-checkout"] = 25
let at25 = users.filter { isOn("new-checkout", for: $0, in: flags) }.count
let kept = at10.allSatisfy { isOn("new-checkout", for: $0, in: flags) }
print("raised to 25%: \(at25) users; all \(at10.count) kept: \(yesNo(kept))")

let both = at10.filter { isOn("dark-mode", for: $0, in: flags) }.count
print("also on for dark-mode at 10%: \(both) of them, about one in ten")
let unknown = isOn("no-such-flag", for: "user-1", in: flags)
print("an unknown flag: \(unknown ? "on" : "off")")

In Swift: &* is the wrapping multiply; a plain * stops the program on overflow. The argument labels make each call read as a sentence: isOn(flag, for: user, in: flags).

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

def fnv1a32(text)
  # FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  text.each_byte.reduce(0x811C9DC5) { |hash, byte| ((hash ^ byte) * 0x01000193) & 0xFFFFFFFF }
end

def on?(flags, flag, user)
  percent = flags[flag]
  return false if percent.nil? # an unknown flag gets the safe default: off

  # The bucket, 0 to 9,999, is the user's place in line for this flag.
  fnv1a32("#{flag}:#{user}") % 10_000 < percent * 100
end

def yes_no(value)
  value ? 'yes' : 'no'
end

users = (0...50_000).map { |i| "user-#{i}" }
flags = { 'new-checkout' => 10, 'dark-mode' => 10 }
at10 = users.select { |u| on?(flags, 'new-checkout', u) }
puts "new-checkout at 10%: #{at10.size} of #{users.size} users"
again = at10.all? { |u| on?(flags, 'new-checkout', u) }
puts "the same users on a second call: #{yes_no(again)}"

flags['new-checkout'] = 25
at25 = users.count { |u| on?(flags, 'new-checkout', u) }
kept = at10.all? { |u| on?(flags, 'new-checkout', u) }
puts "raised to 25%: #{at25} users; all #{at10.size} kept: #{yes_no(kept)}"

both = at10.count { |u| on?(flags, 'dark-mode', u) }
puts "also on for dark-mode at 10%: #{both} of them, about one in ten"
unknown = on?(flags, 'no-such-flag', 'user-1')
puts "an unknown flag: #{unknown ? 'on' : 'off'}"

In Ruby: Integers grow past 64 bits, so & 0xFFFFFFFF keeps the low 32 bits; a predicate method ends in ?, so is_on is on? here.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

fun fnv1a32(text: String): UInt {
    // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
    var hash = 0x811c9dc5u
    for (byte in text.encodeToByteArray()) {
        hash = (hash xor byte.toUByte().toUInt()) * 0x01000193u
    }
    return hash
}

fun isOn(
    flags: Map<String, Int>,
    flag: String,
    user: String,
): Boolean {
    val percent = flags[flag] ?: return false // an unknown flag gets the safe default: off
    // The bucket, 0 to 9,999, is the user's place in line for this flag.
    return fnv1a32("$flag:$user") % 10_000u < (percent * 100).toUInt()
}

fun yesNo(ok: Boolean) = if (ok) "yes" else "no"

fun main() {
    val users = List(50_000) { "user-$it" }
    val flags = mutableMapOf("new-checkout" to 10, "dark-mode" to 10)
    val at10 = users.filter { isOn(flags, "new-checkout", it) }
    println("new-checkout at 10%: ${at10.size} of ${users.size} users")
    val again = at10.all { isOn(flags, "new-checkout", it) }
    println("the same users on a second call: ${yesNo(again)}")

    flags["new-checkout"] = 25
    val at25 = users.count { isOn(flags, "new-checkout", it) }
    val kept = at10.all { isOn(flags, "new-checkout", it) }
    println("raised to 25%: $at25 users; all ${at10.size} kept: ${yesNo(kept)}")

    val both = at10.count { isOn(flags, "dark-mode", it) }
    println("also on for dark-mode at 10%: $both of them, about one in ten")
    val unknown = isOn(flags, "no-such-flag", "user-1")
    println("an unknown flag: ${if (unknown) "on" else "off"}")
}

In Kotlin: UInt arithmetic wraps at 32 bits, and ?: return false leaves the function as soon as the flag is missing.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

int fnv1a32(String text) {
  // FNV-1a, 32 bits, over the bytes of the text (every ID here is ASCII).
  var hash = 0x811c9dc5;
  for (final unit in text.codeUnits) {
    hash = ((hash ^ unit) * 0x01000193) & 0xFFFFFFFF;
  }
  return hash;
}

bool isOn(Map<String, int> flags, String flag, String user) {
  final percent = flags[flag];
  if (percent == null) {
    return false; // an unknown flag gets the safe default: off
  }
  // The bucket, 0 to 9,999, is the user's place in line for this flag.
  return fnv1a32('$flag:$user') % 10000 < percent * 100;
}

String yesNo(bool ok) => ok ? 'yes' : 'no';

void main() {
  final users = List.generate(50000, (i) => 'user-$i');
  final flags = {'new-checkout': 10, 'dark-mode': 10};
  final at10 = users.where((u) => isOn(flags, 'new-checkout', u)).toList();
  print('new-checkout at 10%: ${at10.length} of ${users.length} users');
  final again = at10.every((u) => isOn(flags, 'new-checkout', u));
  print('the same users on a second call: ${yesNo(again)}');

  flags['new-checkout'] = 25;
  final at25 = users.where((u) => isOn(flags, 'new-checkout', u)).length;
  final kept = at10.every((u) => isOn(flags, 'new-checkout', u));
  print('raised to 25%: $at25 users; all ${at10.length} kept: ${yesNo(kept)}');

  final both = at10.where((u) => isOn(flags, 'dark-mode', u)).length;
  print('also on for dark-mode at 10%: $both of them, about one in ten');
  final unknown = isOn(flags, 'no-such-flag', 'user-1');
  print('an unknown flag: ${unknown ? 'on' : 'off'}');
}

In Dart: int is 64 bits on the VM and in WebAssembly, so the product fits before the mask; compiled to JavaScript it would not.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

new-checkout at 10%: 5076 of 50000 users
the same users on a second call: yes
raised to 25%: 12491 users; all 5076 kept: yes
also on for dark-mode at 10%: 534 of them, about one in ten
an unknown flag: off

The same user always gets the same answer. Raising the percentage only adds users, because buckets below 10% are also below 25%: all 5,076 users who had the feature at 10% still have it at 25%. And two flags at 10% share about 1% of users, as independent flags should: 534 of those 5,076, about one in ten, also have dark-mode, because the flag’s key changes every user’s bucket; without it, every flag at 10% would go to the same tenth of your users. Every service must also hash exactly the same text, or one user gets two answers from two services.

Choose the default as carefully as the rollout. OpenFeature, an open specification for a vendor-neutral flag API, has every evaluation take a flag key and a default value, plus an optional evaluation context whose targeting key identifies the user, and requires it to return the default value instead of throwing when anything goes wrong (flag evaluation, evaluation context). When the flag service is unreachable, users get the default, so make the default the old, safe behaviour. And a flag reverts only the code it guards: anything else the same deploy changed still needs a rollback.

Key idea

A flag’s answer is a function of the flag key and the user ID alone, so every server agrees, raising the share only adds users, and a failed evaluation returns the safe default.

Checkpoint

Check: Flags and percentage rollouts

  1. Question 1 of 2 A service evaluates the flag new-checkout through an OpenFeature client with the default value false, and evaluation fails because the flag provider is unreachable. What does the evaluation return?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: false, the default value the code passed in

    The OpenFeature specification requires evaluation calls not to throw and to return the default value when anything goes wrong, with an error code in the evaluation details. That is why the default should be the safe behaviour, usually the old code path.

  2. Question 2 of 2 new-checkout is on for 10% of users, the buckets below 1,000. It is raised to 25%. Which users have the feature now?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Everyone who had it before, plus the users in buckets 1,000 to 2,499

    The program checked it on 50,000 users: all 5,076 who had the feature at 10% still had it at 25%, when 12,491 had it. That stability is what makes a gradual rollout safe to raise and lower.

Every flag needs an owner and an expiry date

Every flag doubles the paths through the code it guards, and flags multiply because they are cheap to add. Hodgson recommends testing the production configuration with the flags you are about to turn on, and the same with them off, rather than every combination. To stop flags piling up, give each an owner and an expiry date when it is created, add the task to remove it at the same time, and let a test fail once a flag outlives its date.

The cost of a forgotten flag is on record in a regulator’s order. The US Securities and Exchange Commission found that when a trading firm, Knight Capital, deployed new order-routing code to its eight routing servers, a technician did not copy it to one of them, and no second person checked the deployment. The new code reused a flag that had once switched on an old function, Power Peg, which was never deleted. Orders carrying the flag reached the eighth server and woke the old code, which sent child orders without stopping: over 4 million executions in 154 stocks in about 45 minutes, and a loss of more than $460 million. While searching for the cause, the firm removed the new code from the seven correct servers, which made things worse, because the reused flag now woke the old code there too (SEC order).

Not affiliated

Based on public information about Knight Capital. MySmartCoPilot is not affiliated with Knight Capital, and Knight Capital’s real systems may differ from what this lesson describes.

Timeline · 6 events in order How a reused flag woke dead code Walk through the deployment in order. Each step breaks one rule of this lesson.
  1. Before the release

    An old function stays in the code dead code

    Power Peg, a function the firm no longer used, was never deleted, and neither was the flag that had once switched it on.

  2. The deploy

    Seven of eight servers updated unchecked deploy

    New order-routing code was copied to seven of the eight routing servers. A technician missed the eighth, and no second person checked the deployment.

  3. The new code

    An old flag gets a new meaning reused flag

    The new code reused the flag that had once switched on Power Peg, so on a server without the new code the flag still meant the old function.

  4. Orders arrive

    The eighth server wakes the old code

    Orders carrying the flag reached the eighth server, where they switched on Power Peg, which sent child orders without stopping.

  5. The search

    A rollback makes it worse rollback to old code

    Looking for the cause, the firm removed the new code from the seven correct servers. The reused flag then woke the old code there too.

  6. About 45 minutes

    Over 4 million executions

    In about 45 minutes the old code made over 4 million executions in 154 stocks, and the firm lost more than $460 million.

The timeline has 6 events, from Before the release to About 45 minutes.

Each mistake breaks a rule of this lesson: verify that every server runs the version you expect, never give an old flag a new meaning, delete dead code with its flag, and roll back only to a version that handles the new inputs.

Checkpoint

Check: Keeping flags under control

  1. One question In the deployment the SEC order describes, which practice from this lesson would have stopped the trouble before any order was sent?

    Choose one answer.

    Show the answer: One question

    Answer: Checking that every server runs the version you expect before turning anything on

    A technician did not copy the new code to one of the eight servers and no second person checked. Verifying every server, deleting dead code with its flag and never reusing an old flag each break the chain; the first breaks it before the market sees anything.

Five DORA metrics measure delivery, per service

DORA, a long-running research programme on software delivery, measures it with five metrics (DORA metrics). Three describe throughput: change lead time (from commit to production), deployment frequency and failed deployment recovery time. Two describe instability: change fail rate, the share of deployments that need immediate intervention, and deployment rework rate, the share of deployments that were unplanned and made because of an incident. Here is how each is counted for one service in one month, with example numbers:

Metric Kind Counted for one service, with an example
Change lead time Throughput Time from commit to production, such as a median of 6 hours
Deployment frequency Throughput Deployments to production, such as 40 a month
Failed deployment recovery time Throughput Time to recover from a failed deployment, such as 12 minutes
Change fail rate Instability Deployments that needed immediate intervention: 6 of 40 is 15 %
Deployment rework rate Instability Unplanned deployments made because of an incident: 4 of 40 is 10 %

DORA finds that speed and stability are not a trade-off: teams tend to be good, or poor, at all five. Automatic rollback shortens recovery time, canaries make each failure cheaper, and flags let small changes ship often. DORA also warns against turning the metrics into targets and against comparing teams whose systems differ: measure each service against its own past.

Checkpoint

Check: The five DORA metrics

  1. One question A service was deployed 40 times in a month, and 6 of those deployments needed an immediate rollback or fix. What is its change fail rate, in per cent?

    Type a number.

    Show the answer: One question

    Answer: 15 %

    DORA's change fail rate is the share of deployments that need immediate intervention: 6 ÷ 40 = 15%. Track it for this service month by month, not as a target and not against a team whose system is different.

Practise: split users between the variants of a flag

Write the bucketing of a flag service in JavaScript: the bucket of a user, then the variant a split gives them, with the boundary cases and the errors a real service must refuse. Its sample tests run in your browser:

Exercise · Medium · JavaScript

Split users between the variants of a flag by hashing

A flag service has to give every user the same variant on every request and on every server, without storing who got what. Write two functions in rollout.mjs and export them; fnv1a32(text) is there already.

**bucketOf(flagKey, userId)** returns the user's bucket for that flag, a whole number from 0 to 9,999: hash the text flagKey + ':' + userId with fnv1a32 and take the remainder after dividing by 10,000. For example, bucketOf('new-checkout', 'user-42') is 9926.

**variantOf(flagKey, userId, split)** returns the name of the variant the user gets. split is a list of [variant, percent] pairs, such as [['on', 10], ['off', 90]]:

  • Each variant gets Math.round(percent * 100) buckets, and the variants take consecutive ranges in the order they are listed: with the split above, buckets 0 to 999 are 'on' and buckets 1,000 to 9,999 are 'off'.
  • A variant with 0 per cent gets no buckets, so it is never returned.
  • Percents may have fractions: [['on', 0.5], ['off', 99.5]] gives 'on' to buckets 0 to 49.
  • If a percent is negative, or the buckets do not add up to exactly 10,000, throw a RangeError.

Because the ranges follow the list, raising the first variant from 10 to 20 per cent keeps everyone who already had it. The sample tests check that, and the share of 20,000 users each variant gets; they import both functions from rollout.mjs and run in your browser.

Starter code · rollout.mjs

/** FNV-1a, 32 bits, over the characters of `text`. Complete: use it as it is. */
export function fnv1a32(text) {
  let hash = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    hash ^= text.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193) >>> 0;
  }
  return hash;
}

/** The bucket of `userId` for the flag `flagKey`: a whole number from 0 to 9,999. */
export function bucketOf(flagKey, userId) {
  // Replace this line with your code.
  return 0;
}

/** The variant that `userId` gets from `split`, a list of [variant, percent] pairs that add up to 100. */
export function variantOf(flagKey, userId, split) {
  // Replace this line with your code.
  return split[0][0];
}
The sample tests · rollout.test.mjs
import { test, assert } from 'mysmartcopilot:test';
import { bucketOf, variantOf } from './rollout.mjs';

const USERS = Array.from({ length: 20000 }, (_, i) => `user-${i}`);
const share = (flagKey, split, variant) => USERS.filter((u) => variantOf(flagKey, u, split) === variant).length / USERS.length;

test('buckets are the hash of "flagKey:userId" modulo 10,000', () => {
  assert.equal(bucketOf('new-checkout', 'user-42'), 9926);
  assert.equal(bucketOf('new-checkout', 'user-7'), 8825);
  assert.equal(bucketOf('dark-mode', 'user-42'), 3953);
});

test('every bucket is a whole number from 0 to 9,999', () => {
  assert.ok(
    USERS.every((u) => {
      const b = bucketOf('search-v2', u);
      return Number.isInteger(b) && b >= 0 && b < 10000;
    }),
  );
});

test('ranges follow the order of the split, with the boundary in the next range', () => {
  assert.equal(variantOf('new-checkout', 'user-12785', [['on', 10], ['off', 90]]), 'on');   // bucket 999
  assert.equal(variantOf('new-checkout', 'user-15843', [['a', 25], ['b', 75]]), 'a');      // bucket 2499
  assert.equal(variantOf('new-checkout', 'user-5058', [['a', 25], ['b', 75]]), 'b');       // bucket 2500
});

test('0% and 100% mean nobody and everybody', () => {
  assert.equal(share('new-checkout', [['on', 0], ['off', 100]], 'on'), 0);
  assert.equal(share('new-checkout', [['on', 100]], 'on'), 1);
});

test('a 25/75 split gives the treatment to about a quarter of 20,000 users', () => {
  const s = share('price-test', [['control', 75], ['treatment', 25]], 'treatment');
  assert.ok(s > 0.24 && s < 0.26, `the treatment share is ${s}`);
});

test('raising "on" from 10% to 20% keeps everyone who had it', () => {
  const had = USERS.filter((u) => variantOf('new-checkout', u, [['on', 10], ['off', 90]]) === 'on');
  assert.ok(had.length > 0);
  assert.ok(had.every((u) => variantOf('new-checkout', u, [['on', 20], ['off', 80]]) === 'on'));
});

test('a fraction of a per cent is a whole number of buckets', () => {
  assert.equal(variantOf('new-checkout', 'user-880', [['on', 0.5], ['off', 99.5]]), 'on');  // bucket 12
  assert.equal(share('new-checkout', [['on', 0.5], ['off', 99.5]], 'on') * USERS.length, 95);
});

test('splits that do not add up to 100, or have a negative percent, throw a RangeError', () => {
  assert.throws(() => variantOf('new-checkout', 'user-1', [['on', 10], ['off', 80]]), RangeError);
  assert.throws(() => variantOf('new-checkout', 'user-1', [['on', 110], ['off', -10]]), RangeError);
});
A hint

bucketOf is one line: ` fnv1a32(${flagKey}:${userId}) % 10000 . For variantOf, first turn every percent into a number of buckets with Math.round(percent * 100), check that none is negative and that they add up to 10,000, then walk the list keeping the bucket where the current variant's range ends: end += size. The first variant whose end` is greater than the user's bucket is the answer.

The sample tests run on this device, in your browser (QuickJS): nothing is sent to mysmartcopilot.com. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then check yourself, one question at a time, weakest idea first:

Practice that adapts to you

Practise this lesson

20 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 20 What two things multiply to give the damage a bad build does?

    Choose one answer.

    Show the answer: Question 1 of 20

    Answer: The share of traffic it serves and the time until it is gone

    Damage is roughly the share of traffic on the bad build times the time until it is gone. Canaries cut the first factor; fast detection, automatic rollbacks and flags cut the second.

  2. Question 2 of 20 At 2,000 requests a second, a 99.9% monthly objective allows 5,184,000 failed requests. A bad build deployed to everyone fails 360,000 before it is undone. About what share of the month's budget is that, in per cent?

    Type a number.

    Show the answer: Question 2 of 20

    Answer: 6.94 % (anything from 6.89 to 6.99 counts)

    360,000 ÷ 5,184,000 ≈ 0.0694, about 6.94% of the month's error budget in a quarter of an hour, the program's first row. The 5% canary's 13,200 failed requests use 0.25%.

  3. Question 3 of 20 Moving the canary from 5% to 1% of traffic cut the failed requests from 13,200 to 2,640. What does the smaller canary cost?

    Choose one answer.

    Show the answer: Question 3 of 20

    Answer: Its check collects requests five times more slowly, so the canary must run about five times longer

    Rare errors need many requests before a check can see them. At 1% the canary earns them five times more slowly than at 5%, so a quiet service may need hours. Busy services can afford a tiny canary; quiet ones trade a larger share for a shorter bake.

  4. Question 4 of 20 Which way of deploying keeps two full environments and moves every user with one switch of the router?

    Choose one answer.

    Show the answer: Question 4 of 20

    Answer: Blue-green

    Blue-green keeps the old environment, blue, running while green is tested with no users, so switching back is a rollback in seconds. The price is a second environment.

  5. Question 5 of 20 A payments API serves 4,000 requests a second from 40 instances behind a load balancer that can split traffic by percentage, and its metrics can be broken down by version. A bad release would be costly. Which way of deploying fits best?

    Choose one answer.

    Show the answer: Question 5 of 20

    Answer: A canary on 1% of traffic, compared with the old version before every step

    The service is busy enough for a small canary to collect evidence in minutes, it has the two things a canary needs (a traffic split and per-version metrics), and the cost of a bad release is high. A canary limits a bad build to 1% of requests while the comparison runs; a rolling update without a gate would reach the whole fleet before most problems are noticed.

  6. Question 6 of 20 A release changes a web page and the API behind it together, and every user must move to the new pair at the same moment. The team can afford a second full environment for an hour and wants to be back on the old pair within seconds if anything goes wrong. Which way of deploying fits?

    Choose one answer.

    Show the answer: Question 6 of 20

    Answer: Blue-green, switching the router once both new parts are tested

    Blue-green moves everyone at once, and the old environment stays ready, so switching back takes seconds. A rolling update or a canary would mix old pages with the new API, or the reverse, for the length of the rollout.

  7. Question 7 of 20 Why does the automated canary check roll back only at z of 3 or more, not at 2?

    Choose one answer.

    Show the answer: Question 7 of 20

    Answer: It looks again every minute, and each look is another chance that chance alone crosses the limit

    On a healthy canary z is roughly a standard normal value, so the chance of 3 or more on one look is about 0.0013, and of 2 or more about 0.0228. A check that looks sixty times an hour needs the strict limit, and the absolute ceiling catches a badly broken build without waiting.

  8. Question 8 of 20 At a 0.1% baseline error rate the check needs about 24,900 canary requests to catch a doubled rate nine times in ten. How many minutes does a 5% canary need on a service with 200 requests a second?

    Type a number.

    A hint

    The canary gets 5% of 200 requests a second.

    Show the answer: Question 8 of 20

    Answer: 41.4 minutes (anything from 40.4 to 42.4 counts)

    The canary gets 10 requests a second, so 24,866 requests take 2,487 seconds, about 41.4 minutes, the program's first row. At 20,000 requests a second the same check needs 25 seconds: size the bake by requests, not only by the clock.

  9. Question 9 of 20 A canary on 5% of traffic fails 10% of its requests, and the old version fails none. By how many percentage points does the fleet-wide error rate rise?

    Type a number.

    Show the answer: Question 9 of 20

    Answer: 0.5 percentage points

    5% of the traffic at a 10% failure rate is 0.05 × 0.10 = 0.005 of all requests, half a percentage point. A fleet-wide alarm set for a few points would never fire, which is why a canary is compared with its own baseline.

  10. Question 10 of 20 Which of these does a safe rollback need? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 10 of 20

    Answer:

    • A build of the old version that can still be deployed
    • Nothing irreversible done by the release, such as a dropped column
    • An old version that reads everything the new one wrote

    The old build must still be deployable, nothing irreversible may have happened, and the old version must read everything the new one wrote. The third is the one releases most often break, by changing a stored format or a message.

  11. Question 11 of 20 Put the steps of a two-phase deployment that changes a stored format in order.

    Give each item its position, from 1 (first).

    Show the answer: Question 11 of 20

    Answer:

    1. Deploy a version that reads both formats but still writes the old one
    2. Check that every server runs that version, then let it bake
    3. Deploy the version that writes the new format
    4. Rewrite every stored record in the new format
    5. Remove the code that reads the old format

    Readers go before writers. Once every server can read both formats, writing the new one is safe to roll back, because the version you would return to reads it. The old reader goes last, and only after no record in the old format is left.

  12. Question 12 of 20 A release changes the messages one service puts on a queue for another, from a list of IDs to objects with quantities. Which plan keeps every step safe to roll back?

    Choose one answer.

    Show the answer: Question 12 of 20

    Answer: First ship consumers that read both message formats everywhere, then switch the producer to the new one

    A message on a queue is stored data that another version reads, so the same rule applies: deploy the readers of both formats everywhere, check every instance, then switch the writer, and remove the old reader only when no old message is left.

  13. Question 13 of 20 What does a feature flag separate?

    Choose one answer.

    Show the answer: Question 13 of 20

    Answer: Deploying code to the servers from releasing a behaviour to users

    Deploying puts code on servers; releasing lets users use a behaviour. A flag makes them two steps, so a deploy changes nothing users see and a release can be undone in seconds without a deploy.

  14. Question 14 of 20 new-checkout and dark-mode are each on for 10% of 50,000 users. About how many users have both, and why?

    Choose one answer.

    Show the answer: Question 14 of 20

    Answer: About 500, because the flag key is part of the hash, so the two tenths are independent

    Hashing the flag key with the user ID gives every flag its own order of users. Without the flag key, every flag at 10% would go to the same tenth of your users, who would then test every new feature at once.

  15. Question 15 of 20 The web service hashes "flagKey:userId" and the mobile API hashes "userId:flagKey" for the same 10% flag. What does a user who uses both see?

    Choose one answer.

    Show the answer: Question 15 of 20

    Answer: Two independent answers, so about 18% of users get the feature in one place and not the other

    A user is in one service's 10% and not the other's with probability 2 × 0.1 × 0.9 = 0.18. Every service must hash exactly the same text, or one user gets two answers, which is why flag clients share one library.

  16. Question 16 of 20 Which kind of toggle should be gone within a week or two?

    Choose one answer.

    Show the answer: Question 16 of 20

    Answer: A release toggle, which hides an unfinished or unreleased feature

    Hodgson's categories differ by how long a flag lives: release toggles days or weeks, experiment toggles until a test has a result, ops toggles as needed (a few for good) and permissioning toggles for years.

  17. Question 17 of 20 Why is giving an old, unused flag a new meaning dangerous?

    Choose one answer.

    Show the answer: Question 17 of 20

    Answer: Any server or code path that still reads the old meaning wakes the old behaviour when the flag turns on

    A flag's meaning lives in every version of the code that reads it. Give new behaviour a new flag, and delete the dead code together with the flag that switched it on.

  18. Question 18 of 20 Which three DORA metrics describe throughput? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 18 of 20

    Answer:

    • Change lead time
    • Failed deployment recovery time
    • Deployment frequency

    DORA groups change lead time, deployment frequency and failed deployment recovery time as throughput, and change fail rate and deployment rework rate as instability. Teams tend to be good, or poor, at all five.

  19. Question 19 of 20 Of a service's 50 deployments in a month, 4 were unplanned hotfixes made because of an incident in production. What is its deployment rework rate, in per cent?

    Type a number.

    Show the answer: Question 19 of 20

    Answer: 8 %

    Deployment rework rate is the share of deployments that were unplanned and made because of an incident: 4 ÷ 50 = 8%. Compare it with the same service's past months.

  20. Question 20 of 20 A director wants every team to reach the same deployment frequency by next quarter and to rank teams by it. What does DORA's guidance say about that plan?

    Choose one answer.

    Show the answer: Question 20 of 20

    Answer: Do not turn the metrics into targets or compare teams whose systems differ; measure each service against its own past

    DORA warns against making the metrics targets and against comparing teams whose systems differ. Use them to see whether each service is getting better, and improve the practices behind them: automatic rollback, canaries, small changes behind flags.

Design practice: releases to plan

An interviewer who asks about releases wants the first move before the details. Make it for each brief below, then test your numbers on the programs above: the canary check takes any counts, and the cart store shows what a change of format does to a rollback.

Checkpoint

Your first decision

  1. Question 1 of 2 Your service takes 3,000 requests a second. After 10 minutes, a canary on 5% of traffic shows 0.9% errors and the stable version 0.6%. What is your first step before deciding?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Turn both rates into counts over the same 10 minutes, then ask whether the gap is larger than chance

    The canary check of this lesson works on counts: requests and errors of the canary and of the baseline over the same minutes. Work them out first, then the two-proportion test, the minimum number of requests and the ceiling decide; the program above takes any counts.

  2. Question 2 of 2 A release changes how carts are stored. Ten minutes in, errors rise, you roll back, and the errors get worse. What do you ask first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: What the new version wrote during those ten minutes

    A rollback is safe only when the old version reads everything the new one wrote. In the cart program the rollback made 400 carts unreadable: the plan has to separate teaching every server to read the new format from starting to write it.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    Your service takes 3,000 requests a second. After 10 minutes, a canary on 5% of traffic shows 0.9% errors and the stable version 0.6%. Do you promote, wait or roll back? Show the numbers, then say what you would automate.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to staff

    A release changes how carts are stored: each item becomes an object with a quantity instead of a plain product ID. Ten minutes in, errors rise, you roll back, and the errors get worse. Explain why, and plan the change so that every step can be rolled back.

    Model answer, Pro. First step and follow-ups

Interview questions

What is the difference between deploying and releasing?

Deploying puts a new version of the code on the servers; releasing lets users use a new behaviour. With feature flags they become separate steps: the code ships switched off, so a deploy changes nothing users see, and the release is a configuration change that can reach 1% of users, then everyone, and be switched off again in seconds without a deploy. Keeping them apart makes deploys small and routine, lets a release wait for the right moment and gives a switch that is faster than a rollback.

What is a canary deployment, and what is it compared with?

A canary sends a small share of real traffic, often 1% to 5%, to the new version and moves forward in steps only while the new version is as healthy as the old one. It is compared with the old version serving traffic during the same minutes, on a few metrics such as errors and latency: not with the whole fleet, whose average hides a small canary, and not with the hour before, because traffic and dependencies change over time. It also needs enough requests before a difference counts, and an absolute limit stops a badly broken build at once.

Key takeaways

  • The damage of a bad build is the share of traffic it serves times the time until it is gone; canaries cut the first factor, automatic rollbacks and flags the second.
  • Rolling updates are cheap but mix versions and roll back slowly; blue-green moves everyone at once and back in seconds; a canary exposes a small share and compares it with the old version before each step.
  • Judge a canary against a concurrent baseline with a test such as the two-proportion z-test, a minimum number of requests and an absolute ceiling; quiet services and rare errors need longer canaries.
  • A rollback is safe only when the old version reads what the new one wrote: ship a reader of both formats first, switch the writer second, and remove the old reader once every record is rewritten.
  • Flags separate deploying from releasing; bucket users by a hash of the flag key and user ID, make the default the safe behaviour, and give every flag an owner and an expiry date.
  • Track the five DORA metrics per service, never as targets.

Terms in this lesson

blue-green deployment
A release onto a second full environment that is tested with no users and then made live by one switch of the router; the old environment stays ready, so switching back takes seconds.
canary release
A release that first sends a small share of real traffic, often 1 % to 5 %, to the new version and compares it with the old version serving at the same time before every step up.
feature flag
A switch in configuration that code reads at run time to turn a behaviour on or off for some or all users, so that releasing a feature, or switching it off again, needs no deploy.
rolling update
A release that replaces a few instances at a time until all of them run the new version, so old and new versions serve side by side for the whole rollout.
two-phase deployment
A change of a stored format shipped as two releases: first a version that reads both formats but still writes the old one, then one that writes the new format, so each step can be rolled back.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.