Part 1 · Requirements: what a deploy must guarantee
What the system is for
A deployment system takes a change that has been built and tested and puts it on the machines that serve users, safely and in a way that can be undone. A change is a common way for a service to break, so the safety of this one system matters to every team.
The functional requirements are: register a build as a versioned artifact; describe a release, which is an artifact plus its configuration; roll it out to a set of machines in stages; watch the health of the new version while it rolls out; stop and roll back when it is unhealthy; and keep a record of who deployed what, where and when. Building and testing the code, provisioning machines and changing database schemas are out of scope. The last one deserves a warning, because it is where rollback stops being simple. A change that rewrites data is not undone by running the old code again, so schema changes need their own staged approach, in which a new column is added and used before the old one is removed.
Two words need a definition. A release is one version of one service, made of an artifact, the configuration it runs with, and metadata about who made it. A rollout is the act of moving machines from one release to another. The two are separate so that the same release can be rolled out to a test region first and to production later, and so that a rollback is a rollout to an older release and not a special operation.
Question to ask
Answer we assume
How many services and deploys?
300 services, about 3 production deploys each on a working day
How big is the largest fleet?
4,000 hosts across 8 regions
How big is one artifact?
About 150 MB compressed
How fast must a rollback be?
Minutes, and it must not need the new release to be healthy
Who may deploy?
The owning team, through review; an emergency path with extra logging
What if the deploy system is down?
Running services are unaffected; deploys wait or use a break-glass path
Non-functional requirements
Safety comes first, and it is stated as a limit on the blast radius, the share of users a bad change can touch before it is caught. A good target is that no single step exposes more than a small part of production, and that every step is followed by a check. Speed is a second goal that must not buy safety: a deploy that takes a day is acceptable if it is automatic and stops itself, and one that takes five minutes is not if it can break every region at once.
Repeatability means the same release gives the same result wherever and whenever it is deployed. The release engineering section of the site reliability engineering book puts it in terms of builds: a build should be hermetic, meaning insensitive to the libraries and other software installed on the build machine, and it should be reproducible, so that a release can be rebuilt from the same inputs. The next lesson turns that into a content hash. Auditability means that any running host can be traced to the build, the commit and the person behind it.
Availability of the deploy system itself is subtle. If the deploy system is down, nothing new ships, but nothing running breaks either, because the hosts already have their software. That makes it acceptable for the deploy system to be less available than the services it deploys, as long as an emergency path exists. The reverse dependency is dangerous: if a service needs the deploy system to be up in order to start or restart, the deploy system has become part of every service's availability. The design therefore keeps every host able to restart its current release with no network call to the control plane.
Rollback speed matters more than rollout speed. When a rollout goes wrong, minutes count, so the old artifact must still be on the host or in a nearby cache, and rolling back must not depend on the failing release. Teams that delete the previous artifact to save disk find out why this matters during an incident.
Sizing the system
The estimate looks different from the other cases, because the numbers are small and the interesting number is network traffic. Deploys a day, agent polling and artifact storage are modest. One big deploy is not.
python
services = 300
deploys_per_service_day = 3# production deploys on a working day
hosts_total = 20_000 # every host runs one agent
biggest_service_hosts = 4_000 # the largest single fleet
artifact_mb = 150# one build, compressed
poll_s = 15# an agent asks for work this often
regions = 8
deploys_day = services * deploys_per_service_day
print(f"deploys a day: {deploys_day:,} "
f"(about {deploys_day / 24:.0f} an hour on average)")
polls = hosts_total / poll_s
print(f"agent polls a second: {polls:,.0f}")
store_gb_day = deploys_day * artifact_mb / 1000
print(f"new artifacts a day: {store_gb_day:,.0f} GB "
f"({store_gb_day * 365 / 1000:,.0f} TB a year if all kept)")
Python 3.12.10. Assumptions of ours; change them and rerun. Save all the blocks of this lesson together as sizing.py.
python
one_deploy_gb = biggest_service_hosts * artifact_mb / 1000
print(f"one deploy to {biggest_service_hosts:,} hosts pulls "
f"{one_deploy_gb:,.0f} GB")
window_min = 10
gbps = one_deploy_gb * 8 / (window_min * 60)
print(f"over {window_min} minutes that is {gbps:,.1f} Gbit/s, "
f"or {gbps / regions:,.1f} Gbit/s in each of {regions} regions")
per_region = biggest_service_hosts / regions
print(f"hosts behind each regional cache: {per_region:,.0f}")
print(f"origin downloads with caches: {regions}, "
f"not {biggest_service_hosts:,}")
Continue in the same file: what one big deploy pulls across the network.
text
deploys a day: 900 (about 38 an hour on average)
agent polls a second: 1,333
new artifacts a day: 135 GB (49 TB a year if all kept)
one deploy to 4,000 hosts pulls 600 GB
over 10 minutes that is 8.0 Gbit/s, or 1.0 Gbit/s in each of 8 regions
hosts behind each regional cache: 500
origin downloads with caches: 8, not 4,000
Output of the script.
Nine hundred deploys a day is 38 an hour on average, so the control plane is tiny. A fleet of 20,000 agents polling every 15 seconds makes 1,333 requests a second, which is also small. The artifacts add 135 GB a day. The number to design around is the last group. A single deploy to the largest fleet pulls 600 GB, which is 8 Gbit/s if it completes in 10 minutes. Every host downloading from one store would congest it and slow the deploy, and the slowdown would hit during the very moment a fix is urgent. The third lesson puts a cache in each region, so the origin is read 8 times and not 4,000.
What the numbers decide
Three design decisions follow. First, the control plane can be a small, replicated service with an ordinary database, because the load is low and the data is a few tables of releases and rollouts. Second, artifact distribution needs its own design, with regional caches in front of the artifact store, because that is where the bytes go. Third, agents, the small programs that run on each host and install releases, should pull, as the sizing assumes: each asks the control plane what release it should run, which keeps the control plane from needing a connection to every host and works for hosts behind firewalls.
The rest of the chapter takes the problem in the order a release lives it. The second lesson builds and stores the artifact. The third lesson draws the whole system. The fourth lesson compares the ways to replace the old version. The fifth lesson spreads a rollout over time so that a bad change is caught while few users have it. The sixth lesson handles configuration and feature flags, which change behaviour without a deploy, and the failures of the deploy system itself.
Why is the deploy system allowed to be less available than the services it deploys?
Hosts already run their release and restart it without the control plane, so an outage only delays new deploys. The exception is a break-glass path for emergencies.
What is the number to design around in the sizing, and why?
The bytes of one big deploy: 600 GB to 4,000 hosts, or 8 Gbit/s over 10 minutes. The control-plane request rates are small.
Why are release and rollout separate ideas?
The same release can go to test and then production, and a rollback is just a rollout to an older release.
Part 2 · Artifacts and their store
An artifact is a sealed package
An artifact is the output of a build, packed into one file that can be copied to any host and run. It might be a container image, a tarball of binaries or a zip of code. What matters is not the format but three properties. It is immutable: once published, an artifact is never changed, and a fix is a new artifact. It is self-contained: it carries the libraries it needs, so a host does not install anything at deploy time. And it is identified by its content, not by a name someone typed.
The third property needs the most care. A version label such as 1.4.0 is a name, and a name can be reused by mistake or by an attacker: if someone rebuilds and publishes a different file under 1.4.0, hosts that fetch it get different code from hosts that fetched it yesterday. A content hash fixes this. Hash the bytes of the artifact with a function such as SHA-256, and use the digest as its address. The same bytes always have the same digest, and different bytes never do, in practice. A release that names an artifact by digest cannot be silently swapped.
This is what the release engineering section of the site reliability engineering book asks for when it says builds should be hermetic, and that the tools must give consistency and repeatability. If two builds of the same source produce byte-identical output, they get the same digest, and the second publish stores nothing new. If they differ in some irrelevant way, such as a timestamp inside the file, every build gets a new digest and the store fills with copies that are the same in every way that matters. The code in this lesson shows both outcomes.
Releases, manifests and verification
The artifact alone does not say how to run it. A release manifest is a small document that pins everything a rollout needs: the service name, a human-readable version, the artifact's digest, and the digest of its configuration. It is also immutable and content-addressed. Rolling out a release means telling each host which manifest to run. Rolling back means telling it an older manifest.
Hosts must not trust the network or the disk. When an agent fetches an artifact it computes the digest of what it received and compares it with the digest in the manifest. A mismatch means a corrupted transfer, a bad cache or tampering, and the agent refuses to install. The check is cheap, a hash over bytes the host has just read, and it turns every download into a verified one.
Configuration is part of the release. Keeping the configuration digest in the manifest means a configuration change is a new release that goes through the same stages as code. The release engineering section calls configuration changes a potential source of instability, and describes several ways to keep configuration alongside the code. Which way a team chooses matters less than the rule that it is versioned and reviewed like code.
Field
Example
Why it is there
service
orders
Which fleet this release is for
version
1.4.0
A label for people; not trusted by machines
artifact
sha256:c8e5...
The exact bytes to run
config
sha256:850f...
The exact configuration to run with
Building, storing and verifying, run
The code packs a small build directory into a tar archive. It first does this naively and then with the metadata normalised, so the archive depends only on file names and contents. Then it stores artifacts by digest and verifies one on fetch.
python
import hashlib, io, json, os, pathlib, tarfile, tempfile, time
def pack(src, normalise=True):
"""Bytes of a tar archive of src. Normalised: sorted names,
no times, no owners, one file mode."""
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tar:
for path in sorted(pathlib.Path(src).rglob("*")):
ifnot path.is_file():
continue
name = path.relative_to(src).as_posix()
info = tar.gettarinfo(str(path), arcname=name)
if normalise:
info.mtime, info.mode = 0, 0o644
info.uid = info.gid = 0
info.uname = info.gname = ""with open(path, "rb") as f:
tar.addfile(info, f)
return buf.getvalue()
def digest(data):
return"sha256:" + hashlib.sha256(data).hexdigest()
def make_tree(root, version_text):
(root / "app").mkdir(parents=True)
main = root / "app" / "main.py"
main.write_text(f"VERSION = {version_text!r}\n")
(root / "app" / "config.json").write_text('{"workers": 4}\n')
Python 3.12.10, standard library. Pack a build directory into one file whose bytes depend only on its contents. Save all the blocks of this lesson together as artifacts.py.
Without normalising, two builds of identical source gave different digests, because the archive records each file's modification time and the second build wrote its files a moment later. With normalising, the digests are equal. The unnormalised digests will differ on every run of this script, since they depend on the time it runs, so the printed values are one real run. A real change to the source, version 1.4.1, gave a different digest, as it should.
The store and the verified fetch
python
store = tmp / "store"
store.mkdir()
def put(data):
d = digest(data)
path = store / d.split(":")[1]
ifnot path.exists(): # the same bytes are stored once
path.write_bytes(data)
return d
def release_manifest(name, version, artifact, config):
return {"service": name, "version": version,
"artifact": artifact, "config": config}
art = put(pack(tmp / "build1"))
art_again = put(pack(tmp / "build2"))
cfg = put(b'{"timeout_ms": 800}\n')
print("stored files:", len(list(store.iterdir())),
"(two identical builds, one config)")
manifest = release_manifest("orders", "1.4.0", art, cfg)
shown = {k: v[:19] + "..."if v.startswith("sha256:") else v
for k, v in manifest.items()}
print(json.dumps(shown, indent=1))
Continue: a store keyed by digest, and a manifest that says what a release is.
python
def fetch_verified(wanted):
data = (store / wanted.split(":")[1]).read_bytes()
if digest(data) != wanted:
raise ValueError(f"digest mismatch for {wanted[:19]}...")
return data
print("fetch ok:", len(fetch_verified(manifest["artifact"])), "bytes")
victim = store / manifest["artifact"].split(":")[1]
blob = bytearray(victim.read_bytes())
blob[600] ^= 1# flip one bit on the "disk"
victim.write_bytes(bytes(blob))
try:
fetch_verified(manifest["artifact"])
except ValueError as e:
print("corrupted copy refused:", e)
Continue: the agent on a host checks the digest before it installs anything.
Two identical builds and one configuration left two files in the store: the second publish of the same bytes stored nothing new. The manifest is a few lines of JSON that name its parts by digest. Then the script flipped one bit in the stored artifact, as a failing disk might, and the verified fetch refused it. The error names the digest that was expected, so an operator can see which artifact is damaged.
In a real system the store is replicated, so a damaged copy is repaired from another, and old artifacts are kept for as long as a rollback might need them, with a rule such as the last 20 releases of each service. Garbage collection works by digest too: an artifact is deleted only when no release manifest still names its digest.
Why does an archive need its timestamps and owners removed before hashing?
Otherwise two builds of the same source differ in those fields and get different digests, so the store fills with copies and a rebuild cannot be recognised as the same release.
What does an agent do after it downloads an artifact, and what did the run show?
It hashes the bytes and compares with the digest in the manifest. A single flipped bit made the check fail, and the artifact was refused.
Why is a rollback a rollout to an older manifest and not a special operation?
The old manifest names the old artifact and configuration by digest, and both still exist, so the normal staged path can run it.
Part 3 · High-level design
The parts
The deployment system has five parts, and the sizing from the first lesson explains why they are split this way. The build system produces artifacts. The artifact store keeps them by digest and replicates them into every region, with a cache near each group of hosts. The orchestrator is the control plane: it holds the releases and rollouts, decides which hosts should run what, and moves a rollout from stage to stage. The agent on each host fetches and installs the release it is told to run and reports its state. The health pipeline collects metrics and alarms, which the orchestrator reads to decide whether a stage is healthy.
The agent pulls. Every 15 seconds or so it asks the orchestrator which release it should run. If that is not what it is running, it fetches the manifest and the artifact from its regional cache, verifies the digests, starts the new version beside the old one, checks that it is healthy, switches traffic and stops the old one. Then it reports the result. Pulling means the orchestrator holds no connection to each host and need not know a host's address. A host that was off during a rollout catches up when it returns, because it simply asks what it should be running.
The orchestrator keeps the desired state: for each fleet, which release each group of hosts should run. A rollout changes the desired state one stage at a time. This is a form of the control loop that Kubernetes and similar systems use, where one component records what should be true and others work to make it true. It makes the design dependable, because a crashed orchestrator or agent resumes from the recorded desired state and does not lose its place in a script.
Animated sceneA canary stops a bad release0:28
Watch for the canary catching a bad change before the fleet gets it
Read it as steps
A bad release reaches the canary, an alarm fires, and the rest of the fleet is spared.
In the scene the release reaches the canary and nothing else. The alarm, not a person, stops the rollout, and the rollback is a rollout of the old release to the hosts that took the new one. The later waves never started, so most of the fleet never ran the bad release.
Distribution and the load it creates
The scene shows the control loop. The next question is the bytes, which the estimate scene sums up.
Animated sceneWhat one deploy pulls0:16
Load in each region: ≈ 1 Gbit/s (the origin is read 8 times, not 4,000)
Read it as steps
One deploy to 4,000 hosts moves 600 GB, about 8 Gbit/s over ten minutes.
Regional caches change the picture. With a cache in each of 8 regions, the origin store is read once per region and each cache serves about 500 hosts over the local network. The origin sees 8 downloads and not 4,000. A cache that does not hold the artifact fetches it from the origin once and serves every later request from memory or disk, the read-through pattern of the cache chapter, with one simplification: the content is immutable, so there is nothing to invalidate. Content addressing makes this particularly clean, since a cached object is valid forever.
Very large artifacts and very large fleets add a second tier. Hosts in a cell can fetch pieces from each other, so each artifact crosses the cache's network once and then spreads inside the rack. We do not build that here, but it follows the same idea.
Part
Scales by
If it fails
Build system
More build workers
No new releases; running services unaffected
Artifact store
Replicas in every region
Caches serve what they hold; rollouts needing new bytes pause
Orchestrator
Replicated service, one leader per rollout
Rollouts pause; hosts keep running
Agent
One per host
That host stops updating; it keeps running its current release
Health pipeline
Sharded metrics store
Rollouts must fail closed: no signal means stop, not go on
The last row is the one that must be a rule: when the health pipeline cannot be read, the rollout stops. A rollout that continues when it has no signal has no safety at all.
Why does the agent pull the desired release instead of the orchestrator pushing to each host?
The orchestrator needs no connection or address for each host, and a host that was off catches up by asking when it returns.
What do regional caches change in the estimate?
The origin is read once per region, 8 times, and not 4,000 times, so the 8 Gbit/s of traffic stays inside each region.
What must a rollout do when it cannot read the health metrics?
Stop. A rollout with no signal cannot tell a healthy stage from a failing one.
Part 4 · Deep dive: rollout strategies
Rolling, blue-green and canary
A rollout strategy is the rule for replacing the old release with the new one. Three are standard, and the differences are about how much of the service holds the new release at once, and how fast you can go back.
A rolling update replaces hosts a few at a time. Capacity stays up because only a few hosts are out of service at once. Kubernetes' Deployment object makes this its default strategy, and its documentation gives two limits that control the pace. maxUnavailable, with a default of 25 percent, is how many pods may be unavailable during the update, rounded down. maxSurge, also 25 percent by default, is how many extra pods may be created above the desired number, rounded up. The two cannot both be zero. The code in this lesson computes the limits for several sizes.
A blue-green deployment keeps two complete environments. The live one, say blue, serves traffic while the new release is installed and tested in green, which receives no user traffic. When green is ready, traffic is switched over at once, and switching back is one more switch. It gives instant rollback and a clean test of the whole new environment, at the price of double the capacity during the change, and it moves all users at once, so a bug that testing missed reaches everyone immediately.
A canary deployment sends the new release to a small share of real traffic first and compares it with the rest. The canarying section of the site reliability engineering workbook defines the idea as a partial and time-limited deployment of a change in a service, together with its evaluation. The part that gets the change is the canary and the rest is the control. A canary exposes a bug to few users and gives a real-traffic test, but needs a good signal to compare, and it takes time.
Strategy
Exposure of a bug
Rollback
Extra capacity
Needs
Rolling
Grows as the update moves
Roll forward the other way; takes as long as the rollout
A little (maxSurge)
Health checks per host
Blue-green
All users at the switch
Switch back, seconds
A whole second environment
A way to test green and switch traffic
Canary
The canary share only
Remove the canary
Small
Metrics comparing canary and control
Rolling
Exposure of a bugGrows as the update moves
RollbackRoll forward the other way; takes as long as the rollout
Extra capacityA little (maxSurge)
NeedsHealth checks per host
Blue-green
Exposure of a bugAll users at the switch
RollbackSwitch back, seconds
Extra capacityA whole second environment
NeedsA way to test green and switch traffic
Canary
Exposure of a bugThe canary share only
RollbackRemove the canary
Extra capacitySmall
NeedsMetrics comparing canary and control
Judging a canary
The decision a canary makes is whether the new release is worse than the old one on the same traffic. Raw numbers cannot answer that, because a 1 percent error rate is fine if the old release also had 1 percent and a disaster if it had 0.1. The method is to compare the two groups over the same period. The canarying section of the workbook says the canary should be sizeable and last long enough to be representative, that the metrics should indicate problems in the service and be attributable to the change, and that a team should start from its service level indicators and use only a few metrics. Error rate and latency are the usual choices for a front end.
There is a statistical problem under the comparison. A small canary sees few requests, and with few requests a count of errors is noisy. Two groups with the same true error rate can differ by chance, and a group with a worse rate can look fine. A two-proportion z-test measures how many standard errors apart the two observed rates are. If the z score is above a limit, say 3, the canary's rate is unlikely to be that high by chance and the system rolls back. A larger canary or a longer one reduces the noise, which is why the guidance says sizeable and long enough.
The test has assumptions: it works best when the counts are not tiny, and the requests should be independent. A real system also checks a minimum request count before it decides, and treats too little traffic as inconclusive and not as healthy. The run on the next pages makes the point with a one-minute canary that misses a real fault.
Rolling limits, run
python
import math
def rolling_limits(replicas, surge_pct=25, unavailable_pct=25):
"""Kubernetes rounds maxSurge up and maxUnavailable down."""iftype(replicas) isnot int or replicas < 1:
raise ValueError(
f"replicas must be a positive integer: {replicas!r}")
if surge_pct < 0or unavailable_pct < 0:
raise ValueError("percentages cannot be negative")
if surge_pct == 0and unavailable_pct == 0:
raise ValueError("both limits are zero: the update is stuck")
surge = math.ceil(replicas * surge_pct / 100)
unavailable = math.floor(replicas * unavailable_pct / 100)
return surge, unavailable
for n in (1, 3, 4, 10, 100):
s, u = rolling_limits(n)
print(f"{n:>3} replicas: up to {n + s:>3} pods at once, "
f"at least {n - u:>3} available")
for bad in [(3, 0, 0), (0,), (2.5,)]:
try:
rolling_limits(*bad)
except ValueError as e:
print("refused:", e)
Python 3.12.10, standard library. How many pods can a rolling update replace at once? Save all the blocks of this lesson together as canary.py.
text
1 replicas: up to 2 pods at once, at least 1 available
3 replicas: up to 4 pods at once, at least 3 available
4 replicas: up to 5 pods at once, at least 3 available
10 replicas: up to 13 pods at once, at least 8 available
100 replicas: up to 125 pods at once, at least 75 available
refused: both limits are zero: the update is stuck
refused: replicas must be a positive integer: 0
refused: replicas must be a positive integer: 2.5
Output of the rolling limits.
The limits follow the documentation's rounding. For 10 replicas, 25 percent surge rounds up to 3, so up to 13 pods exist at once, and 25 percent unavailable rounds down to 2, so at least 8 are available. For 3 replicas the unavailable limit rounds down to zero, so all 3 stay available while a surge pod is added. The call with both limits at zero is refused, as the documentation says it must be, and so are a replica count of zero and one that is not a whole number.
Three canaries
The next blocks add the comparison and run three situations with 5 percent of traffic on the canary: a healthy change, a bad change watched for 10 minutes, and the same bad change watched for 1 minute.
python
import random
def serve(rnd, requests, error_rate):
return sum(rnd.random() < error_rate for _ in range(requests))
def z_score(err_c, n_c, err_k, n_k):
"""Two-proportion z-test: is the canary's error rate higher
than the control's?"""
for errs, n in ((err_c, n_c), (err_k, n_k)):
iftype(errs) isnot int ortype(n) isnot int \
ornot0 <= errs <= n or n == 0:
raise ValueError(f"bad counts: {errs!r} errors in {n!r}")
p = (err_c + err_k) / (n_c + n_k)
se = math.sqrt(p * (1 - p) * (1 / n_c + 1 / n_k))
return0.0if se == 0else (err_c / n_c - err_k / n_k) / se
def decide(err_c, n_c, err_k, n_k, z_limit=3.0, min_requests=500):
z = z_score(err_c, n_c, err_k, n_k)
if min(n_c, n_k) < min_requests:
return"WAIT", z # too little traffic is not healthyreturn ("ROLL BACK"if z > z_limit else"promote"), z
Continue: a canary compares error rates, canary against control.
Continue: three situations, with 5% of traffic on the canary.
text
case canary control z decision
healthy, 10 min 22/10000355/1900000.7 promote
bad (1.0%), 10 min 114/10000430/19000017.1 ROLL BACK
bad (1.0%), 1 min 9/100041/190004.2 ROLL BACK
Output of the three canaries.
The first row is a healthy change: 22 errors in 10,000 canary requests against 355 in 1,90,000 for the control, rates of 0.22 and 0.19 percent. The z score is 0.7, so it is promoted. The second row raises errors to 1.0 percent. Over 10 minutes the canary had 114 errors in 10,000 and the z score is 17.1, so it rolls back. The third row is the same bad change seen for 1 minute: 9 errors in 1,000 requests, a z score of 4.2, which only just clears the limit.
A canary that is too short
python
def miss_rate(minutes, trials=400, seed=1):
rnd = random.Random(seed)
n_c = int(traffic_per_min * 0.05 * minutes)
n_k = int(traffic_per_min * 0.95 * minutes)
missed = 0for _ in range(trials):
e_c = serve(rnd, n_c, 0.010)
e_k = serve(rnd, n_k, BASELINE)
missed += decide(e_c, n_c, e_k, n_k)[0] == "promote"return missed / trials
for minutes in (1, 3, 10):
print(f"bad change, {minutes:>2} min canary: promoted by mistake "
f"in {miss_rate(minutes):.1%} of 400 trials")
print("1 min, five seeds:",
[f"{miss_rate(1, seed=s):.1%}"for s in range(1, 6)])
Continue: how often does a short canary miss the bad change?
text
bad change, 1 min canary: promoted by mistake in 15.8% of 400 trials
bad change, 3 min canary: promoted by mistake in 0.0% of 400 trials
bad change, 10 min canary: promoted by mistake in 0.0% of 400 trials
1 min, five seeds: ['15.8%', '14.2%', '15.0%', '14.5%', '13.2%']
Output of the repeated trials.
The block repeats the one-minute test 400 times. It promoted the bad change by mistake in 15.8 percent of the trials. At 3 minutes and at 10 minutes it never did in 400 trials. The traffic share and error rates are our made-up numbers. Five seeds gave 13.2 to 15.8 percent at one minute, so read it as about 14 percent; an exact binomial calculation outside this script gives 14.4 percent at one minute and 0.06 percent at three. The cost of a too-short canary is a bad release that gets through, and the fix is a canary large enough and long enough for the fault you want to catch.
python
print("20 s canary:", decide(3, 333, 12, 6333)[0])
for bad in [(-1, 100, 3, 100), (101, 100, 3, 100), (0, 0, 0, 0)]:
try:
decide(*bad)
except ValueError as e:
print("refused:", e)
Continue: too little traffic, and counts that cannot be true.
text
20 s canary: WAIT
refused: bad counts: -1 errors in 100
refused: bad counts: 101 errors in 100
refused: bad counts: 0 errors in 0
Output of the checks.
A 20 second canary has 333 canary requests, below the minimum of 500, so the verdict is to wait, not to promote. The bad inputs are counts that cannot be true. Before the checks, a negative count was promoted and more errors than requests was rolled back with a z score of 13.9, as if they were data. A feed that sends nonsense must stop the rollout, not steer it.
For 10 replicas and the default 25 percent limits, how many pods may exist at once and how many must stay available?
Up to 13 pods (10 plus a surge of 3, rounded up) and at least 8 available (25 percent of 10 is 2.5, rounded down to 2 unavailable).
Why is a one-minute canary risky?
It sees few requests, so the error counts are noisy. In the run it let the bad release through in 15.8 percent of 400 trials, against none at 3 and 10 minutes.
What does blue-green give that a canary does not, and what does it cost?
Instant rollback by switching traffic back and a clean test of the whole new environment. It costs a second full environment and moves all users at the switch.
Part 5 · Deep dive: waves, bake time and rollback
Waves
A canary on one host is the smallest stage of a larger plan. A wave is a group of hosts that receive a release together, and a rollout is a series of waves of growing size. The point is that each wave is a test with a larger sample than the last, and the next one starts only after the current one has proved itself.
An Amazon Builders' Library article on automating safe, hands-off deployments, an engineering description of one company's practice, gives a worked example of a pipeline built this way, and we use its shape as our reference without claiming it describes any particular product. It begins with a one-box stage, where the change goes to a single host or a small slice of one region's traffic, and it says that stage typically serves at most ten percent of the requests of its region or availability zone. Next come waves of increasing size. Its first wave goes to a region with a low number of requests, which limits the damage of the first production deployment, and the pipeline in the article ends with a wave that covers the remaining regions. Inside a wave, the change goes to one availability zone, or cell, at a time.
Ordering waves by risk is the idea. A small, quiet region is cheap to harm and is likely to show crashes and gross errors. A large, busy region has a different kind of exposure and shows problems that appear only under load, such as a slow memory leak or a lock that is contended only at volume. Starting small and quiet and moving to large and busy finds the cheap faults cheaply and the expensive ones with the safeguards of every earlier stage in place.
A good wave plan is also about cells, units of the service that fail independently, such as a region, an availability zone or a shard of customers. A bad release in one cell must not spread to another through the rollout. The plan therefore does not deploy to two cells that share a dependency in the same wave unless the earlier waves have shown the release is safe.
Bake time and automatic rollback
Bake time is the minimum time a wave must stay healthy before the rollout may go on. A fast bug shows within seconds, but many faults need time: a leak takes hours to exhaust memory, a nightly job runs once a day, a cache fills slowly. The same article gives the minimums for its pipeline, and they show how seriously the idea is taken. It says to wait at least one hour after each one-box stage, at least 12 hours after the first regional wave, and at least two to four hours after each of the remaining regional waves. Those numbers belong to that pipeline. Ours are our own choices in the same spirit: 1 hour, 12 hours, then 3.
During the bake, the rollout watches an alarm. The article says the deployment is rolled back automatically if the team's high-severity aggregate alarm goes into the alarm state. The design rule is that the rollback is automatic: a person is told and may override, but the system acts first, since a faulty release can do a great deal of damage in the minutes a person needs to wake up. The alarm should be built from the same service level indicators as the canary comparison, as the server errors chapter described, and may use the fast burn-rate alerts from that chapter.
Rollback itself is a rollout of the previous release, so it can be slow if the fleet is large. A rollback of 421 hosts to the old release is much quicker than a rollback of 4,000. That is another benefit of the early stages: a rollback that touches few hosts is fast. Teams also give the rollout a kill switch that freezes all rollouts, used when something unrelated is wrong, such as an outage in a dependency, and a new release would only confuse the diagnosis.
Animated sceneLife of a rollout0:30
Watch for an alarm during a bake sending the whole rollout back
Read it as steps
A rollout bakes, is promoted wave by wave, and rolls back when an alarm fires.
The scene has two end states. A rollout ends Done when every wave is promoted, or Rolled back when the old release is restored. The state table is what stops a late next wave event from starting another wave after an alarm has fired, which is why the scene shows that event being refused.
A wave plan, run
The code models a plan for a fleet of 4,000 hosts. It runs a change that fails only under the load of the large region, which the early stages do not see. It then repeats the same fault with the change pushed everywhere at once, and tests the plan validator.
python
from dataclasses import dataclass
@dataclass
class Stage:
name: str
hosts: int # hosts that get the new build in this stage
bake_h: float # hours the stage stays quiet before the next# Our plan, with bake times in the spirit of one published pipeline:# at least 1 h after a one-box, 12 h after the first regional wave,# 2 to 4 h after the later waves (we take 3).
PLAN = [
Stage("one-box (small region)", 1, 1.0),
Stage("wave 1: small region", 20, 12.0),
Stage("wave 2: large region", 400, 3.0),
Stage("wave 3: three regions", 1200, 3.0),
Stage("wave 4: the rest", 2379, 0.0),
]
FLEET = sum(s.hosts for s in PLAN)
baking = sum(s.bake_h for s in PLAN)
print("fleet:", FLEET, "hosts; baking time in total:", baking, "hours")
Python 3.12.10. A wave plan: where the change goes and how long each stage must stay quiet. Save all the blocks of this lesson together as waves.py.
python
def roll_out(plan, fails_at, alarm_after_h=1.0):
"""The bug shows in the stage named fails_at, and the alarm
fires alarm_after_h hours after that stage starts."""
exposed, clock, log = 0, 0.0, []
for stage in plan:
exposed += stage.hosts
log.append(f"t={clock:5.1f} h deploy {stage.name:<22} "
f"({exposed:>4} hosts)")
if stage.name == fails_at:
clock += alarm_after_h
log.append(f"t={clock:5.1f} h ALARM in bake: "
f"roll back {exposed} hosts")
return exposed, clock, log
clock += stage.bake_h
log.append(f"t={clock:5.1f} h done")
return exposed, clock, log
exposed, clock, log = roll_out(PLAN, fails_at="wave 2: large region")
print("\n".join(log))
print(f"hosts that ran the bad build: {exposed} of {FLEET} "
f"= {exposed / FLEET:.1%}")
Continue: a change that only fails under the load of the large region.
text
fleet: 4000 hosts; baking time in total: 19.0 hours
t= 0.0 h deploy one-box (small region) ( 1 hosts)
t= 1.0 h deploy wave 1: small region ( 21 hosts)
t= 13.0 h deploy wave 2: large region ( 421 hosts)
t= 14.0 h ALARM in bake: roll back 421 hosts
hosts that ran the bad build: 421 of 4000 = 10.5%
Output of the staged rollout.
The total of the minimum bake times is 19 hours, so even a clean rollout takes at least that long. That is the price of safety. The bad change passed the one-box and the first wave, as designed, because it only fails under the large region's load. It was caught in wave 2, one hour into the bake. By then 421 hosts, 10.5 percent of the fleet, had run the bad build, and all 421 were rolled back.
Continue: the same bug with the change pushed everywhere at once.
python
def validate(plan):
ifnot plan:
raise ValueError("a plan needs at least one stage")
for s in plan:
iftype(s.hosts) isnot int or s.hosts <= 0or s.bake_h < 0:
raise ValueError(f"bad stage {s.name!r}: hosts={s.hosts}, "
f"bake_h={s.bake_h}")
if plan[0].hosts > 0.01 * sum(s.hosts for s in plan):
raise ValueError("first stage must be at most 1% of the fleet")
returnTrue
print("our plan ok:", validate(PLAN))
bad_plans = [[Stage("bad", 0, 1.0)], [Stage("bad", 5, -1.0)],
[Stage("big first", 500, 1.0), Stage("rest", 500, 0.0)],
[], [Stage("part", 12.5, 1.0)]]
for bad in bad_plans:
try:
validate(bad)
except ValueError as e:
print("refused:", e)
Continue: refuse a plan that is badly formed.
text
all at once: 4000 of 4000 hosts = 100.0%
our plan ok: True
refused: bad stage 'bad': hosts=0, bake_h=1.0
refused: bad stage 'bad': hosts=5, bake_h=-1.0
refused: first stage must be at most 1% of the fleet
refused: a plan needs at least one stage
refused: bad stage 'part': hosts=12.5, bake_h=1.0
Output of the comparison and the checks.
Pushed everywhere at once, the same fault reaches all 4,000 hosts, 100 percent. The staged plan limited the blast radius to a tenth. The validator refuses stages with no hosts or a negative bake, a first stage larger than 1 percent of the fleet, an empty plan and a fractional host count. The 1 percent figure is our own rule, not a published one.
Why do waves go from small, quiet regions to large, busy ones?
Cheap faults show in a small region at low risk, and load-dependent faults need a busy region, which is reached only after the earlier stages have passed.
In the run, how many hosts ran the bad build and how many would have if it had gone everywhere at once?
421 of 4,000, which is 10.5 percent, against all 4,000 or 100 percent.
Why must the rollback be automatic and not wait for a person?
A faulty release can do large damage in the minutes a person needs to respond, so the system acts when the alarm fires and tells people.
Part 6 · Config, feature flags and failures
Configuration is a deploy too
Changing a setting can break a service as completely as changing code, and often faster, because a setting is read by every host the moment it arrives. The release engineering section of the site reliability engineering book calls configuration changes a potential source of instability. The first rule is therefore to treat configuration as part of the release: versioned, reviewed, and rolled out in waves, with the digest in the manifest as the second lesson showed.
The second rule is for settings that change often or must change in seconds. A feature flag is a setting that turns a behaviour on or off at run time for a chosen share of users, without a deploy. Flags separate two moments that used to be one: shipping the code, which can happen at any time with the new behaviour off, and releasing the behaviour, which is a change of a flag that a product team controls and can reverse in seconds. A flag that is off is also a kill switch for a feature that misbehaves.
The usual way to roll a flag out to a percentage is to hash the user into a bucket. Hash a string made of the flag name and the user id with SHA-256, take the result modulo 100, and treat the user as in the rollout if the bucket is below the percentage. This has three useful properties. It is stateless, since nothing is stored per user. It is sticky, since the same user always gets the same bucket, so their experience does not flicker. And raising the percentage only adds users, so the people who saw the feature at 10 percent still see it at 20. Including the flag name in the hash makes different flags independent, so the same unlucky users are not in every experiment.
Flags, run
python
import hashlib, json
def bucket(flag, user_id):
"""Same flag and user always give the same bucket, 0 to 99."""
h = hashlib.sha256(f"{flag}:{user_id}".encode()).digest()
return int.from_bytes(h[:8], "big") % 100def enabled(flag, user_id, percent):
iftype(percent) isnot int ornot0 <= percent <= 100:
raise ValueError(f"percent must be an integer 0 to 100: "
f"{percent!r}")
ifnot isinstance(user_id, str) ornot user_id:
raise ValueError("user id must be a non-empty string")
return bucket(flag, user_id) < percent
users = [f"u{i}"for i in range(1_00_000)] # one lakh made-up idsfor pct in (0, 1, 10, 50, 100):
n = sum(enabled("new-checkout", u, pct) for u in users)
print(f"{pct:>3}% rollout: {n:>7,} of {len(users):,} users "
f"= {n / len(users):.2%}")
Python 3.12.10. Hash a user into one of 100 buckets, per flag. Save all the blocks of this lesson together as flags.py.
python
at_10 = {u for u in users if enabled("new-checkout", u, 10)}
at_20 = {u for u in users if enabled("new-checkout", u, 20)}
print("everyone in the 10% is still in the 20%:", at_10 <= at_20)
other = {u for u in users if enabled("dark-mode", u, 10)}
print(f"two independent 10% flags overlap on "
f"{len(at_10 & other):,} users (chance: about "
f"{len(at_10) // 10:,})")
for bad in (-1, 101, 12.5, "10", True):
try:
enabled("new-checkout", "u1", bad)
except ValueError as e:
print("refused:", e)
try:
enabled("new-checkout", "", 10)
except ValueError as e:
print("refused:", e)
Continue: raising the percentage only adds users, and flags are independent.
text
0% rollout: 0 of 100,000 users = 0.00%
1% rollout: 1,018 of 100,000 users = 1.02%
10% rollout: 10,119 of 100,000 users = 10.12%
50% rollout: 50,298 of 100,000 users = 50.30%
100% rollout: 100,000 of 100,000 users = 100.00%
everyone in the 10% is still in the 20%: True
two independent 10% flags overlap on 994 users (chance: about 1,011)
refused: percent must be an integer 0 to 100: -1
refused: percent must be an integer 0 to 100: 101
refused: percent must be an integer 0 to 100: 12.5
refused: percent must be an integer 0 to 100: '10'
refused: percent must be an integer 0 to 100: True
refused: user id must be a non-empty string
Output of the bucket runs.
Over one lakh made-up users, a 10 percent rollout enabled 10,119 users, 10.12 percent, and a 50 percent rollout 50,298. The numbers are close to the target and not equal, because hashing spreads users evenly in the long run and not exactly. The 10 percent group is a subset of the 20 percent group. Two independent 10 percent flags overlapped on 994 users, near the 1,011 that chance alone would give, which shows the flags do not choose the same people. Percentages that are not integers from 0 to 100 are refused, including the string 10, which would otherwise fail later with a confusing comparison error, and True, which Python would otherwise count as 1 percent. An empty user id is refused too, since every such user would share one bucket.
python
FLAGS = json.loads("""{
"version": 17,
"flags": {
"new-checkout": {"percent": 10, "killed": false},
"dark-mode": {"percent": 100, "killed": false}
}}""")
def is_on(config, flag, user_id):
f = config["flags"].get(flag)
if f isNoneor f["killed"]:
returnFalse# unknown or killed: the old behaviourreturn enabled(flag, user_id, f["percent"])
print("v17, u5 sees new-checkout:", is_on(FLAGS, "new-checkout", "u5"),
"| unknown flag:", is_on(FLAGS, "no-such-flag", "u5"))
before = sum(is_on(FLAGS, "new-checkout", u) for u in users)
FLAGS["version"] = 18
FLAGS["flags"]["new-checkout"]["killed"] = True
after = sum(is_on(FLAGS, "new-checkout", u) for u in users)
print(f"users on at v17: {before:,}; after the kill switch (v18): "
f"{after:,}")
Continue: a flag is configuration, so it is versioned and has a kill switch.
text
v17, u5 sees new-checkout: False | unknown flag: False
users on at v17: 10,119; after the kill switch (v18): 0
Output of the config run.
The configuration is a versioned document. An unknown flag is off, which is the safe, old behaviour, and a killed flag is off for everyone. In the run, the kill switch took 10,119 users to none in one configuration change, with no deploy. The flag configuration must itself go out in waves and be checked, since a bad flag file is a bad release.
Failures of the system itself
The deploy system can fail in ways that matter. The table lists the main ones and what the design does. The principle is that the deploy system must fail closed, by stopping rollouts, and that it must never be a reason a running service stops.
Failure
What happens
What the design does
Orchestrator down
Rollouts pause
Hosts keep running; a standby takes over from the recorded desired state
Health pipeline unreadable
No signal for the bake
The rollout stops and pages the owner; it never continues without a signal
Artifact corrupt or missing
A host cannot install
Digest check refuses it; agent retries from another cache; the rollout counts the host as failed
Agent crashes mid-install
A host is half updated
The agent installs beside the old release and switches only after a health check, so it resumes on restart
The bad release also breaks the rollback
Old release will not start
Old artifacts and configuration are kept; test the rollback path as part of every release
A schema change cannot be undone
Old code cannot read new data
Expand first, migrate, then contract in a later release; never one step
The fifth row is worth stating again, because it is the failure that surprises teams. A rollback runs the old release, and the old release must still work with whatever the new release did to shared data. That is a property of the change and not of the deploy system, and the deploy system can only enforce the process: a release that includes a destructive data change needs a separate approval and a longer bake.
Trade-offs and extensions
Several choices could go the other way. Speed or safety: more waves and longer bakes catch more faults and make a deploy take a day, and teams with very frequent deploys use smaller waves for low-risk changes and keep the long plan for risky ones. Push or pull: pushing from the orchestrator is simpler to reason about and gives immediate rollouts, and pulling scales better and survives hosts that were off. Automatic or manual promotion: automatic promotion is faster and removes toil, and a manual approval gate is reasonable for a service that is a single point of failure for others. One canary or per-cell canaries: a per-cell canary catches faults that depend on a cell's configuration and costs more stages.
Extensions reuse the same parts. Deployments to mobile apps are different, because users, not the company, decide when to update, and a bad build cannot be pulled back, so staged rollout through the app store and server-side flags carry the safety. Database migrations are a rollout of their own. Infrastructure changes, such as a new load balancer rule, follow the same waves and bakes. Progressive delivery ties flags to the rollout system so that a flag's percentage rises only while the alarms stay quiet.
Why is a feature flag useful even when a deploy system with waves exists?
It separates shipping code from releasing behaviour, and a flag can be changed and reversed in seconds, so it works as a kill switch.
In the run, what happened to the users when the kill switch was set?
The 10,119 users with the new checkout dropped to none in one configuration change, with no deploy.
Why must a rollout fail closed when the health pipeline cannot be read?
Without a signal, a healthy stage cannot be told from a failing one, so continuing would remove the safety the stages provide.