Testing in production: canaries, flags and synthetic checks
Staging cannot reproduce your users. Test the change on a slice of real traffic, with a size you chose, a rule for stopping you wrote first, and a switch that works in seconds
Owoleaf handles about 36,000 card top-ups an hour (illustrative). Rachid releases the new flow to 1% of users. The old flow fails 0.1% of requests; the new flow, because of a bug, fails 2%. After one hour, what do you expect to see?
Testing before release answers one question: does this change do what we meant, in an environment we built? Testing in production answers another: does it keep working in the environment we did not build, with the data, traffic, providers and devices that only exist live? Both are testing. Neither replaces the other. The checkout suite you have built across this course is the cheap, fast, early half. This chapter is the late half, and it is dangerous in a way the early half is not, because the users are real.
What staging cannot know
A staging environment differs from production in at least five ways, and each has caused real outages.
- Data. Production holds years of odd records: an order with no postcode, a product with a 400-character name, a wallet in a state nobody planned for. Staging data is a copy at best, and usually a tidy invention.
- Traffic. Production has a mix: bursts at lunchtime, retries, a partner’s batch job, a bot. Staging has your test runner.
- Dependencies. The payment provider’s sandbox accepts cards the live one rejects, and the live one asks live banks questions the sandbox never asks.
- Scale and config. Connection pool sizes, timeouts, caches and the number of instances differ. A race that needs 200 concurrent requests does not appear with 3.
- Users. Real people use old phones, slow networks and sequences of clicks no one wrote down.
You cannot close these gaps by adding more staging. You can make the first live exposure small, observed and reversible. Four tools do that, and each answers a different question.
| Tool | The question it answers | What controls the blast radius | What it cannot see |
|---|---|---|---|
| Feature flag | Does this behaviour work for real users? | A percentage of users, or a list | Problems in code that runs whatever the flag says |
| Canary release | Does this build work under real traffic? | A few instances out of many | Faults that need all users or the full load |
| Synthetic check | Is this one journey working right now? | One test account, one order | Anything the probe does not do |
| Dark launch or shadow traffic | Does the new path agree with the old on real requests? | Its answers are thrown away | Anything that only shows when the answer is used |
The fourth row is named for completeness and not built here. The first three are what you build in the lab, on the checkout service, with Owoleaf’s top-up change as the scenario in your head. The lab’s checkout service stands in for the top-up flow: the mechanics are the same, and only the money is fake.
Feature flags: separating release from deploy
A deploy puts code on servers. A release lets users reach behaviour. Merge the two and every deploy is a bet on the whole user base. A flag separates them: the new code ships switched off, and a decision, made later and made by someone who is watching, turns it on.
The lab’s checkout/flags.py is the small honest version. A flag is a name with enabled and rollout_percent. For one user, is_enabled(flag, user_id) computes bucket(flag, user_id), which is the first four bytes of a SHA-256 hash of flag:user_id, modulo 100. The answer is true when the bucket is below the rollout percentage. Three properties follow, and each is a test you should be able to write.
The same user always gets the same answer. A hash has no memory and no randomness, so a user in bucket 8 is on the new path at 10% and stays on it at 25%. Raising the percentage only adds people. A user who flips between old and new on each request would see prices or screens change under them, and your data would mix the two paths.
The percentage is real. Of 10,000 users the lab’s hash puts 97 in the first 1%, 480 in the first 5% and 2,495 in the first 25%. It is close to the nominal figure, not equal, so you test for a range.
Flags are independent of each other. The flag’s name is part of the hash. Without it, the same 1% of users would be first in line for every experiment and your unluckiest customers would meet every unfinished feature. Two 10% cohorts under different names overlap by about 1% of users, not by all of them: in the lab’s hash 112 of 10,000 users are in both, against 100 expected.
A flag has a second job, which is the reason operations teams love it: the kill switch. FlagStore re-reads its file when the file’s modification time changes, so setting enabled to false takes effect on the next request with no deploy and no restart. At 2 a.m. that is the difference between a 30-second fix and a 20-minute rollback pipeline. A kill switch you have never used is a hope, so the lab flips it live and a test asserts it.
How flags go wrong
- The flag file takes the service down. The lab’s
FlagStoreraises if the file holds invalid JSON. Wire it in naively and a half-saved file turns every order into a 500. You break exactly this at the end of the lab. A flag read must fail closed: unreadable means off. - Flag debt. Every flag doubles the paths through the code. Ten live flags are 1,024 combinations, and you test a handful. Delete a flag once the rollout is at 100% and stable. A flag with no owner and no date is a future incident.
- Unlabelled telemetry. If your dashboards do not record which path served a request, a 2% failure rate on 1% of users hides in the average. The lab returns an
X-Checkout-Pathheader for this reason. In a real service the path goes on the log line, the trace and the metric. - Testing only the default. A flag is a test configuration. The suite runs with the flag off and on, or it covers only what users stop seeing.
Canary releases: judge by comparison, with rules written first
A canary is a new build on a small part of production, watched against the rest. The Google SRE Workbook chapter on canarying describes it as a partial, time-limited rollout of a change, evaluated against a control population, and the word that matters is control. You do not ask whether the canary is good. You ask whether it is worse than the baseline running beside it, now.
Why a baseline and not a threshold such as 99% success? Because the world moves. If the provider is slow for ten minutes, a fixed latency threshold fails the canary for something the canary did not do, or passes it because the baseline sits at 80% of the limit and the canary’s slowdown fits underneath. The baseline shares the traffic, the minute and the provider. What differs is the change.
Write the abort rules before the run
Agree the rules, in a file, before the canary takes any traffic. Four things go in it:
- The metrics. Start with two: the error rate and the p95 latency, both from the golden signals of the Observability course.
- What counts as an error. A 5xx is. A 402 decline or a 409 out-of-stock is an answer the service meant to give. Say so, or the first argument happens during the incident.
- How much worse is too much. Error rate: more than 1 percentage point over the baseline. p95: more than 1.5 times the baseline plus 100 ms. The margin stops a 6 ms against 9 ms difference from being a crisis.
- How much data you need. Below a minimum number of requests the honest verdict is neither pass nor fail. It is HOLD: do not widen, do not roll back, wait. Add a minimum number of failures too: an error-rate abort needs at least a handful of failed requests on the canary, or one unlucky request is enough to stop a healthy release.
Why in advance? Because after the numbers arrive, every number has an explanation. “It is only the test accounts.” “That bank is always slow.” A rule written at 10 a.m. on a quiet day beats a judgement made at 3 p.m. with a launch date behind you. The same logic sits behind the error budget: decide what you will do when the number crosses the line before it does.
The minimum sample deserves the most thought, because small canaries are statistically weak. In the Predict, a 1% canary saw 7 failures in an hour. An abort rule of one extra percentage point would fire there, but a real 0.3% regression would show as one failure and look like luck. The numbers are worse than they feel. A simulation of the lab’s judge, with a baseline that fails 0.1% of requests and a 1-point margin, aborted a healthy canary about 3% of the time on 30 requests per side, and caught a true 2% failure rate only about 44% of the time. Thirty requests cannot support a margin of one point. With a minimum of 3 failures and 200 requests per side, a true 2% failure rate was caught in roughly three runs in four, and with 500 requests per side in about 90%; a healthy canary almost never aborted. That is why the lab’s rules file asks for 200 requests and 3 failures, and why the Predict’s canary, at 360 requests an hour, needs at least half an hour for a verdict. Owoleaf either waits longer, or widens in steps (1%, 5%, 25%, 100%) with a bake time at each, so that the larger step provides the sample that the smaller could not. Say the cost aloud: a small canary is safe because it is slow to prove anything.
What an A/A run is for
Before you trust the comparison, run it with a canary that is not changed: the same build on both sides. It should say PROMOTE. If it does not, your rules are too tight for the noise in your system, and no real canary can pass. The lab starts with this run. Teams that skip it spend their first month aborting healthy releases.
Production tooling automates all of this. Argo Rollouts runs the stepwise widening on Kubernetes and queries your metrics to promote or roll back. Netflix’s open-source Kayenta is the best-known statistical judge. The logic in the lab’s canary_compare.py, a few lines of comparison, is the heart of each.
Synthetic checks: someone is always using it
A real user is not always there. At 3 a.m. there may be no top-ups for ten minutes, and a broken checkout shows no error rate because there is no traffic: zero errors out of zero requests. A synthetic check is a program that plays one journey on a schedule. The Observability course’s chapter on synthetic monitoring covers where probes run from and how to alert on them. Here you build the test side.
The lab’s scripts/synthetic_check.py places one real order, reads it back and prints PASS 36 ms or FAIL .... Three decisions turn it from a script into a monitor.
How often. Every 10 seconds gives you a first alert in about 30 seconds. It also places 8,640 orders a day.
What it costs. Each probe takes one unit of stock and charges the fake provider. At 10 seconds apart the 100 units of product 2 are gone in under 17 minutes. In a real shop that is stock, a payment fee, an order in the revenue report and a parcel for the warehouse to ignore. A synthetic probe needs a test account, a test product with unlimited stock, a provider sandbox, and a marker (the lab’s synthetic- key prefix) that every report excludes. A probe that books real revenue is a bug of its own.
When to alert. One failed probe is a blip. Three in a row, 30 seconds, is an outage. The lab’s loop script says ALERT after that count, and the count is an argument so that you can choose it.
And a fourth, easy to forget: a probe can fail for a reason that is not an outage. In the lab you set the stock to zero and the probe fails with a 409. The system is working exactly as designed, and the alert is true and useless. Before you page anyone, know what each failure message means.
What a probe cannot do
It sees one journey with one user and one cart. It does not see the variety of real traffic, and a probe’s latency limit (1,500 ms in the lab) is a limit for being broken, not for being worse. In the lab a canary whose provider takes a second passes the probe (a slow provider still answers inside 1,500 ms) and fails the canary comparison. The probe asks whether it works; the canary asks whether it is worse. You need both.
What not to test in production
Testing in production is not testing without care. Never move real customers’ money for a test: use test accounts, the provider’s sandbox or a zero-value authorisation. Never write test data that reaches customers’ statements, reports or notifications. Never use a flag for a change you cannot reverse: a schema migration that drops a column is not undone by switching a flag off, and the migrations chapter is where that belongs. And do not start a canary you cannot stop: know who can press the button, and that it works, before the release, not during it. The QA career track’s chapter on testing in production and observability covers who decides and who is on call; this one covers the mechanics.
The same discipline joins the rest of the course. Fault injection taught you what the checkout does when the provider fails. A canary with the provider on 500 mode, as you will see, is the same fault seen from the release side: the canary instance has its own provider, and only that one fails, so the difference is attributable.
The lab has no flag in the API, second instance or canary tool, so you write them: one edit to checkout/api.py, a test file, two scripts and a rules file. Numbers below were taken on 2026-11-24 on a busy Mac. Your latencies will differ, and your verdicts should not.
1. Wire the flag into the API. In checkout/api.py, make four changes. Import the store, take it as an optional argument, read it in create_order, and build it from an environment variable:
from checkout.flags import FlagStore
def create_app(
db: Database, payments: Payments, clock: Clock, index: SearchIndex, flags: Optional[FlagStore] = None
) -> FastAPI: @app.post("/orders", status_code=201)
def create_order(
body: CartIn, idempotency_key: str = Header(...), x_user_id: Optional[str] = Header(None)
) -> Any:
user = x_user_id or idempotency_key
path = "new" if flags and flags.is_enabled("new-charge-path", user) else "old"
items = [i.model_dump() for i in body.lines]
# ... unchanged ...
return JSONResponse(status_code=201 if created else 200, content=order, headers={"X-Checkout-Path": path}) flag_file = os.environ.get("CHECKOUT_FLAGS")
return create_app(db, payments, SystemClock(), index, FlagStore(flag_file) if flag_file else None)The last block replaces the return create_app(...) line at the end of app_from_env. The new path does nothing different yet. In your real change the branch holds the new code; here it only labels the response, so you can see who got it. Now create tests/integration/test_flags.py:
"""Flags: stable cohorts, and a kill switch that needs no restart."""
import json
import os
from fastapi.testclient import TestClient
from checkout.api import create_app
from checkout.flags import FlagStore, bucket
from checkout.search_index import SearchIndex
CART = {"lines": [{"product_id": 2, "qty": 1}], "distance_km": 3}
def write_flags(path, rollout, enabled=True):
path.write_text(json.dumps({"new-charge-path": {"enabled": enabled, "rollout_percent": rollout}}))
stamp = os.stat(path).st_mtime + 1 # a new mtime, so the store re-reads at once
os.utime(path, (stamp, stamp))
def path_taken(client, key, user):
r = client.post("/orders", json=CART, headers={"Idempotency-Key": key, "X-User-Id": user})
assert r.status_code == 201
return r.headers["X-Checkout-Path"]
def test_a_one_percent_rollout_reaches_about_one_percent():
reached = sum(1 for i in range(10_000) if bucket("new-charge-path", f"user-{i}") < 1)
assert 70 <= reached <= 130 # 97 today; the hash is fixed, so this never flickers
def test_a_user_keeps_their_answer_and_the_kill_switch_needs_no_restart(tmp_path, db, payments, clock):
flags = tmp_path / "flags.json"
write_flags(flags, rollout=10)
client = TestClient(create_app(db, payments, clock, SearchIndex(), FlagStore(str(flags))))
assert [path_taken(client, f"k{i}", "user-7") for i in range(3)] == ["new"] * 3 # bucket 8, inside 10
write_flags(flags, rollout=10, enabled=False)
assert path_taken(client, "k9", "user-7") == "old".venv/bin/pytest tests/integration/test_flags.py -v -p no:randomly
.venv/bin/pytest -q2 passed). The full suite shows 25 passed, 1 skipped, 1 deselected: the 23 starter tests plus these two. The os.utime line in the helper matters. Two writes inside one clock tick can leave the same modification time, and a store keyed on it would miss the second write.2. Start the stable pair and watch the cohort. Check the ports, create the flag file at 1% and start the provider and the API. Each runs in its own terminal, from labs/testing:
lsof -i :8094 -i :8095 -i :8594 -i :8595
mkdir -p data
echo '{"new-charge-path": {"enabled": true, "rollout_percent": 1}}' > data/flags.json
.venv/bin/uvicorn fake_provider.app:app --port 8095In the second terminal:
CHECKOUT_DB=data/stable.sqlite CHECKOUT_FLAGS=data/flags.json .venv/bin/uvicorn checkout.api:app --port 8094Then, in a third, count the cohort and place orders for two named users:
.venv/bin/python - <<'PY'
from checkout.flags import bucket
for pct in (1, 5, 25):
n = sum(1 for i in range(10_000) if bucket("new-charge-path", f"user-{i}") < pct)
print(pct, "%:", n, "of 10,000")
print([i for i in range(1000) if bucket("new-charge-path", f"user-{i}") < 1][:3])
PY
order() { curl -si -X POST localhost:8094/orders -H 'Content-Type: application/json' \
-H "Idempotency-Key: $1" -H "X-User-Id: $2" \
-d '{"lines":[{"product_id":2,"qty":1}],"distance_km":3}' | grep -i x-checkout-path; }
order f1 user-32; order f2 user-7lsof prints nothing when all four ports are free. The cohort counts are 1 %: 97 of 10,000, 5 %: 480 of 10,000 and 25 %: 2495 of 10,000, and the first three users inside 1% are [32, 149, 305]. The two orders print x-checkout-path: new for user-32 and x-checkout-path: old for user-7. The flag decides per user, not per request.3. Flip the flag without a restart. Raise the rollout to 10%, then switch the flag off, and watch the same users:
echo '{"new-charge-path": {"enabled": true, "rollout_percent": 10}}' > data/flags.json
order f3 user-32; order f4 user-7
echo '{"new-charge-path": {"enabled": false, "rollout_percent": 10}}' > data/flags.json
order f5 user-7
echo '{"new-charge-path": {"enabled": true, "rollout_percent": 1}}' > data/flags.jsonnew and new: user-32 stays on the new path, and user-7 (bucket 8) joins it when 10% takes it in. After enabled is false, user-7 is old again on the very next request. The server was never restarted. The last line puts the flag back to 1% for the rest of the lab.4. Run the synthetic check on a schedule. Create scripts/synthetic_loop.py. It reuses probe from the lab’s check and adds the schedule and the alert rule:
"""Run the synthetic check on a schedule and alert on consecutive failures.
.venv/bin/python scripts/synthetic_loop.py --every 10 --alert-after 3 [--count 6]
"""
import argparse
import sys
import time
from datetime import datetime
from synthetic_check import probe # scripts/ is on sys.path when this file is run
parser = argparse.ArgumentParser()
parser.add_argument("--base", default="http://127.0.0.1:8094")
parser.add_argument("--every", type=float, default=10, help="seconds between probes")
parser.add_argument("--max-ms", type=float, default=1500)
parser.add_argument("--alert-after", type=int, default=3, help="consecutive failures that raise the alert")
parser.add_argument("--count", type=int, default=0, help="stop after this many probes (0 means run for ever)")
ns = parser.parse_args()
failures_in_a_row, runs, alerted = 0, 0, False
while ns.count == 0 or runs < ns.count:
started = time.monotonic()
try:
ok, ms, message = probe(ns.base, ns.max_ms)
except Exception as exc: # belt and braces: the probe reports an unreadable reply itself, but a monitor must never crash on a surprise
ok, ms, message = False, (time.monotonic() - started) * 1000, f"probe could not read the reply: {type(exc).__name__}"
runs += 1
failures_in_a_row = 0 if ok else failures_in_a_row + 1
stamp = datetime.now().strftime("%H:%M:%S")
print(f"{stamp} {'PASS' if ok else 'FAIL'} {ms:.0f} ms {message} (failures in a row: {failures_in_a_row})", flush=True)
if failures_in_a_row >= ns.alert_after and not alerted:
print(f"{stamp} ALERT: {failures_in_a_row} failed probes in a row against {ns.base}", flush=True)
alerted = True
if ok:
alerted = False
if ns.count == 0 or runs < ns.count:
time.sleep(max(0.0, ns.every - (time.monotonic() - started)))
sys.exit(1 if failures_in_a_row else 0).venv/bin/python scripts/synthetic_loop.py --every 2 --count 3; echo "exit $?"00:27:37 PASS 17 ms order placed and read back (failures in a row: 0), latencies between about 5 and 40 ms, then exit 0. The lab runs every 2 seconds so that you do not wait. In a deployment you would leave the default of 10. Each line is a real order: the check consumed three units of stock and made three charges at the fake provider.5. Make the probe fail for the wrong reason. Pretend the shelf is empty, probe, then put the stock back:
.venv/bin/python - <<'PY'
from checkout.db import Database
db = Database("data/stable.sqlite")
print("before:", db.stock_of(2)); db.set_stock(2, 0)
PY
.venv/bin/python scripts/synthetic_loop.py --every 1 --count 3 --alert-after 2; echo "exit $?"
.venv/bin/python -c "
from checkout.db import Database
Database('data/stable.sqlite').set_stock(2, 100)"
.venv/bin/python scripts/synthetic_check.pybefore: prints a number a little under 100 (91 in the run, after the orders so far). Then three FAIL lines, each order returned 409 {'error': 'out_of_stock', ...}, an ALERT: 2 failed probes in a row after the second, and exit 1. After the stock is restored the single check prints PASS. The system worked as designed and the alert fired anyway. A probe that eats its own stock will page you for being successful, which is why the cost of a probe is part of its design.6. Write the abort rules, then start the canary. The rules go in a file before any canary traffic. Create canary_rules.json in labs/testing:
{
"min_requests": 200,
"min_errors": 3,
"max_error_rate_over_baseline": 0.01,
"p95_ratio": 1.5,
"p95_margin_ms": 100
}Create scripts/canary_compare.py. It sends the same orders to a baseline and a canary, alternating so that both see the same seconds, and judges the canary by the rules file:
"""Send the same load to a baseline and a canary and judge the canary by rules written first.
.venv/bin/python scripts/canary_compare.py --baseline http://127.0.0.1:8094 \
--canary http://127.0.0.1:8595 --rules canary_rules.json [--n 200]
Exit 0 for PROMOTE, 1 for ABORT, 2 for HOLD (not enough requests to judge).
"""
import argparse
import json
import math
import sys
import time
import urllib.error
import urllib.request
import uuid
def place_order(base: str, user: str, product: int):
body = json.dumps({"lines": [{"product_id": product, "qty": 1}], "distance_km": 3}).encode()
req = urllib.request.Request(
base + "/orders", data=body, method="POST",
headers={"Content-Type": "application/json", "Idempotency-Key": "canary-" + uuid.uuid4().hex[:12],
"X-User-Id": user},
)
started = time.monotonic()
try:
with urllib.request.urlopen(req, timeout=10) as r:
status = r.status
except urllib.error.HTTPError as e:
status = e.code
except OSError:
status = 599
return status, (time.monotonic() - started) * 1000
def p95(values):
ordered = sorted(values)
return ordered[max(0, math.ceil(0.95 * len(ordered)) - 1)]
def summarise(samples):
errors = sum(1 for status, _ in samples if status >= 500) # 4xx are answers, not failures of ours
counts = {}
for status, _ in samples:
counts[status] = counts.get(status, 0) + 1
return {"statuses": dict(sorted(counts.items())), "requests": len(samples), "errors": errors,
"error_rate": errors / len(samples) if samples else 0.0,
"p95_ms": p95([ms for _, ms in samples]) if samples else 0.0}
def judge(rules, base, can):
if min(base["requests"], can["requests"]) < rules["min_requests"]:
return "HOLD", [f"fewer than {rules['min_requests']} requests on one side"]
reasons = []
if (can["error_rate"] > base["error_rate"] + rules["max_error_rate_over_baseline"]
and can["errors"] >= rules["min_errors"]):
reasons.append(f"error rate {can['error_rate']:.1%} against baseline {base['error_rate']:.1%} "
f"(allowed +{rules['max_error_rate_over_baseline']:.1%})")
limit = base["p95_ms"] * rules["p95_ratio"] + rules["p95_margin_ms"]
if can["p95_ms"] > limit:
reasons.append(f"p95 {can['p95_ms']:.0f} ms over the limit of {limit:.0f} ms")
return ("ABORT" if reasons else "PROMOTE"), reasons
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--baseline", required=True)
parser.add_argument("--canary", required=True)
parser.add_argument("--rules", required=True)
parser.add_argument("--n", type=int, default=200, help="orders per side")
parser.add_argument("--product", type=int, default=2, help="product id to order (needs stock for n orders per side)")
ns = parser.parse_args()
rules = json.load(open(ns.rules))
print("rules:", json.dumps(rules))
base_samples, can_samples = [], []
for i in range(ns.n): # alternate, so both sides see the same minutes
base_samples.append(place_order(ns.baseline, f"user-{i}", ns.product))
can_samples.append(place_order(ns.canary, f"user-{i}", ns.product))
base, can = summarise(base_samples), summarise(can_samples)
for name, s in (("baseline", base), ("canary", can)):
print(f"{name:9} requests={s['requests']} error_rate={s['error_rate']:.1%} p95={s['p95_ms']:.0f} ms "
f"statuses={s['statuses']}")
verdict, reasons = judge(rules, base, can)
print(verdict + ("" if not reasons else ": " + "; ".join(reasons)))
sys.exit({"PROMOTE": 0, "ABORT": 1, "HOLD": 2}[verdict])The canary is a second instance with its own database and its own provider, so that you can break the canary’s provider and leave the baseline’s alone. It also runs the flag at 100%, as a canary of new behaviour would. Create its flag file, check the ports, and start each server in its own terminal:
echo '{"new-charge-path": {"enabled": true, "rollout_percent": 100}}' > data/canary-flags.json
lsof -i :8594 -i :8595
.venv/bin/uvicorn fake_provider.app:app --port 8594If you want the slow-provider run in step 7 to finish in about a minute, start this provider as FAKE_PROVIDER_SLOW_S=0.4 .venv/bin/uvicorn fake_provider.app:app --port 8594 instead. Its slow mode then waits 0.4 s, not the default 1 s.
PROVIDER_URL=http://127.0.0.1:8594 CHECKOUT_DB=data/canary.sqlite CHECKOUT_FLAGS=data/canary-flags.json \
.venv/bin/uvicorn checkout.api:app --port 8595The canary load needs a product with plenty of stock on both instances. Add one, then run the A/A comparison:
for port in 8094 8595; do curl -s -X POST localhost:$port/products -H 'Content-Type: application/json' \
-d '{"seller_id":"shea-co","name":"Canary load item","price_kobo":100000,"stock":5000}'; echo; done
.venv/bin/python scripts/canary_compare.py --baseline http://127.0.0.1:8094 \
--canary http://127.0.0.1:8595 --rules canary_rules.json --product 5; echo "exit $?"
.venv/bin/python scripts/canary_compare.py --baseline http://127.0.0.1:8094 \
--canary http://127.0.0.1:8595 --rules canary_rules.json --product 5 --n 20; echo "exit $?"curl returns a product with "id":5. The first comparison prints the rules, then baseline requests=200 error_rate=0.0% p95=5 ms statuses={201: 200} and a canary line of the same shape (p95=5 ms in one run), then PROMOTE and exit 0. Both sides are healthy, so this is the A/A run: the rules pass a canary with nothing wrong, which you need to know before you trust them to fail one. Your p95 values differ but should sit within the margin. The second run, with 20 requests per side, prints HOLD: fewer than 200 requests on one side and exit 2. The A/A run took a second or two on this machine; every number here is from one run.7. Break the canary. Put the canary’s provider, and only that one, in 500 mode, then run the same comparison:
curl -s -X POST localhost:8594/_admin/mode -H 'Content-Type: application/json' -d '{"mode":"500"}'; echo
.venv/bin/python scripts/canary_compare.py --baseline http://127.0.0.1:8094 \
--canary http://127.0.0.1:8595 --rules canary_rules.json --product 5; echo "exit $?"
.venv/bin/python scripts/synthetic_loop.py --base http://127.0.0.1:8595 --every 1 --count 3 --alert-after 3{"mode":"500"}. The canary line reads error_rate=100.0% and statuses={502: 200} against statuses={201: 200} on the baseline, then ABORT: error rate 100.0% against baseline 0.0% (allowed +1.0%) and exit 1. The canary’s checkout turns the provider’s 500 into a 502, which counts as an error under your written rule. The synthetic loop against the canary fails three times with order returned 502 ... provider returned 500 and prints ALERT. The baseline is untouched, so the difference is attributable: only one side differs.Now the failure no error rate sees. Make the canary’s provider slow, with no errors. Each canary order waits for the provider, so 200 requests per side take a minute or two:
curl -s -X POST localhost:8594/_admin/mode -H 'Content-Type: application/json' -d '{"mode":"slow"}'; echo
.venv/bin/python scripts/canary_compare.py --baseline http://127.0.0.1:8094 \
--canary http://127.0.0.1:8595 --rules canary_rules.json --product 5; echo "exit $?"
.venv/bin/python scripts/synthetic_check.py --base http://127.0.0.1:8595
curl -s -X POST localhost:8594/_admin/mode -H 'Content-Type: application/json' -d '{"mode":null}'200 x 1 s (or 200 x 0.4 s with the shorter delay) because every canary order waits for the provider. It shows error_rate=0.0% on both sides and a canary p95 near the delay (in a check on this machine with the 0.4 s delay the canary’s p95 was 426 ms against a baseline of 5 ms), then ABORT: p95 426 ms over the limit of 108 ms and exit 1. The limit is the baseline’s p95 times 1.5, plus the 100 ms margin. The plain synthetic check against the same canary prints a PASS of about 0.4 s (about 1 s with the default delay), because both are under its 1,500 ms limit. The probe says the canary works. The comparison says it is much worse. The last command clears the mode.8. Leave the stable pair running. The break below needs it, with a valid data/flags.json. Stop the canary pair now with Ctrl-C in its two terminals. Step 9 stops the rest and cleans up.
Break the flag, not the code. With the stable pair running and a valid data/flags.json, overwrite the flag file with a half-saved edit, as if an editor or a deploy script had been interrupted. Restart nothing:
printf '{"new-charge-path": {"enabled": tr' > data/flags.json
curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8094/orders -H 'Content-Type: application/json' \
-H "Idempotency-Key: g1" -H "X-User-Id: user-7" -d '{"lines":[{"product_id":2,"qty":1}],"distance_km":3}'
.venv/bin/python scripts/synthetic_loop.py --every 1 --count 3 --alert-after 2Every order returns 500, with a plain-text body (Internal Server Error), not JSON. The synthetic loop prints order returned 500, and the reply was not JSON: 'Internal Server Error' three times and then ALERT, and exits 1. The file that was meant to be a safety switch has taken checkout down for everybody, new path or not. The lab’s synthetic_check.py reports a reply it cannot parse as an ordinary failure, so the probe and your loop both see a red check, not a traceback. Now write the test that should have existed. Add this to tests/integration/test_flags.py:
def test_a_half_written_flag_file_means_old_path_not_a_500(tmp_path, db, payments, clock):
flags = tmp_path / "flags.json"
flags.write_text('{"new-charge-path": {"enabled": tr')
client = TestClient(create_app(db, payments, clock, SearchIndex(), FlagStore(str(flags))))
assert path_taken(client, "k1", "user-7") == "old"It fails with json.decoder.JSONDecodeError. Fix it in checkout/api.py with a guard above create_app, and use it in create_order in place of the inline flags.is_enabled call:
def flag_on(flags: Optional[FlagStore], name: str, user: str) -> bool:
"""A flag that cannot be read is off. Never let the flag file take an endpoint down."""
try:
return bool(flags and flags.is_enabled(name, user))
except Exception:
return False path = "new" if flag_on(flags, "new-charge-path", user) else "old"The test passes (26 passed, 1 skipped, 1 deselected for the whole suite). Restart the stable API with the half-saved file still in place and an order now returns 201 with x-checkout-path: old. Notice the cost of failing closed: a flag at 100% that cannot be read drops everyone to the old path. For a kill switch that is the right way to fail, and you chose it on purpose.
9. Put the lab back. Stop the stable pair (Ctrl-C in each terminal) and confirm the four ports are free. Then remove everything you added and undo the edit to checkout/api.py:
lsof -i :8094 -i :8095 -i :8594 -i :8595
git checkout checkout/api.py
rm -f tests/integration/test_flags.py scripts/synthetic_loop.py scripts/canary_compare.py canary_rules.json
rm -f data/stable.sqlite data/canary.sqlite data/flags.json data/canary-flags.json
git status --short .
.venv/bin/pytest -q 2>&1 | tail -1lsof and git status --short . print nothing, and the suite ends 23 passed, 1 skipped, 1 deselected. The flag store and the synthetic check you started from are the lab’s own files, and you did not change them.Rachid's card top-up change is ready. Owoleaf has about 36,000 top-ups an hour at peak (illustrative) and a team on call. The change touches the redirect to the card issuer, which the provider sandbox cannot reproduce. A bad release costs real customers failed top-ups and support calls, but no money is lost: a failed top-up does not happen. What is your rollout plan?
- BOOK Canarying Releases Google SRE Workbook, chapter 16
The primary account of canarying: a partial, time-limited rollout compared with a control, and the advice to define acceptable behaviour for each metric in advance. It gives no sample-size statistics, which is why this chapter simulates them. Read it for the argument for deciding the thresholds before the release. Read: the whole chapter; it is short. Skip the pipeline diagrams on a first read.
- POST Feature Toggles (aka Feature Flags) Pete Hodgson, 2017
The standard taxonomy: release, experiment, ops and permissioning toggles, with their different lifetimes. Read the categories and the section on managing the toggle configuration. It explains why flag debt grows. Skip the implementation sketches.
- DOC OpenFeature: introduction OpenFeature project
A vendor-neutral standard for evaluating flags: the evaluation API, evaluation context, providers and hooks. Read it to see how the lab's two-line flag check looks when a team uses a real flag service. Skip the SDK pages for languages you do not use.
- DOC Argo Rollouts documentation Argo Project
How progressive delivery is automated on Kubernetes: stepwise canary, traffic shifting and analysis that queries metrics and rolls back on its own. Read the overview and the canary strategy pages. Skip the ingress-controller specifics unless you use one.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.