Courses / System Design Interview / Chapter 12
Module 3 · Building Blocks II: Monitoring, Caching and Messaging · Chapter 12 of 49
Distributed Monitoring: Metrics, Logs and Traces
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Non-Functional Requirements: Availability, Scale, Latency and More and Building Blocks: The Parts Every Design Reuses. Next up: Monitoring Server-Side Errors.
Part 1 · Why monitor, and the four golden signals
What monitoring is for
A service that handles crores of requests a day will break somewhere, and the only open question is who finds out first. Monitoring is collecting numbers and events from a running system so that you notice a problem before your users report it.
The reason it needs its own chapter is that a distributed system fails in pieces. One server out of forty can be slow, one route can return errors, one region can lose a database replica, and the other thirty-nine servers keep the home page looking fine. As the core concepts chapter explained, a partial failure does not announce itself. Something has to look.
Google's site reliability book says monitoring must answer two questions: what is broken, and why. The first is the symptom, what a user or a caller sees, such as checkouts failing. The second is the cause, such as a database running out of connections. The book calls the difference between them one of the most important parts of writing monitoring that has a strong signal and little noise. A symptom is what you alert a person about. A cause is what that person investigates after being alerted.
One team's symptom can be another team's cause. For the checkout team, a slow payment provider is a cause. For the payment provider's own team, the same slowness is the symptom they were paged for. Draw the line from where you stand.
The four golden signals
If you can measure only four things about a service that other people call, the same book suggests these. Together they are the four golden signals.
| Signal | Meaning | Example for an order API |
|---|---|---|
| Latency | Time to serve a request. Track successful and failed requests separately. | p99 of GET /orders/17 is 180 ms for successes |
| Traffic | How much demand the system sees, in a unit that fits it. | 1,200 requests per second |
| Errors | Rate of failing requests: explicit, implicit or by policy. | 1.5% of requests return a 5xx status |
| Saturation | How full the most constrained resource is. | Database connection pool is 92% in use |
Two details are easy to miss. First, latency of failures must be kept apart from latency of successes. A request that fails at once with an error is very fast, and mixing it in makes a broken service look quick. Second, an error is not only a 500. The book names three kinds: an explicit error such as an HTTP 500, an implicit error such as a 200 response with the wrong content, and an error by policy, such as counting any response slower than one second as a failure because your agreement with users says so.
Saturation is the signal that warns early. Many systems get slow well before a resource reaches 100% use, so you pick a utilisation target and watch the distance to it. A queue that keeps growing, a memory graph that only climbs, and a full connection pool are all saturation. The percentile idea behind latency is the one from the non-functional chapter: report p50, p95 and p99, not the mean.
Black-box and white-box
There are two ways to look. Black-box monitoring tests behaviour from outside, as a user would: a script requests the home page every minute and records whether it worked. It sees symptoms, and only problems that are happening now. White-box monitoring reads the system's own internals, such as logs, counters and an HTTP endpoint that reports state. It can see problems that are about to happen, and failures that retries are hiding from users.
The book recommends heavy use of white-box monitoring and a modest but critical amount of black-box monitoring. The two are not rivals. White-box tells you the checkout service is retrying every third database call. Black-box tells you whether a customer can still buy something.
One more rule from the same chapter shapes everything that follows. Paging a human is expensive, and people who are paged often learn to ignore pages, including the real ones. Every page should be actionable and need judgement. If the right response is a fixed script, a machine should run it. A subcritical problem belongs on a dashboard, not in someone's inbox.
| Term | Meaning |
|---|---|
| Symptom | What a user or caller sees going wrong |
| Cause | The internal reason behind a symptom |
| Golden signals | Latency, traffic, errors and saturation |
| Black-box | Monitoring from outside, as a user would |
| White-box | Monitoring from the system's own internals |
A food app returns HTTP 200 for every order, but the body says 'no restaurants found' for a whole city. Which kind of error is that?
- An implicit error: the status is fine and the content is wrong.
Part 2 · Metrics, logs and traces
Three kinds of telemetry
Telemetry is the data a running system sends out about itself. Three kinds are standard, and each answers a different question.
A metric is a measurement captured at runtime, such as requests served so far or current memory use. A log is a record of one event, such as one failed payment, with fields that say what happened. A trace follows one request along its path through the system. A trace is made of spans: one span is one timed step, such as the call to the payment provider, with a start, a duration and the id of the trace it belongs to. OpenTelemetry, the open standard for producing this data, lists traces, metrics, logs and baggage as the signals it supports today, with events and profiles still in development. Baggage carries values along with a request from one service to the next.
| Kind | Answers | Cost to keep | Weak at |
|---|---|---|---|
| Metric | How many, how fast, how full? | Low: a few numbers per series, however much traffic | Saying which request failed |
| Log | What exactly happened in this event? | High: grows with every event | Showing trends cheaply |
| Trace | Where did this request spend its time? | Medium to high: one record per step | Showing totals over all requests |
AnswersHow many, how fast, how full?
Cost to keep
Counters, gauges and histograms
Metrics come in a few shapes. A counter only goes up, or resets to zero when the process restarts: requests served, errors seen. A gauge goes up and down: memory in use, queue depth, connections open. A histogram counts how many observations fell into each range, such as requests that took under 50 ms, under 100 ms, under 250 ms. A histogram is what lets you compute a percentile later.
You rarely read a counter's raw value. You read how fast it grows. If a counter went from 6,000 to 6,900 over one minute, the rate is 15 requests per second. A counter is also safe to lose samples from: if one reading is missed, the next one still contains the full total.
A metric is not one number. It is one number per combination of labels, the key-value pairs attached to it. http_requests_total with route="/pay" and status="500" is a different time series from the same metric with status="200". Each new label value makes a new series, so a label such as the user id, with lakhs of values, would create lakhs of series and overwhelm the store. Keep label values few and bounded. A later chapter measures what this costs.
One handler, three signals
The program below is a request handler that produces all three signals for a made-up order service. It keeps a counter in a dictionary, writes a log line as JSON, and writes a span record. The log and the span carry the same eight-character trace id, shortened here to keep the lines short. A real trace id is 32 hex characters. The route /pay is rigged to fail so there is an error to look at.
import json import time import uuid requests_total = {} def log(**fields): print(json.dumps(fields, separators=(",", ":"))) def handle(route): trace_id = uuid.uuid4().hex[:8] start = time.perf_counter() time.sleep(0.02) status = 500 if route == "/pay" else 200 ms = round((time.perf_counter() - start) * 1000, 1) key = (route, status) requests_total[key] = requests_total.get(key, 0) + 1 log(kind="log", route=route, status=status, trace_id=trace_id) log(kind="span", name="handle", trace_id=trace_id, ms=ms) handle("/orders") handle("/pay") handle("/orders") print(requests_total)
signals.py: a counter, a log line and a span from one handler
{"kind":"log","route":"/orders","status":200,"trace_id":"4fc7bfbb"}
{"kind":"span","name":"handle","trace_id":"4fc7bfbb","ms":20.4}
{"kind":"log","route":"/pay","status":500,"trace_id":"4be2b41e"}
{"kind":"span","name":"handle","trace_id":"4be2b41e","ms":20.4}
{"kind":"log","route":"/orders","status":200,"trace_id":"0373f5db"}
{"kind":"span","name":"handle","trace_id":"0373f5db","ms":20.3}
{('/orders', 200): 2, ('/pay', 500): 1}Python 3.12.10. Trace ids and durations differ on every run.
Read the output as a debugging session. The counter at the end says one /pay request failed and two /orders requests succeeded, but it cannot say which request. The log line with status 500 names the route and carries trace id 4be2b41e in this run. Searching for that id finds the span, which says the step took 20.4 ms, so this failure was not a timeout. The id is the thread that ties the records into one story.
The span durations are close to 20 ms because the handler sleeps for 20 ms and then adds a little overhead. In 21 runs made for this page the extra was mostly under 1 ms, and twice about 3 ms. Your numbers will vary.
Why can a counter alone not tell you which request failed?
- A counter holds one number per label combination. It has no record of individual requests.
Part 3 · Pull and push collection
Two ways to get numbers out
Metrics have to travel from the servers that produce them to a store that keeps them. There are two directions. In a pull design, a collector asks each server for its current numbers on a schedule. In a push design, each server sends its numbers to the collector when it chooses.
Prometheus, a widely used open-source monitoring system, is the best-known pull design. Its documentation describes a pull model over HTTP: Prometheus scrapes targets, meaning it makes an HTTP request to each one and reads the answer. Its list of targets comes from a static list or from service discovery, a lookup of which servers currently exist.
| Pull | Push | |
|---|---|---|
| Who starts the transfer | The collector, on a schedule | The application, when it likes |
| Dead server | The scrape fails, so you notice at once | Silence, which looks the same as a quiet server |
| Finding targets | Collector needs a list or discovery | Application needs the collector's address |
| Short-lived jobs | May finish before they are scraped | Can send a result just before exiting |
| Debugging | Open the endpoint in a browser | Inspect what was sent |
The dead-server row is the strongest argument for pull. A collector that scrapes a server and gets no answer knows something is wrong. Prometheus records this as a series named up, which is 1 when the instance is reachable and 0 when the scrape failed. With push, a server that crashed and a server that has nothing to say look the same.
What a scrape returns
The thing that gets scraped is an ordinary HTTP endpoint, usually /metrics, that returns plain text. Prometheus documents a text format for it. Each metric has an optional # HELP line with a description and a # TYPE line naming one of counter, gauge, histogram, summary or untyped. Then come the samples, one per line, written as the metric name, labels in braces and a number. The type line must come before the first sample of that metric. The response is sent as text/plain; version=0.0.4.
The server below counts requests by route and status, and serves them at /metrics in that format. A route named /pay returns status 500 on purpose. Everything else returns 200.
from http.server import BaseHTTPRequestHandler, HTTPServer counts = {} class App(BaseHTTPRequestHandler): def log_message(self, *args): pass def metrics(self): lines = ["# HELP http_requests_total Requests served.", "# TYPE http_requests_total counter"] for (route, status), n in sorted(counts.items()): labels = f'route="{route}",status="{status}"' lines.append("http_requests_total{%s} %d" % (labels, n)) return "\n".join(lines) + "\n" def do_GET(self): if self.path == "/metrics": code, ctype = 200, "text/plain; version=0.0.4" data = self.metrics().encode() else: code = 500 if self.path == "/pay" else 200 key = (self.path, code) counts[key] = counts.get(key, 0) + 1 ctype, data = "text/plain", b"ok\n" self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data)
app.py: count each request, or serve the counters at /metrics
The scraper
The scraper is the other half. It starts the server on port 55462, sends some traffic, scrapes the endpoint and prints the text. It then sends more traffic, scrapes again and prints how much each counter grew between the two scrapes.
import threading import urllib.error import urllib.request from http.server import HTTPServer from app import App PORT = 55462 srv = HTTPServer(("127.0.0.1", PORT), App) threading.Thread(target=srv.serve_forever, daemon=True).start() base = f"http://127.0.0.1:{PORT}" def hit(path, times): for _ in range(times): try: urllib.request.urlopen(base + path).read() except urllib.error.HTTPError: pass def scrape(): text = urllib.request.urlopen(base + "/metrics").read().decode() series = {} for line in text.splitlines(): if not line.startswith("#"): name, value = line.rsplit(" ", 1) series[name] = float(value) return text, series
scrape_demo.py, part 1: start the server, define hit and scrape
hit("/orders", 6) hit("/pay", 2) text, first = scrape() print(text, end="") hit("/orders", 9) hit("/pay", 3) _, second = scrape() for name in second: print(name, "+", int(second[name] - first[name])) srv.shutdown()
scrape_demo.py, part 2: scrape, send more traffic, scrape again
# HELP http_requests_total Requests served.
# TYPE http_requests_total counter
http_requests_total{route="/orders",status="200"} 6
http_requests_total{route="/pay",status="500"} 2
http_requests_total{route="/orders",status="200"} + 9
http_requests_total{route="/pay",status="500"} + 3Python 3.12.10. The numbers are fixed by the traffic the script sends.
The first scrape reads six good /orders calls and two failed /pay calls. The second scrape differs by nine and three, matching the traffic sent in between. A real collector scrapes on a fixed interval: Prometheus uses one minute unless configured, and 15 seconds is a common setting, and the growth is divided by the time between the two scrapes to give a rate. This run sends the requests back to back with no waiting, so the script prints the growth and leaves out the rate.
Two properties make counters good for scraping. A missed scrape loses nothing, because the next one carries the full total. And a counter that drops to a smaller value tells the collector the process restarted, so the collector knows to start counting again from the new value instead of recording a negative number of requests.
Part 4 · Storing time series and downsampling
A series is a list of timestamped values
Each scrape adds one point, a timestamp and a value, to every series it sees. A time-series database is a store built for exactly that: appending points in time order, and reading back ranges of a series fast. Prometheus names a series by the metric name plus its labels, and stores each value with its timestamp.
The volume adds up. One series scraped every second collects 86,400 points a day. A service with a thousand series collects 8.64 crore points a day. Few teams want a month of per-second detail for everything, and almost nobody needs last month's data at the resolution of last minute.
The usual answer is downsampling, also called a rollup. Points older than some age are replaced by a summary of each time bucket, for example one row per minute instead of sixty rows. Recent data stays detailed for debugging a live incident, and old data stays coarse for trend reading. One row per minute is a sixtieth of the points of one row per second, so a rollup shrinks a series sixty-fold.
What a summary row must keep
A rollup loses information, so what you keep matters. The next program makes one hour of made-up processor load readings, one per second, with a mean near 40% and some random noise. For ten seconds in the middle of the hour the value jumps to 98%. It then builds one row per minute holding the minimum, the average and the maximum.
import random random.seed(7) samples = [] for t in range(3600): value = random.gauss(40, 4) if 1800 <= t < 1810: value = 98.0 samples.append((t, value)) rollup = [] for minute in range(60): chunk = [v for _, v in samples[minute * 60:(minute + 1) * 60]] rollup.append((minute, min(chunk), sum(chunk) / len(chunk), max(chunk))) print("raw points:", len(samples), " rolled-up rows:", len(rollup)) print("minute min avg max") for m, lo, avg, hi in rollup[29:32]: print(f"{m:>6} {lo:6.1f} {avg:6.1f} {hi:6.1f}")
rollup.py: 3,600 one-second points become 60 rows
raw points: 3600 rolled-up rows: 60 minute min avg max 29 30.5 39.3 52.1 30 31.9 50.8 98.0 31 32.7 40.1 46.9
Python 3.12.10. The random seed is fixed, so this output repeats.
The output shows three of the sixty rows, minutes 29, 30 and 31. In minute 30 the average is 50.8. A reader looking only at averages would see a mild rise and move on. The maximum for that minute is 98.0, which shows that the machine was nearly saturated for ten seconds. That is a short spike, and it is the kind of thing that makes a user's request time out.
So a rollup should keep at least the minimum and maximum next to the average. For counters, keep the last value in each bucket, since the growth between buckets is what matters. For latency, which is the hard case, you cannot compute a percentile for a longer period by averaging percentiles of shorter ones. The average of two p99 values is not the p99 of the combined requests. Keep histogram bucket counts instead, because counts add up correctly across buckets and across servers, and a percentile can be estimated from the summed counts afterwards.
Retention in tiers
Most systems store the same data at several resolutions and give each a retention, the time after which it is dropped. A typical layout, shown as an example and not a standard, is raw points for a few days, one-minute rollups for a few months and one-hour rollups for a few years. The raw tier is large but short, and the old tiers are tiny but long.
| Tier | Resolution | Example retention | Used for |
|---|---|---|---|
| Raw | 1 s or 15 s | Days | Debugging a live incident |
| Rollup 1 | 1 min | Months | Dashboards, week-over-week comparison |
| Rollup 2 | 1 h | Years | Capacity planning, yearly trends |
Resolution1 s or 15 s
Example retentionDays
Used forDebugging a live incident
Resolution1 min
Example retentionMonths
Used forDashboards, week-over-week comparison
Resolution
Part 5 · Dashboards and the first alert rule
Dashboards answer a question you already have
A dashboard is a screen of charts over your time series. Good ones are built around questions, not around whatever data happens to exist. The first row of a service's dashboard is usually the four golden signals: traffic, errors, latency percentiles and saturation, each over the last few hours. Below that go the causes you check next, such as the database, the cache and the queue depths.
A few habits keep a dashboard useful. Show percentiles, not just the mean. Put the same time range on every chart so spikes line up. Draw the target as a line, for example the latency you promised, so that nobody has to remember it. Show the number of failing requests and the share of failing requests, because a service with a low rate can still lose a lot in absolute terms when traffic is high, and a high rate on tiny traffic can be nothing to worry about.
Dashboards are for looking. Nobody can watch one all night, which is why a second tool exists.
An alert rule has three parts
An alert rule is a condition that the system checks for you, continuously, and a promise to tell someone when it holds. A useful rule has three parts. The condition is a comparison over a series, such as the share of requests that failed in the last minute being above 5%. The duration says how long the condition must hold before the rule fires, which filters out a one-scrape blip. The destination says who hears about it and how loudly.
Prometheus rules have this shape: an expression, an optional for duration, and labels such as a severity. While the condition holds but the duration has not elapsed, the alert is in a pending state. After the duration it is firing. Prometheus sends firing alerts to a separate component, Alertmanager, which handles grouping, silencing and routing to people. The next chapter covers that part.
The condition should be a symptom. Alert on the rate of failing user requests, which is what users feel, and use cause measures such as processor load for dashboards. A processor-load alert that fires while users are happy teaches the on-call engineer to ignore alerts. A request-failure alert that fires only when users are hurting does the opposite.
A rule over scraped numbers
The next program takes what a scraper sees: two cumulative counters, all requests and failed requests, sampled every 15 seconds for six minutes. It applies a rule: error ratio above 5% for three scrapes in a row. The data is simulated with a fixed seed. Failures run at 1% normally, and at 30% for the scrapes from 150 s to 240 s.
import random random.seed(11) # Two cumulative counters, sampled every 15 seconds for 6 minutes. total, errors, scrapes = 0, 0, [] for i in range(24): n = random.randint(90, 110) bad_rate = 0.30 if 10 <= i < 17 else 0.01 total += n errors += sum(random.random() < bad_rate for _ in range(n)) scrapes.append((i * 15, total, errors)) THRESHOLD, FOR = 0.05, 3 # error ratio above 5% for 3 scrapes streak, state = 0, "ok" for (t0, t1, e1), (_, t2, e2) in zip(scrapes, scrapes[1:]): ratio = (e2 - e1) / (t2 - t1) streak = streak + 1 if ratio > THRESHOLD else 0 if streak >= FOR: new = "FIRING" elif streak > 0: new = "pending" else: new = "ok" if new != state: print(f"t={t0 + 15:>3}s ratio={ratio:.2f} {state} -> {new}") state = new
alert.py: error ratio per scrape and a rule with a three-scrape duration
t=150s ratio=0.30 ok -> pending t=180s ratio=0.35 pending -> FIRING t=255s ratio=0.01 FIRING -> ok
Python 3.12.10. The random seed is fixed, so this output repeats.
The first bad scrape at 150 s moves the rule to pending, because one reading is not enough. Two scrapes later, at 180 s, the third bad reading in a row makes it fire. When the failures stop, the first good scrape at 255 s returns the rule to ok. A single bad scrape would have been ignored. The cost of that safety is delay: this rule needs 45 seconds of badness before anyone hears of it.
Watching it run
The scene below shows the whole path. A collector scrapes two servers, stores each scrape, and a rule reads the latest points. When one server's errors rise and stay up for three scrapes, the rule fires and the on-call engineer is paged.
Watch for the collector: it asks each server for its numbers
Read it as steps
Two servers are scraped on a schedule. When errors rise and stay up, a rule pages the on-call engineer.
Notice the order: scrape, store, evaluate, page. Each stage can fail on its own, so mature teams also watch the watchers. If the collector stops, the rule sees no new points, so a good rule treats missing data as a problem, and a check from outside, as the next chapter describes, confirms that alerts can still reach a person.
| Term | Meaning |
|---|
All chapters · Previous: Unique IDs: Sequencers, UUIDs and Snowflake IDs