Observability and safe deployments
Foundations F14. What to say when the interviewer asks "how would you know it's broken?" and "how do you ship changes safely?": metrics, logs and traces and what each is for, the four golden signals, SLIs, SLOs and error budgets, burn-rate alerts that page only when users hurt, canary releases with automated analysis, rolling and blue-green deploys with rollback-safe schema changes, feature flags and why config is a deploy, and incident response with blameless postmortems. Each idea is told as a story you'll remember, with a lab that prices one bad change in error budget.
Start here
Every design ends with the same two questions: "how would you know it's broken?" and "how do you change it without breaking it?" A Senior answer doesn't stop at "we'd add monitoring and CI/CD". It names the signals and what each is for, picks the few numbers that show users are hurting, turns the target into an error budget, pages a human only when that budget is burning fast, rolls every change out in stages with something comparing the new version against the old, keeps rollback cheap (including for database changes and config), and runs an incident with clear roles and a blameless review afterwards.
This page covers those eight ideas. They belong together because most outages start with a change: Google's SRE book puts it at roughly 70%, and its three answers are progressive rollouts, detecting problems quickly and accurately, and rolling back safely. Failure domains, health checks and disaster recovery were on the reliability page; overload and load shedding on the scaling page.
Opening a new metro line in Bengaluru
A new metro line is about to open across Bengaluru. Lakhs of people will use it every day, and the people running it get one chance at a first impression. Everything on this page happens between the last trial run and the first monsoon:
- The control room has a wall of numbers, a diary at every station, and the smart-card taps of every passenger. (metrics, logs and traces)
- The operations chief asks every station the same four questions each hour. (what to measure: the golden signals)
- The line promises trains on time 99 times out of 100, and treats the hundredth as a budget. (SLIs, SLOs and error budgets)
- The alarm in the chief's phone rings when passengers are stuck, not when a fan fails. (alerting on symptoms and burn rates)
- The line opens two stations first, while the old bus route still runs alongside. (canary releases with analysis)
- The bus keeps running until the metro has proved itself, and the smart card works on both. (rolling, blue-green, rollback and compatible changes)
- The platform doors are installed everywhere but switched on one station at a time. (feature flags, and config as a deploy)
- One evening a train stops in a tunnel, and one person takes charge. (incident response and blameless postmortems)
The metro is a teaching story; the companies, incidents and numbers cited on this page are real.
Metrics, logs and traces
Metrics are cheap numbers over time that tell you something is wrong; logs are detailed records of single events that tell you what happened; traces follow one request across services to show where its time went. Correlate them with a shared trace ID.
The wall, the diary and the smart card
The metro control room has three ways of seeing the line.
On the wall, big numbers update every few seconds: passengers entering per minute, trains per hour, average wait. Anyone can glance at it and see that something changed at 6:10 pm. But the wall can't say why.
At each station, the station master keeps a diary: "6:08 pm, gate 3 jammed, card reader rebooted." Detailed, but there are fifty diaries and nobody can read them all.
And there are the smart-card taps. When a commuter complains that her trip from Whitefield took 50 minutes, the control room follows her card: in at 6:02, through the interchange at 6:31, out at 6:52. Now they know the half hour went at the interchange, not on the train.
- Metrics: numeric measurements aggregated over time (counters, gauges, histograms), stored per time series. Cheap to keep for months, fast to query, perfect for dashboards and alerts. They lose detail: you see that p99 rose, not which request.
- Logs: one record per event, ideally structured (JSON with fields, not free text), with a request ID and trace ID. Rich detail, expensive at volume; sample or reduce noisy debug logs.
- Traces: one request's path through every service, as a tree of spans (each with a start, a duration and a parent). A trace ID is passed along in a header on every call, so all spans and logs for one request can be joined.
Cardinality is the cost to watch in metrics: each unique combination of label values is a new time series. Labels like status code and endpoint are fine; user ID or email will create millions of series.
Sampling keeps tracing affordable: keep a fixed share of traces (head sampling), or decide after the request finishes so slow and failed ones are always kept (tail sampling, which needs a buffer).
Use them in order: a metric alerts you, a trace shows which service is slow, its logs show why.
Google's Dapper paper (Sigelman et al., 2010) described tracing across Google's production fleet: each trace has a 64-bit trace ID, spans record parent IDs, and the first production version kept about one trace in every 1,024 requests, using at most 0.3% of one core in a worst-case test (as summarised by Adrian Colyer, 2015).
Today the trace ID usually travels in the W3C Trace Context header (a W3C Recommendation, November 2021), for example traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01: a version, a 16-byte trace ID, the caller's span ID and flags. OpenTelemetry's context propagation carries that context across process and network boundaries so traces, metrics and logs can be correlated.
Prometheus's naming guide warns that "every unique combination of key-value label pairs represents a new time series" and says not to use labels for "user IDs, email addresses, or other unbounded sets of values."
- More detail (logs at debug level, 100% of traces, per-user metrics) makes debugging easier but can cost more than the service it watches; keep metrics low-cardinality and put high-cardinality detail in sampled traces and logs.
- Head sampling is simple and cheap but drops most of the rare slow requests you care about; tail sampling keeps them but needs a collector that holds whole traces before deciding.
Every service emits RED metrics per endpoint, structured logs with the trace ID, and OpenTelemetry spans. We keep 1% of traces plus every error and every request over 1 s, using tail sampling at the collector. Metrics page us; traces and logs tell us why.
Adding user_id or order_id as a metric label so you can "drill down". It multiplies time series by the number of users and can take the metrics system down; that detail belongs in logs and traces.
What to measure: the four golden signals
For any user-facing service, watch latency, traffic, errors and saturation; measure latency as percentiles, separate the latency of failures, and measure what users experience, not what the machine feels.
Four questions at every station
The operations chief can't watch a thousand sensors. Every hour she asks every station four questions:
- How many people came through? (traffic)
- How long did they wait for a train? Not the average: how long did the unluckiest one in a hundred wait? (latency)
- How many couldn't get through, because the gate rejected their card or the platform was closed? (errors)
- How full is the platform right now, compared with what it can safely hold? (saturation)
A station that answers those four well is fine, whatever its fans and pumps are doing. A station where one of them looks wrong gets a phone call.
The four golden signals (Google's SRE book):
- Latency: time to serve a request. Use percentiles (p50, p99, p99.9), not averages, and keep failed requests separate: a fast error can make the average look better while users suffer.
- Traffic: demand, in the unit that matters (requests/s, messages/s, concurrent streams).
- Errors: failed requests, explicit (HTTP 500) and implicit (a 200 with the wrong content, or a response slower than promised).
- Saturation: how full the most constrained resource is (CPU, memory, connections, queue depth). It tells you trouble is coming before latency shows it.
Two shorthands interviewers like:
- RED for request-driven services: Rate, Errors, Duration.
- USE for resources (disks, CPUs, pools): Utilisation, Saturation, Errors.
Symptoms vs causes: "users are seeing errors" is a symptom; "the database CPU is at 95%" is a possible cause. Alert on symptoms, keep causes on dashboards for diagnosis.
Google's SRE book (2016) defines the four: latency is "the time it takes to service a request", traffic "a measure of how much demand is being placed on your system", errors "the rate of requests that fail", and saturation "how 'full' your service is". It adds that "a slow error is even worse than a fast error!", and that monitoring should answer two questions, "what's broken, and why?"
The same book's SLO chapter says Google "generally prefer[s] to work with percentiles rather than the mean": a p99 of 900 ms with a 50 ms average means one request in a hundred is eighteen times slower than typical, and a page that makes 30 backend calls hits at least one of those on about one load in four (1 − 0.99^30 ≈ 26%).
- Measuring at the load balancer or client is closest to what users feel but hides which service is at fault; per-service metrics locate the fault but can all look green while users fail. Keep both.
- Saturation metrics warn early but are noisy and environment-specific; use them for dashboards and capacity planning, rarely for pages.
For the feed service I'd watch the four golden signals per endpoint: requests/s, p50/p99 latency of successful requests, error rate including timeouts, and saturation as connection-pool and queue usage. Users' symptoms page us; causes like CPU stay on dashboards.
Showing average latency and CPU graphs as "monitoring". The average hides the slow tail users feel, and CPU at 90% may be fine while users get errors for a reason CPU never shows.
SLIs, SLOs and error budgets
An SLI is the measurement (share of good requests), an SLO is the target for it (99.9% over 30 days), an SLA is a contract with penalties; the gap between the SLO and 100% is an error budget that the team spends on change and protects when it runs low.
On time, 99 times out of 100
The metro promises the city: 99 trains in 100 will reach the terminal within two minutes of the timetable. Not 100 in 100. Nobody could keep that promise, and trying would mean never closing a track for maintenance or testing a new signal system.
So the hundredth train is a budget. Each month the line can afford about one late train in a hundred. Track work, a new timetable trial, a signal upgrade: each spends a little of it.
When a bad week uses up the month's budget, the chief stops all trials and upgrades until the line is back on time. When the budget is barely touched, the engineers can try more.
- SLI (indicator): a ratio of good events to all events, measured where users feel it. Availability: successful requests ÷ all requests. Latency: requests faster than 300 ms ÷ all requests.
- SLO (objective): the target over a window, usually 28 or 30 days: "99.9% of checkout requests succeed".
- SLA (agreement): a contract with consequences (credits, refunds). Keep the internal SLO tighter than the SLA so you notice before you owe money.
- Error budget = 1 − SLO. At 99.9% over 30 days that's 43 minutes of full outage, or 4.3 hours at 10% errors, or 0.1% of all requests.
- Error budget policy: what the team agrees to do when the budget is spent, typically freeze risky releases and put engineers on reliability until it recovers. It turns "move fast vs be stable" from an argument into a number.
Pick few SLOs (one or two per user journey), set them from what users need, not from what the system does today, and remember that each extra nine costs ten times less downtime.
The SRE book defines an SLI as "a carefully defined quantitative measure of some aspect of the level of service", an SLO as "a target value or range of values for a service level that is measured by an SLI", and an SLA as a contract "that includes consequences of meeting (or missing) the SLOs", and recommends "a tighter internal SLO than the SLO advertised to users".
Google's example error budget policy (SRE workbook, Appendix B, 2018) says that if the service exceeds its budget for the trailing four weeks, "we will halt all changes and releases other than P0 issues or security fixes until the service is back within its SLO", and that "if a single incident consumes more than 20% of error budget over four weeks, then the team must conduct a postmortem."
- A tighter SLO protects users but leaves less budget for change, so releases slow down; a looser one ships faster but users notice. Set it from user need and what the dependencies can support.
- A 30-day rolling window smooths out one bad day but forgives a slow, steady leak; a short window reacts faster but swings wildly. Most teams use 28–30 days.
Checkout's SLO is 99.95% of requests succeeding over 30 days, measured at the load balancer: that's a budget of about 22 minutes of full outage a month. If we burn it, the policy freezes feature releases until we're back inside.
Saying the SLO is 100%, or quoting the cloud provider's SLA as your availability. 100% leaves no room to change anything, and a provider's SLA is about their credits, not your users' experience.
Alerting on symptoms: burn rates, not thresholds
Page a human only when users are hurting and someone needs to act, and decide that by how fast the error budget is burning over two windows; everything else is a ticket or a dashboard.
The alarm that rings for passengers
In the first week, the chief's phone rang forty times a night. A ventilation fan in a substation ran hot. A card reader rebooted. A pump's pressure dipped. Each was real, none needed her, and by Thursday she had stopped looking.
Then a train stopped in a tunnel for 20 minutes, and the alarm that mattered was buried among the others.
So they changed the rule. Her phone rings only for things passengers feel: trains delayed, gates refusing cards, platforms closed. And not for one late train. It rings when lateness is eating the month's budget fast: a bad hour that, at this rate, would use up the month in two days. A slow drip that would use it up in a month goes to the morning meeting instead.
- Burn rate = how fast you're spending the error budget compared with spending it evenly over the window. Burn 1 uses the whole 30-day budget in 30 days; burn 14.4 uses 2% of it in an hour and all of it in about two days.
- Multi-window: fire only when both a long window (1 h) and a short window (5 min) are over the rate. The long window avoids paging on a 2-minute blip; the short one makes the alert stop soon after the problem does.
- Severity by speed: a fast burn pages; a slow burn opens a ticket for working hours.
Rules for pages:
- Every page should need a human and a decision; if the fix is a script, automate it.
- Alert on symptoms (the SLI), not causes (CPU, disk, a single pod restart).
- Each page links to a runbook and a dashboard.
- Track pages per shift and prune the noisy ones; alert fatigue is how real pages get missed.
Thresholds on raw error rate ("errors > 1% for 5 minutes") are a reasonable start, but they ignore the SLO: too twitchy for a 99% service, too slow for a 99.99% one.
Google's SRE workbook (ch. 5, "Alerting on SLOs", 2018) recommends, for a 99.9% SLO: page when 2% of the budget burns in 1 hour (burn rate 14.4, short window 5 minutes), page when 5% burns in 6 hours (burn 6, short window 30 minutes), and open a ticket when 10% burns in 3 days (burn 1, short window 6 hours). It notes that at 100% errors a 99.9% service exhausts a month's budget in 43 minutes.
The SRE book (ch. 6) states the rule behind it: "Every page should be actionable", and "if a page merely merits a robotic response, it shouldn't be a page."
- Faster alerts (short windows, low thresholds) catch problems sooner but page on blips and wear out on-call; slower ones are quieter but let more budget burn. Two windows and two speeds get most of both.
- SLO alerts watch the whole service, so a bug hitting 1% of traffic (one region, one app version) can stay below every threshold; pair them with per-operation SLIs and canary analysis.
We page on burn rate: 14.4 over 1 hour with a 5-minute check, or 6 over 6 hours with a 30-minute check. A burn of 1 over 3 days becomes a ticket. CPU, disk and pod restarts are dashboards, not pages, and every page links a runbook.
"Alert if CPU > 80% or any 5xx." It pages on things users don't feel and misses things they do, such as a bug that returns 200 with an empty cart.
Canary releases and automated analysis
Send a change to a small slice of production first, compare it automatically with an unchanged baseline on the metrics that matter, and only then widen it in stages; the canary must see enough traffic, for long enough, to show a real difference.
Two stations first
The metro doesn't open the whole line on day one. It opens two stations on a Sunday morning, with a few thousand passengers. The control room compares that stretch with the old bus route it replaces, at the same hours: are people getting through faster? Are more of them stuck at gates?
If two stations work for a week, it opens ten. Then the whole line.
The chief knows the trap. Open two stations for one hour on a quiet Sunday, see nothing go wrong, and declare victory? With that few passengers, a gate that rejects one card in a hundred might not have rejected anyone yet. A trial only means something if enough people have been through it.
- Canary: a partial, time-limited deployment to a small share of production (1–5% of servers, users or a cell), compared with the rest before going further.
- Baseline: compare against the same number of fresh instances running the old version at the same time, not against all of production; otherwise warm caches, traffic mix and time of day look like differences.
- Automated analysis: a judge compares a dozen key metrics (error rate, latency percentiles, saturation, business metrics like orders/min) and passes, fails (automatic rollback) or asks a human.
- Enough evidence: a 1% canary on a quiet service may need many minutes to show a 0.5% error difference. Bake time should come from traffic and the smallest bug you want to catch, not a habit.
- Stages (1% → 10% → 50% → 100%, or cell by cell, region by region) shrink the blast radius: a bad change hits a slice for a short time instead of everyone.
- What canaries miss: problems that only appear at full load, at another time of day, or after days (a slow memory leak, a certificate expiring). Pair them with SLO alerts and gradual later stages.
Google's SRE workbook (ch. 16, 2018) defines canarying as "a partial and time-limited deployment of a change in a service and its evaluation", warns that ending one "after receiving just a handful of queries doesn't provide a useful signal", and shows the payoff: a change that fails 20% of requests, sent to a 5% canary, raises the overall error rate only to 1%.
Google and Netflix open-sourced Kayenta for automated canary analysis (Google Cloud blog, 10 April 2018). It routes a small share of traffic, "for example 1%", to a canary and to a freshly deployed baseline, typically three instances each, compares chosen metrics with statistical tests, and scores the canary 0–100: success continues the deployment, failure triggers a rollback. The post notes that manual canary analysis "is prone to human bias and error".
- More stages and longer bakes catch more bugs before they spread but slow every deploy, good or bad; automating the analysis is what makes long pipelines bearable.
- Comparing against a fresh baseline is accurate but costs extra instances during each deploy; comparing against all of production is free but noisy.
Deploys go 1% → 10% → 50% → 100%, with Kayenta-style analysis against a fresh baseline at each stage: error rate, p99 latency and orders per minute. At 20K requests/s the 1% stage sees enough traffic to catch a 0.5% error increase in about a minute; a 200 requests/s service would need about 16 minutes, so bake times come from traffic. Failure rolls back automatically.
"We'll canary it" with no comparison and no numbers. A canary nobody measures is just a slower rollout; one that runs for five quiet minutes proves nothing.
Try it: How much budget does one bad change cost?
A bad version goes out. Pick how it rolls out and what is watching, and see who notices first (canary analysis or the SLO alerts), at what share of traffic, and how much of the month's error budget it burns before the rollback lands. The verdict flips across the presets: all at once hurts everyone, a canary with analysis catches it at 1%, a canary nobody compares passes unseen, a quiet service needs a longer bake, and a global config push spends almost the whole month in one go.
A checkout service at 20,000 requests/s with a 99.95% SLO. The new version fails 20% of requests (say, one payment method breaks). It goes to every server in one step.
| What we're sizing | Number | How we got it | So we decide |
|---|---|---|---|
| 1 · The error budget | |||
| Allowed failure a monthThe SLO isn't only a promise to users; the room under it is a budget the team spends on change. Every bad deploy draws on it. | 22 min | budget = (1 − 99.95%) × 43,200 min = 22 min of full outage (or twice as long at half the traffic failing) = 26M failed requests a month at 20K req/s | Measure each rollout by how much budget a bad change could cost, not by whether it "usually works". |
| 2 · Stage by stage | |||
| Who notices, and whenAnalysis compares the canary with a baseline, so it sees a bug on 1% of traffic. SLO alerts watch the whole service, so they only see it once enough traffic is affected. | a burn-rate page at 100% | 100% of traffic: analysis: no baseline left at 100%; burn 400 → page after 3.2 min → caught after 3.2 min canary needs ≈ 3² × (2 × 0.01% + 20%) ÷ (20%)² requests; burn = share × 20% ÷ 0.05%; page at 14.4 (1 h) or 6 (6 h), ticket at 1 (3 days) | There was only one stage: everyone had the bug before anything could notice. Add a small first stage. |
| 3 · The damage | |||
| Budget spent by one bad changeDamage = how much traffic sees the bug × for how long. Stages shrink the first; analysis, alerts and a fast rollback shrink the second. | 21% | at 100%: detect 3.2 min + decide 10 min + roll back 10 min = 23 min exposed = 4.6 min of full outage ≈ 5.6M failed requests; ÷ 22 min budget = 21% | Over 20% of the budget in one incident: Google's example policy requires a postmortem. Shrink the first stage. |
| 4 · The price of safety | |||
| A good change reaches everyone inStages cost time on every deploy, good or bad. That's why teams automate the analysis (no one has to watch) and ship small changes often. | seconds | 0 waits × 30 min = 0 | No wait, and no safety: every change, good or bad, reaches everyone at once. |
| 5 · Verdict for this rollout | |||
| What you get | Caught, but only after 100% of users saw itThe alert worked (3.2 min), but by then the whole fleet had the change, so every minute of detecting, deciding and rolling back hit 100% of traffic: 4.6 min of full outage, 21% of the month's budget. A 1% canary with analysis would have cut that to a sliver. Speed was the only thing bought: the change reached everyone at once. | ||
Try: on All at once, switch stages to 1 → 10 → 50%. On Canary, no analysis, turn analysis on. On Quiet service, set the wait to 20 minutes. On Global config push, set the rollback to 1 minute (a kill switch). Model: rounded teaching values; the burn-rate thresholds are the SRE workbook's for a 30-day SLO, the canary sample size is a z = 3 rule of thumb, each stage's alert clock starts fresh, and real bugs are often subtler (one region, one device type) than one error rate.
Rolling, blue-green and rollback-safe changes
Replace servers a few at a time (rolling) or switch all traffic between two full environments (blue-green); either way, rollback is only fast if the new code, the old code and the data can live together, so change schemas and APIs in expand, migrate, contract steps.
Keep the bus running
When the metro opens, the city doesn't cancel bus route 500D on the same day. For a few weeks both run. If the metro has a bad day, passengers walk back to the bus stop and nobody is stranded.
The smart card helps: it was changed months earlier so the same card works on both the bus and the metro. If the metro had needed a new card that buses can't read, going back to the bus would have meant handing out new cards to everyone, and there'd be no going back at all.
Only when the metro has carried people reliably through a full month does the city retire the bus route.
Ways to roll out code:
- Rolling: replace instances in batches behind the load balancer. Cheap (little spare capacity), but for a while two versions serve at once, and rollback is another rolling deploy.
- Blue-green: run the new version as a full second environment (green), switch traffic from blue to green in one step, keep blue warm for a fast switch back. Simple rollback, but double capacity during the switch, and a one-step switch hits everyone at once unless you shift weights gradually.
- Canary (previous section): a rolling or weighted rollout with analysis between steps.
Make rollback safe:
- Every version must work with the version before and after it, because both run at once: new fields optional, old fields still filled.
- Expand, migrate, contract for schema and API changes. Add the new column (expand), write both and backfill (migrate), switch reads, and only drop the old column after the old code is gone for good (contract). Each step ships separately and can be rolled back.
- Separate deploy from release: ship code dark and turn it on with a flag (next section).
- Roll back first, debug second: if a deploy correlates with the problem, undo it before finding the root cause.
Kubernetes Deployments roll out by default with maxSurge and maxUnavailable of 25% each (at most a quarter of pods extra, at most a quarter unavailable at once) and report a rollout as failed if it makes no progress within progressDeadlineSeconds, which "defaults to 600s" (Kubernetes API reference, checked Oct 2026). With readiness probes, a version that never becomes ready stalls the rollout instead of replacing every pod.
Danilo Sato's "Parallel Change" (martinfowler.com, May 2014) names the expand, migrate and contract phases and notes that most database refactorings follow it, with the migrate phase as "the transition period between the original and the new schema".
- Blue-green gives the fastest, simplest rollback but doubles capacity during deploys and switches everyone at once; rolling is cheap but mixes versions for longer.
- Expand-migrate-contract makes every step reversible but turns one change into three or four deploys spread over days, with code that handles both shapes in between.
We roll out with Kubernetes rolling updates behind canary analysis, so a version that fails readiness never spreads. Schema changes go expand, migrate, contract: add the column, dual-write and backfill, switch reads, and drop the old column a release later, so rolling back code never meets a schema it can't read.
Renaming or dropping a column in the same release that stops using it. Rolling back the code then fails against the new schema: there is no way back, only forward under pressure.
Feature flags, and config is a deploy
Feature flags separate deploying code from releasing a feature, so you can turn it on for 1% and off in seconds; but a flag flip, a config value or a rule update is a production change too, and needs the same stages and analysis as code.
Doors installed, switched off
Every platform on the new line has glass screen doors. They were installed weeks before opening, but switched off: open all the time, as if they weren't there.
On opening day the team switches them on at one station. They watch boarding times and stuck passengers for a few days, then switch on five more stations, then the rest. When one station's doors start jamming in the rain, the station master turns them off with a key on the platform, and trains keep running.
One lesson came the hard way. Someone once pushed a new door timing setting to every station at once from head office, "just a setting", and every door on the line started closing too early. A setting is a change, like any other.
Feature flags (toggles) come in four kinds (Pete Hodgson's taxonomy):
- Release flags: ship unfinished or risky code dark, turn it on gradually. Short-lived; remove within a week or two.
- Experiment flags: A/B tests, users bucketed by a hash of their ID.
- Ops flags (kill switches): turn off an expensive or failing feature under load.
- Permission flags: features for some customers or plans.
How they're served: evaluate in-process from a cached ruleset (no network call per check), updated by a push or poll; if the flag service is down, use the last known values (static stability).
Flags are debt: each one doubles the paths to test. Keep a count, add an owner and an expiry, delete them after release.
Config is a deploy: config, flags, rules, routing tables, ML models and content updates change behaviour in production just like code, and often reach every server in seconds. Version them, validate them, and roll them out in the same stages with analysis. Keep a separate, fast path for real emergencies.
On 2 July 2019, Cloudflare deployed a new WAF rule containing a regular expression that drove CPU to nearly 100% on every core handling HTTP traffic worldwide. Its blog postmortem notes that the procedure for rule changes "specifically allows it to be pushed globally", skipping the staged rollout used for its software; the outage ran from 13:42 to 14:09 UTC (27 minutes), ended by a global WAF kill switch. The fix promised staged rollouts of rules "while retaining the ability to do emergency global deployment for active attacks".
On 19 July 2024, a CrowdStrike content update (Channel File 291) supplied 21 input fields to a sensor that expected 20, crashing Windows machines; Microsoft estimated about 8.5 million devices, under 1% of Windows machines (TechCrunch, 20 July 2024). CrowdStrike's root cause summary (August 2024) committed to deployment rings and to letting customers control how such content is deployed.
Martin Fowler's site published Hodgson's taxonomy in October 2017, calling flags "inventory which comes with a carrying cost".
- Flags give instant rollback and gradual release without a deploy, but every flag is a branch in the code and a config change that can break production; keep them few and short-lived.
- Pushing config instantly everywhere is what you want during an attack and the worst thing for a routine change; keep two paths and make the fast one rare and deliberate.
The new pricing engine ships dark behind a release flag. We enable it for 1% of users by hashed user ID, then 10%, 50%, 100% with the same canary analysis as code; the flag is the rollback, effective in seconds. Rules and config go through the same staged pipeline, with a separate break-glass path for emergencies.
Treating a config or flag change as "not a deploy" and pushing it everywhere at once. Cloudflare in 2019 and CrowdStrike in 2024 are the examples interviewers know.
Incident response and blameless postmortems
When users are hurting, declare an incident early, give it one commander with separate people working the fix and talking to stakeholders, mitigate first (roll back, shift traffic) and find the root cause later, then write a blameless postmortem whose action items fix the system, not the person.
A train stops in a tunnel
At 7:40 one evening a train stops between two stations, with six hundred people on board. Within a minute the control room has a plan, because it has practised one.
One person, the duty controller, takes charge. She doesn't fix the train. She decides, and she keeps a running log on the screen.
A maintenance engineer works on the train. Only he touches it. A third person makes announcements: to the passengers on the train, to the stations, to the press. The first goal is not to find out why. It's to get people moving: a rescue train pushes the stalled one to the next platform.
A week later, the inquiry asks what happened, not who did it. If the driver had to choose between two manuals that disagreed, the fix is one manual, not a warning letter. A team that's afraid of the inquiry stops reporting near-misses, and then nobody learns anything.
Declare early. Make it an incident if users can see it, a second team is needed, or it isn't solved after an hour of focused work. Declaring is cheap; a late declaration is expensive.
Roles (as Google's SRE book describes them):
- Incident commander: owns the state and the decisions, assigns work, keeps the live incident doc. Doesn't debug.
- Operations: the only people changing production.
- Communications: regular updates to stakeholders and the status page.
- Planning: follow-ups, handoffs, tracking what was changed temporarily.
Mitigate before root cause. Roll back the last change, fail over, turn off the flag, shed load. Diagnosis can continue after users are fine.
Blameless postmortem:
- Write one for user-visible impact past a threshold, any data loss, an on-call rollback or traffic shift, a long resolution, or a monitoring failure (someone else noticed first).
- Include the timeline, impact in SLO terms, contributing causes (usually several), what went well, and action items with owners and dates.
- Blameless means assuming people acted reasonably with what they knew. Ask "what made this easy to get wrong?"
Measure the response: time to detect, time to mitigate, and how often detection came from users instead of alerts.
Google's SRE book (ch. 14, "Managing Incidents", 2016) lists the roles: the incident commander "holds the high-level state about the incident", "the operations team should be the only group modifying the system during an incident", and the communications lead "is the public face of the incident response task force". It says to declare an incident if a second team is needed, the outage is visible to customers, or the issue is unsolved "even after an hour's concentrated analysis", and calls a living incident document the commander's "most important responsibility".
Its postmortem chapter (ch. 15) defines blameless as focusing "on identifying the contributing causes of the incident without indicting any individual or team", with triggers including user-visible downtime beyond a threshold, "data loss of any kind", on-call intervention such as a "release rollback", and "a monitoring failure (which usually implies manual incident discovery)". Cloudflare's 2019 write-up is a public example: a minute-by-minute timeline, the regex explained in depth, and a list of process and engineering fixes with dates.
- Declaring often means some false alarms and process overhead; declaring late means confused, uncoordinated fixing while users wait. Most teams find the overhead cheap.
- Rolling back first can hide the evidence you need for the root cause; capture logs, traces and a heap dump on the way, but don't make users wait for the investigation.
If checkout's burn-rate page fires, the on-call engineer declares an incident, takes command and pulls in an ops engineer and a comms lead. Step one is rolling back whatever changed in the last hour. Then a blameless postmortem within five days, with action items tracked like any other work.
Describing incident response as "we'd debug it and fix the bug". Interviewers want mitigation first (rollback, failover, flag off), clear roles, and a review that changes the system.
Remember it
One line per idea. Read this the night before.
- The wall, the diary and the smart card: metrics say something's wrong, traces say where, logs say why; join them with a trace ID and keep user IDs out of metric labels.
- Four questions at every station: latency (as percentiles), traffic, errors, saturation; alert on symptoms, not causes.
- On time, 99 times out of 100: SLI is the measure, SLO the target, SLA the contract; 1 − SLO is a budget you spend on change.
- The alarm that rings for passengers: page on burn rate over two windows (14.4 in 1 h, 6 in 6 h); slow burns are tickets.
- Two stations first: canary on a slice, compare with a fresh baseline automatically, bake long enough for the traffic to show a difference.
- Keep the bus running: every version must work with its neighbours; expand, migrate, contract; roll back first, debug second.
- Doors installed, switched off: flags separate deploy from release; config is a deploy and goes through the same stages.
- A train stops in a tunnel: declare early, one commander, mitigate first, blameless postmortem with real action items.
Check yourself
Answer out loud, then open.
Users report that checkout is slow, but every service's dashboard is green. How do you find the problem?
Start from what the user saw and follow one request.
- Check the checkout SLI at the edge (load balancer or client): p99 latency and errors per endpoint, to confirm and size it.
- Pull traces for slow checkout requests (tail sampling keeps them) and look for the span that grew: a downstream call, a retry, a queue wait, or a gap between spans (time in a thread pool or GC).
- Read that service's logs for those trace IDs.
Green dashboards usually mean the averages are fine while the tail isn't, or each service is within its own limits while the chain adds up.
Say it metrics told us it's slow, the trace tells us where, the logs tell us why.
Your team wants to add customer_id as a label on the request-latency metric so they can see each customer's latency. What do you say?
Don't put it on the metric. Each unique label combination is a separate time series, so 2 million customers × 20 endpoints × a dozen histogram buckets is hundreds of millions of series, enough to slow or crash the metrics system.
Instead:
- Keep metrics low-cardinality (endpoint, status, region, maybe customer tier).
- Put customer_id in traces and structured logs, and query those for one customer.
- If a few big customers need dashboards, give them a dedicated metric for the top N only.
A service has a 99.9% availability SLO over 30 days. What is its error budget, and when should it page someone?
Budget: 0.1% of requests, or about 43 minutes of full outage in 30 days (43,200 × 0.001).
Page on burn rate (Google's SRE workbook):
- Burn 14.4 over 1 hour (2% of the budget in an hour), confirmed over the last 5 minutes.
- Burn 6 over 6 hours (5% of the budget), confirmed over 30 minutes.
- Burn 1 over 3 days (10%) opens a ticket instead.
At 100% errors the whole budget lasts 43 minutes, so the 1-hour page fires within about a minute; a 0.2% error rate (burn 2) never pages but shows up as a ticket.
You roll out a change to a 1% canary for 10 minutes, see no errors, and go to 100%. An hour later errors are up 0.5%. What went wrong, and how would you design the rollout?
The canary couldn't have seen it. To tell 0.5% extra errors from noise you need a couple of thousand requests on the canary; on a quiet service 1% of traffic may be only a few requests a second, so 10 minutes wasn't enough. And "no errors" was probably judged by eye, without a baseline.
Better:
- Compare the canary with a fresh baseline of the old version automatically, on error rate, latency and a business metric.
- Size the bake from traffic: requests needed ÷ canary requests per second.
- Go in stages (1% → 10% → 50% → 100%), with analysis at each, and roll back automatically on failure.
- Keep SLO burn-rate alerts as the safety net for what canaries miss.
You need to rename the column user_name to display_name in a busy table without downtime. How do you deploy it?
Expand, migrate, contract, each as its own deploy:
- Expand: add display_name (nullable). Deploy code that writes both columns and still reads user_name.
- Migrate: backfill display_name in batches; then deploy code that reads display_name.
- Wait until no running version reads user_name, and rollback to that old version is no longer needed.
- Contract: stop writing user_name, then drop it.
At every point, the current and previous code both work with the schema, so any deploy can be rolled back.
What's the difference between deploying and releasing, and why do feature flags matter for safe rollouts?
Deploying puts code on servers; releasing turns behaviour on for users. Flags split the two.
- Code ships dark, so deploys are small and routine.
- The feature is released gradually by flag (1%, 10%, 100%) and turned off in seconds without a redeploy.
- Ops flags act as kill switches under load.
The catch: a flag flip is itself a production change. Roll it out in stages with analysis, cache flag values so a flag-service outage changes nothing, and delete release flags within a week or two.
At 2 pm, error rates jump right after a deploy. Walk through the first 30 minutes.
- Minute 0–2: the burn-rate page fires; on-call declares an incident, takes command (or hands it to someone), opens the incident doc and channel.
- Minute 2–10: mitigate. The deploy correlates, so roll it back (or turn off its flag) without waiting for a root cause. Ops makes changes; one person posts updates.
- Minute 10–20: confirm recovery on the SLI, not just on the servers. If not recovered, look at the next suspect (a config change, a dependency).
- Minute 20–30: capture evidence (traces, logs, the diff), estimate impact in budget terms, tell stakeholders.
- After: a blameless postmortem with a timeline, contributing causes (why did the canary miss it?) and owned action items.
Say it roll back first, debug second.
Where you'll use this in the series
- Interview framework · turning "reliable" into an SLO and a budget
- Scaling and performance · percentiles, saturation and the slow tail
- Reliability and disaster recovery · health checks, failover and drills
- Idempotency, exactly-once and sagas · tracing a request across a saga
- Rate limiter · rolling out new limits safely, and 429 metrics
- Uber: from tap to pickup · SLO table, traces and the incident playbook
- Metrics and logging system (Datadog) · building the metrics, logs and traces pipeline itself
- Evaluation and guardrails platform · canarying a new model like a new binary (coming)
Sources
- Introduction ("roughly 70% of outages are due to changes in a live system"), Google SRE book, ch. 1 (2016)
- Dapper, a Large-Scale Distributed Systems Tracing Infrastructure, Sigelman et al., Google (2010)
- Dapper, a large-scale distributed systems tracing infrastructure, Adrian Colyer, the morning paper (Oct 2015)
- Trace Context, W3C Recommendation (Nov 2021)
- Context propagation, OpenTelemetry docs (checked Oct 2026)
- Metric and label naming, Prometheus docs (checked Oct 2026)
- Monitoring Distributed Systems, Google SRE book, ch. 6 (2016)
- Service Level Objectives, Google SRE book, ch. 4 (2016)
- Example Error Budget Policy, Google SRE workbook, appendix B (2018)
- Alerting on SLOs, Google SRE workbook, ch. 5 (2018)
- Canarying Releases, Google SRE workbook, ch. 16 (2018)
- Introducing Kayenta: an open automated canary analysis tool from Google and Netflix, Google Cloud blog (10 Apr 2018)
- Deployment v1 apps, Kubernetes API reference (checked Oct 2026)
- Parallel Change, Danilo Sato, martinfowler.com (May 2014)
- Feature Toggles (aka Feature Flags), Pete Hodgson, martinfowler.com (Oct 2017)
- Details of the Cloudflare outage on July 2, 2019, Cloudflare blog (Jul 2019)
- Root Cause Analysis, Channel File 291: executive summary, CrowdStrike (Aug 2024)
- Microsoft says 8.5M Windows devices were affected by CrowdStrike outage, TechCrunch (20 Jul 2024)
- Managing Incidents, Google SRE book, ch. 14 (2016)
- Postmortem Culture: Learning from Failure, Google SRE book, ch. 15 (2016)
- System design core concepts, Hello Interview (third party, used to cross-check interview expectations)
Checked October 2026. Theory and guidance come from Google's SRE book (2016) and SRE workbook (2018), the Dapper paper (2010), the W3C Trace Context recommendation (2021), the Prometheus, OpenTelemetry and Kubernetes docs, and martinfowler.com (2014, 2017); incidents are as their companies published them (Cloudflare July 2019, CrowdStrike August 2024, Microsoft's estimate as reported July 2024). The lab uses rounded teaching values and the SRE workbook's burn-rate thresholds.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.