Courses / System Design Interview / Chapter 13
Module 3 · Building Blocks II: Monitoring, Caching and Messaging · Chapter 13 of 49
Monitoring Server-Side Errors
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Non-Functional Requirements: Availability, Scale, Latency and More, Building Blocks: The Parts Every Design Reuses and Distributed Monitoring: Metrics, Logs and Traces. Next up: Monitoring Client-Side Errors.
Part 1 · Health checks, heartbeats, liveness and readiness
Asking a server whether it is well
A load balancer, an orchestrator and a monitoring system all need the same answer many times a minute: is this server fit to be used? A health check is a small request that a server answers to say so, and the caller acts on the answer.
The simplest health check is an HTTP endpoint such as /healthz that returns status 200 when the process is running. A caller that gets 200 treats the server as alive. A caller that gets an error, or no answer within a timeout, counts one failure. Callers rarely act on a single failure. They wait for several failures in a row, because one dropped packet or one garbage-collection pause should not remove a good server. The core concepts chapter showed why: from outside, a slow server and a dead one look alike, so any rule that declares a server dead is a guess that can be wrong.
A heartbeat is the same idea turned around. Instead of being asked, the server sends a short message to a monitor at a fixed interval, such as every five seconds. The monitor declares the server missing when several beats in a row do not arrive. Health checks are pull, heartbeats are push, and the trade-offs are the ones from the monitoring chapter: a heartbeat that stops is a signal, but a monitor that is itself down sees nothing.
Liveness, readiness and startup
Kubernetes, the widely used container orchestrator, splits health into three questions, and the split is useful far beyond Kubernetes. Its documentation describes three kinds of probe, each with its own consequence when it fails.
| Probe | Question | If it fails |
|---|---|---|
| Liveness | Is the process stuck beyond repair? | The container is restarted |
| Readiness | Can it serve traffic right now? | It is removed from the service's endpoints, with no restart |
| Startup | Has it finished starting up? | Other probes wait; failing it kills the container |
A probe makes one kind of call: a command, a gRPC check, a TCP connection or an HTTP GET. For HTTP the probe succeeds on any status from 200 up to but not including 400.
The difference between liveness and readiness is the most common source of mistakes. A server that has lost its database connection is not broken. Restarting it will not bring the database back, and it will make things worse by throwing away warm caches and open connections. What it should do is stop receiving traffic until the database returns. That is a readiness failure. The Kubernetes page draws the same line: the liveness probe passes when the app itself is healthy, and the readiness probe also checks that each required back-end service is available. It also warns that a badly designed liveness probe can cause cascading failures. Picture a liveness check that calls the database: when the database fails, every instance fails liveness together and is restarted together, and the restarts add load just as the database comes back.
Two endpoints in code
This server has two endpoints. /healthz always returns 200 while the process runs. /readyz returns 200 only when a flag standing for the database is up, and 503 otherwise. The first block is the server, the second is the checker that flips the flag and calls both endpoints.
import threading import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, HTTPServer state = {"db_up": True} class App(BaseHTTPRequestHandler): def log_message(self, *args): pass def do_GET(self): if self.path == "/healthz": code = 200 # the process is running elif self.path == "/readyz": code = 200 if state["db_up"] else 503 else: code = 404 self.send_response(code) self.send_header("Content-Length", "0") self.end_headers()
health.py, part 1: the two endpoints and the server on port 55463
srv = HTTPServer(("127.0.0.1", 55463), App) threading.Thread(target=srv.serve_forever, daemon=True).start() def check(path): try: url = "http://127.0.0.1:55463" + path return urllib.request.urlopen(url).status except urllib.error.HTTPError as e: return e.code for label, db_up in [("db up", True), ("db down", False)]: state["db_up"] = db_up print(label, "healthz", check("/healthz"), "readyz", check("/readyz")) srv.shutdown()
health.py, part 2: flip the flag and call each endpoint
db up healthz 200 readyz 200 db down healthz 200 readyz 503
Python 3.12.10. The output is deterministic.
With the database up, both endpoints say 200. With it down, liveness still says 200 and readiness says 503. A load balancer using readiness would stop sending requests to this server and a restart-on-failure rule using liveness would leave it alone, which is exactly the behaviour you want. When the database returns, readiness goes back to 200 with no human action.
A server loses its connection to the database. Should that fail its liveness check?
- No. A restart does not repair the database and throws away warm state. It should fail readiness, so traffic stops until the database is back.
Why do callers usually wait for several failed checks in a row before acting?
- A single slow or dropped answer is common, and a slow server looks the same as a dead one. Several failures in a row make a wrong decision less likely.
Part 2 · Black-box probing
Looking from outside
Health checks come from inside the same network and ask the server about itself. A server can answer 200 on /healthz while users cannot reach it, because a certificate expired, a firewall rule changed or the DNS record points to the wrong address. Black-box probing, introduced in the monitoring chapter, closes that gap: a prober makes the same kind of request a user makes, from a place a user could be, and records the outcome.
A probe records at least three things: the status or the error, the time the whole request took, and the time it was made. From a stream of probes you compute two numbers that work as symptoms: the share of probes that succeeded, and a latency percentile. These match the error and latency signals from the monitoring chapter, measured as a user would measure them.
Probes come in two depths. A shallow probe fetches one URL and checks the status. A synthetic transaction walks through a user journey: log in as a test account, search, add an item to a cart, and check that the cart page shows it. Shallow probes are cheap and run every few seconds. Transactions are rich but touch many services, so they run less often and must use test accounts and test data so that they do not create real orders.
Where to probe from
A prober on the same machine as the server shares its network and its faults, so it proves little. Run probers in other places: another data centre, another cloud region, and a few outside networks. A failure seen from one place and not another is a clue. If all probers fail, the problem is probably the service. If one fails, it is probably the path to that one place.
| Probe from | Catches | Misses |
|---|---|---|
| Same machine | A crashed process | Anything on the network path |
| Same data centre | Service and load balancer faults | Internet routes, DNS, certificates seen by users |
| Other regions or networks | What users see, and regional problems | Faults only some devices hit |
Black-box probes see symptoms only while they are happening, as the monitoring chapter noted. A server that is 90% saturated but still answering looks perfect to a prober. That is why probing is paired with white-box measures in the next lesson. And a prober sees the whole path, so it cannot tell you which hop failed. When it fails, it opens the investigation rather than ending it.
Two servers and one prober
The program starts two local servers. web-a answers every request with 200 after a 10 ms delay. web-b answers every request with 500 after a 30 ms delay. The prober sends ten requests to each and prints how many succeeded and the median time. The code is split into the server setup and the prober.
import statistics import threading import time import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, HTTPServer def make(port, status, delay): class H(BaseHTTPRequestHandler): def log_message(self, *args): pass def do_GET(self): time.sleep(delay) self.send_response(status) self.send_header("Content-Length", "0") self.end_headers() srv = HTTPServer(("127.0.0.1", port), H) threading.Thread(target=srv.serve_forever, daemon=True).start() return srv servers = {"web-a": make(55464, 200, 0.01), "web-b": make(55465, 500, 0.03)} ports = {"web-a": 55464, "web-b": 55465}
probe.py, part 1: two servers on ports 55464 and 55465
def probe(port): start = time.perf_counter() try: url = f"http://127.0.0.1:{port}/" status = urllib.request.urlopen(url).status except urllib.error.HTTPError as e: status = e.code return status, (time.perf_counter() - start) * 1000 for name, port in ports.items(): results = [probe(port) for _ in range(10)] ok = sum(1 for s, _ in results if s < 500) med = statistics.median(ms for _, ms in results) print(f"{name}: {ok}/10 ok, median {med:.0f} ms") for s in servers.values(): s.shutdown()
probe.py, part 2: probe each ten times and summarise
web-a: 10/10 ok, median 11 ms web-b: 0/10 ok, median 32 ms
Python 3.12.10. The medians are about the sleep plus a little overhead and change a little each run.
The prober sees what a monitor needs: web-a is fine, and web-b failed ten out of ten. Notice the latency. The median of web-b is the time of its failures. Its errors came back quickly, so a latency average that mixed them with a healthy server's successes would look fine while every request to web-b failed. That is why the monitoring chapter said to keep the latency of failures apart from the latency of successes.
Notice also what the prober did not say: why web-b fails. For that you need the server's own logs and counters, the topic of the next lesson.
From failed probes to a page
A prober that raised an alert on a single failed request would wake someone for every dropped packet. Like the rule in the monitoring chapter, a probe alert needs a duration: a number of failed probes in a row, or a share of failures over a few minutes, from more than one location. The scene below shows the usual path. A prober checks two servers, one of them returns errors again and again, and an alert goes to the on-call engineer.
Watch for the prober: it asks both servers, as a user would
Read it as steps
A prober checks two servers. One keeps failing, so after three misses in a row it pages on-call.
The prober, not the servers, raised the alarm. That is the value of an outside view. If server 2 had crashed so hard that it could no longer report its own errors, this path would still have worked.
A prober running on the same machine as the service says all is well. What can it not catch?
- Anything between the user and the machine: DNS, certificates, firewalls and routes.
Part 3 · White-box error rates and saturation
What the server knows about itself
A prober sees a request succeed or fail. The server knows far more: which route, which status, how long each request took, how many requests were running at the same moment. White-box monitoring, from the monitoring chapter, uses those internals. For errors on a server, the standard source is the request log, one line for every request the server handled, or the counters derived from it.
From such a log you can compute three things, each of which answers a different question. The error count per minute says how many requests failed. The error ratio, failed requests divided by all requests, says how likely a user is to be hurt. And the in-flight count, the number of requests being worked on at once, says how full the server is.
Counts and ratios are not interchangeable. At 200 requests a minute, ten failures are 5%, a serious problem. At ten lakh requests a minute, ten failures are one in a lakh, which is noise. An alert on the count would fire on the busy service all day, and one on the ratio would be right both times. Prefer the ratio for alerting, and keep the count on the dashboard for scale.
Saturation: how full is it
Errors report damage after it has happened. Saturation, the fourth golden signal from the monitoring chapter, is how full a limited resource is, and it warns before the damage. The resources that matter depend on the service: processor time, memory, disk space, the number of worker threads, the number of open database connections, the depth of a queue.
Little's law from the non-functional chapter ties the in-flight count to latency and traffic. If 20 requests arrive per second and each takes 0.2 seconds, about 4 are in flight. If the same 20 requests per second each take 2 seconds, about 40 are in flight. A server with 50 worker slots is then nearly full, even though the traffic did not change. Slowness alone can saturate a server.
That is why saturation alerts target a number below the limit. A pool at 100% is already failing, because new requests wait or are refused. A team picks a threshold, say 80% of the slots in use, and alerts there, with enough time left to react.
Counting errors from a log
The program generates a ten-minute synthetic request log with a seeded random generator, about 20 requests per second. From minute 4 to the end of minute 5 a quarter of requests fail with status 503. From minute 5 onwards every request is slow, taking between 1 and 2.5 seconds instead of 0.2. The program prints requests, failures and the error ratio per minute, then the peak number of requests in flight.
import random from collections import defaultdict random.seed(5) # One synthetic request log: (start second, duration in s, status). log = [] for sec in range(600): # 10 minutes for _ in range(random.randint(18, 22)): bad = 240 <= sec < 360 and random.random() < 0.25 status = 503 if bad else 200 dur = random.uniform(1.0, 2.5) if sec >= 300 else 0.2 log.append((sec + random.random(), dur, status)) per_min = defaultdict(lambda: [0, 0]) for start, _, status in log: m = int(start // 60) per_min[m][0] += 1 per_min[m][1] += status >= 500 print("min requests 5xx error%") for m in sorted(per_min): n, bad = per_min[m] print(f"{m:>3} {n:>9} {bad:>4} {100 * bad / n:6.1f}") events = sorted([(s, 1) for s, d, _ in log] + [(s + d, -1) for s, d, _ in log]) now = peak = 0 for _, step in events: now += step peak = max(peak, now) print("peak requests in flight:", peak, "of 50 worker slots")
lograte.py: errors per minute and peak in-flight from a synthetic log
min requests 5xx error% 0 1198 0 0.0 1 1207 0 0.0 2 1217 0 0.0 3 1203 0 0.0 4 1202 291 24.2 5 1186 299 25.2 6 1207 0 0.0 7 1211 0 0.0 8 1202 0 0.0 9 1202 0 0.0 peak requests in flight: 49 of 50 worker slots
Python 3.12.10. The random seed is fixed, so this output repeats.
The error ratio is 0.0 for minutes 0 to 3, then 24.2% and 25.2% for minutes 4 and 5, then back to 0.0. A rule on the ratio would have fired in minute 4. Now look at the last line. Peak in flight is 49 of 50 worker slots. The errors stopped after minute 5, but the slowness did not, and the server came within one slot of being full. Looking at errors alone, you would have closed the incident at minute 6 while the server was still on the edge.
The two kinds of signal catch different failures. The error ratio caught a burst of explicit failures. Saturation caught slowness that never produced an error but would have, one slot later.
Part 4 · SLOs and error budgets
From signals to a target
The non-functional chapter defined SLIs, SLOs and SLAs. This lesson takes an SLO and turns it into a decision tool.
A common form of SLI is the share of good events: requests that succeeded and were fast enough, divided by all valid requests. An SLO then adds a target and a window: 99.9% of requests good, over a rolling 30 days. Google's reliability book argues that demanding 100% is neither realistic nor desirable. One practical reason is cost: each extra nine takes more effort and money, and a user's own phone and network fail more often than that anyway.
The gap between perfect and the target is the error budget: the amount of failure the SLO allows. The book describes it as the rate at which the SLO can be missed, and says that the gap between how much has been spent and what is allowed informs decisions such as whether it is safe to release a new version. A team with budget left can ship quickly. A team that has spent it slows down and fixes reliability. This turns an argument between speed and stability into a number both sides can read.
How much failure is 99.9%
The budget over a 30-day window follows from arithmetic. Thirty days is 43,200 minutes, and 0.1% of that is 43.2 minutes. Each extra nine divides it by ten. This is the table of nines from the non-functional chapter, read as a budget to spend.
WINDOW_MIN = 30 * 24 * 60 # a 30-day SLO window in minutes print("SLO error budget over 30 days") for slo in (0.99, 0.999, 0.9999, 0.99999): label = f"{slo * 100:g}%".ljust(9) print(label, f"{WINDOW_MIN * (1 - slo):7.2f} minutes") slo = 0.999 rps = 2000 # steady traffic, requests per second total = rps * WINDOW_MIN * 60 # requests expected in the window budget = total * (1 - slo) # failures the SLO allows # An incident: 12 minutes in which 40% of requests failed. failed = rps * 12 * 60 * 0.40 print(f"\nrequests in window {total:,.0f}") print(f"budget (failures) {budget:,.0f}") print(f"incident failures {failed:,.0f}") print(f"budget used {100 * failed / budget:.1f}%") print(f"burn rate {0.40 / (1 - slo):.0f}x")
budget.py: budgets for four SLOs and a worked incident
SLO error budget over 30 days 99% 432.00 minutes 99.9% 43.20 minutes 99.99% 4.32 minutes 99.999% 0.43 minutes requests in window 5,184,000,000 budget (failures) 5,184,000 incident failures 576,000 budget used 11.1% burn rate 400x
Python 3.12.10. Deterministic arithmetic.
The top table gives time-based budgets: 432 minutes for 99%, 43.2 for 99.9%, 4.32 for 99.99% and under half a minute for 99.999%. The bottom half converts to requests. At 2,000 requests per second a 30-day window holds 518.4 crore requests, so 99.9% allows 51.84 lakh failures.
The made-up incident is 12 minutes in which 40% of requests failed. That is 5,76,000 failures, 11.1% of the month's budget, in under a quarter of an hour. The burn rate is how fast the budget is being spent compared with a steady pace that would use exactly all of it by the end of the window. Here the error ratio of 40% is 400 times the allowed 0.1%, a burn rate of 400. A burn rate of 1 would end the window with the budget exactly spent.
The budget as arithmetic
The scene shows the calculation row by row, from the 30-day window to the budget at three targets.
Spend it on: risky releases (Out of budget: slow down and fix reliability)
Read it as steps
Each extra nine cuts the allowed failure by ten.
Treat the budget as something to spend on purpose: on releases, experiments, maintenance, and unplanned failures. A service that never spends any of it may be too cautious, because the SLO could be tighter or releases faster. A service that spends it all in week one has a reliability problem to fix before it ships anything else.
Teams write down in advance what happens when the budget runs out. This is an error budget policy. The example policy in Google's SRE workbook says that a service which has exceeded its budget over the previous four weeks halts all changes and releases, except urgent fixes and security fixes, until it is back within its SLO. Agreeing on the rule before an incident matters, because during one every team has a reason why its own release should be the exception.
| Term | Meaning |
|---|---|
| Error budget | The failure the SLO allows: 100% minus the target |
| Burn rate |
Part 5 · Burn-rate alerts and routing to on-call
Why a plain threshold alert is not enough
An alert that fires when the error ratio passes the SLO's limit has two problems. If the incident is mild, such as 0.2% errors against a 0.1% limit, it fires at once but there is no hurry: at that pace the budget lasts 15 days. If the incident is severe, it fires at once too, but the same alert cannot tell the difference. A page should say how fast the budget is going, because that decides how urgent it is.
Google's workbook section on alerting on SLOs builds on burn rate for this reason. A burn rate of 1 uses exactly the whole budget by the end of the window. A burn rate of 14.4 consumes it in 30 days divided by 14.4, a little over two days. Alerting on burn rate means alerting on how soon you will run out.
The workbook recommends several alerts at once, for a 99.9% SLO. Each has a burn rate, a long window and a short window, and the share of the budget consumed in the long window.
| Burn rate | Long window | Short window | Budget consumed | Action |
|---|---|---|---|---|
| 14.4 | 1 hour | 5 minutes | 2% | Page |
| 6 | 6 hours | 30 minutes | 5% | Page |
| 1 | 3 days | 6 hours | 10% | Ticket |
Long window
The short window
Each alert needs both windows to be above the burn rate before it fires. The long window gives confidence that real budget was spent. The short window, which the workbook suggests making one twelfth of the long one, confirms that the budget is still being spent now. It stops the alert from firing about an incident that has already ended, and makes it clear soon after the errors stop, rather than up to an hour later.
The program below runs four hours of made-up per-minute error ratios against a 99.9% SLO. The incident runs from minute 120 to minute 159 at 3% errors, which is a burn rate of 30. It evaluates the 1 hour rule at each minute, with and without the 5-minute confirmation.
SLO = 0.999 BUDGET = 1 - SLO PAGE = 14.4 # burn rate for the 1 h / 5 min rule # Error ratio for each minute of 4 hours. An incident runs from # minute 120 to minute 159 at 3% errors; otherwise 0.05%. ratio = [0.03 if 120 <= m < 160 else 0.0005 for m in range(240)] def burn(m, minutes): window = ratio[max(0, m - minutes + 1):m + 1] return sum(window) / len(window) / BUDGET def fires(m, short): long_ok = burn(m, 60) >= PAGE return long_ok and (burn(m, 5) >= PAGE if short else True) for short in (False, True): on = [m for m in range(240) if fires(m, short)] name = "1 h and 5 min" if short else "1 h only " print(f"{name}: first page at minute {on[0]}, " f"quiet again at minute {on[-1] + 1}")
burn.py: the page rule with and without the short window
1 h only : first page at minute 148, quiet again at minute 191 1 h and 5 min: first page at minute 148, quiet again at minute 162
Python 3.12.10. Deterministic arithmetic.
Both versions page at minute 148, 28 minutes after the incident began. That is the time it takes for 3% errors to push the 1-hour average up to the 1.44% threshold, which is 14.4 times 0.1%. The difference is at the end. The long window alone keeps firing until minute 191, 31 minutes after the incident ended, because the bad minutes take a while to leave the hour. With the short window the alert is quiet by minute 162. An engineer is not told about a problem that has gone.
From alert to a person
A firing alert is not yet a page. Prometheus sends alerts to Alertmanager, which does three jobs that keep the on-call engineer sane. Grouping combines alerts of a similar kind into one notification, so a large outage sends one message and not hundreds. Inhibition suppresses some alerts while others fire, such as muting every alert about a cluster while an alert says the whole cluster is unreachable. A silence mutes matching alerts for a set time, which is how you plan maintenance without noise. Alertmanager can run as a cluster for availability, and each Prometheus is pointed at all of them.
Routing uses the severity: the first two rows of the table go to a pager, the third to a ticket queue. A good page carries what the engineer needs at 3 am: which service, which SLO, the current burn rate and a link to the dashboard and to a runbook, a short document of first steps for this alert.
The alerting path can fail too. The rule engine can stop, a route can be deleted, or the pager integration can break, and then silence looks exactly like health. A common guard is an alert that always fires, often called a dead man's switch or watchdog. It is sent to a service outside your own systems, which expects it every few minutes and pages someone when it stops arriving. A prober run from outside, as in the second lesson, does the same job for the service itself.
A burn rate of 6 over 6 hours consumes what share of a 30-day budget?
- 6 x 6 hours = 36 hours of steady-pace budget out of 720 hours, which is 5%.
What does the short window add to a burn-rate alert?
- It confirms the budget is still being spent, which cuts false pages for incidents that have ended and makes the alert clear soon after errors stop.
Why does the slowest rule open a ticket and not page someone?
- A burn rate of 1 over days is a slow leak. It needs work in office hours, not a call at night.
All chapters · Previous: Distributed Monitoring: Metrics, Logs and Traces