Observability is the practice of understanding a running system purely from the data it emits, without shipping a new build just to ask it a question. Three kinds of telemetry carry that data: logs record what happened, metrics count how often and how much, and traces follow one request through every hop it touches. This lesson shows how the three fit together, why an aggregate can quietly lie, and how a single averaged number can hide a real outage from the very dashboard built to catch it.
The Analogy: A Motorway Traffic Operations Center
A regional traffic operations center watches thirty miles of motorway from a wall of screens. The duty officers cannot stand on the tarmac, so they understand the road entirely through the signals it sends back. Over the years the room has grown three separate record-keeping systems, and each one answers a different kind of question. Used together they give a faithful picture of the road; used carelessly, any one of them can mislead the whole shift.
The first system is the incident log: a running book in which the officer on duty writes each notable event with the exact time and place -- "08:14 debris reported, junction 9 northbound", "08:22 lane 2 reopened". It is precise and story-rich, perfect for reconstructing exactly what happened on one stretch of road, but nobody would judge the health of the whole motorway by counting book entries. The second system is the loop-detector tally board: sensors buried in every lane count vehicles and measure speed, and those numbers are sampled continuously and drawn as trend lines. The board is cheap to keep for years and ideal for spotting slow build-ups, but it has forgotten which car was which -- it knows only totals and averages. The third system follows one tagged probe vehicle: a fleet car with a transponder that stamps its passage at every gantry, so the room can lay out that single journey segment by segment and see precisely where it waited.
Mapped to a running service, the incident log is your logs, the tally board is your metrics, and the probe vehicle is a trace. The four "golden signals" the control room lives by carry over directly: how long a journey takes is latency, how many vehicles pass per hour is traffic, how many incidents occur is errors, and how full the lanes are running is saturation. Each system has a cost: logs are detailed but expensive to store and search, metrics are compact but anonymous, and traces are rich but far too heavy to record for every single vehicle, so you sample them.
The failure that catches this room out is subtle. On a bad morning a single on-ramp jams and a fraction of drivers sit trapped for forty minutes, yet the wall board -- which shows the average journey time across every vehicle -- barely twitches, because the thousands of cars still flowing freely drown out the few hundred that are stuck. The duty officer reports "average travel time nominal" and closes the ticket, while the phones light up with furious drivers. The average is dominated by the majority and is structurally blind to the trapped tail. The honest number was never the mean at all; it was the ninety-fifth or ninety-ninth percentile journey time, the figure that asks "how bad is it for the unluckiest drivers?" -- and that is exactly the trap we will reproduce in code.
Syntax or Core Structure
The three pillars are not three technologies so much as three shapes of data. A log is one record per event; a metric is a single number you keep re-sampling over time; a trace is a per-request record you stitch together across services. The snippet below takes twenty raw request records -- the kind of thing each service emits -- and derives both a metric view (aggregates over all of them) and a single structured log line for the one request that failed.
import json
# Twenty raw request records. In production each of these would be one
# structured log line; the metrics are computed by rolling them up.
LATENCIES = [50] * 18 + [100, 2000] # milliseconds
STATUSES = [200] * 19 + [500] # one server error
REQUESTS = [{'latency_ms': l, 'status': s}
for l, s in zip(LATENCIES, STATUSES)]
# metric view: aggregates over many events
traffic = len(REQUESTS)
errors = sum(1 for r in REQUESTS if r['status'] >= 500)
error_rate = 100.0 * errors / traffic
print('traffic (requests): %d' % traffic)
print('errors (5xx): %d' % errors)
print('error rate: %.1f%%' % error_rate)
# log view: one structured record for the failed request
failed = [i for i, r in enumerate(REQUESTS) if r['status'] >= 500][0]
log = {'event': 'request_failed', 'index': failed,
'latency_ms': REQUESTS[failed]['latency_ms'],
'status': REQUESTS[failed]['status']}
print('log: ' + json.dumps(log, sort_keys=True))
Output:
traffic (requests): 20
errors (5xx): 1
error rate: 5.0%
log: {"event": "request_failed", "index": 19, "latency_ms": 2000, "status": 500}
Notice the division of labour. The metric lines are cheap counters: they throw away the identity of every request and keep only totals, which is exactly why a year of them costs almost nothing to store. The log line is the opposite -- it keeps the full context of one event so you can answer "what happened to that request?" -- but keeping such a record for every request at scale is expensive. The sort_keys=True argument is not cosmetic: structured logs are only useful if their fields are stable and queryable, and deterministic key ordering is the first step toward that.
Technical Depth: From Events to Aggregates
Choosing the right pillar
Each pillar answers a different question and carries a different cost. Reaching for the wrong one is a common source of both blind spots and runaway bills.
| Pillar | Answers | Cardinality cost | Typical retention |
|---|---|---|---|
| Logs | What exactly happened to this event | High per event | Days to weeks |
| Metrics | How much, how many, how fast overall | Low, pre-aggregated | Months to years |
| Traces | Where did this one request spend time | High, usually sampled | Days |
The four golden signals
Google's Site Reliability Engineering book names four signals that, watched together, catch most user-facing problems. They map cleanly onto the metric view above.
| Signal | Question it answers | Example measurement |
|---|---|---|
| Latency | How long do requests take | p50, p95, p99 response time |
| Traffic | How much demand is arriving | requests per second |
| Errors | How often do requests fail | 5xx responses per minute |
| Saturation | How close to full is the system | CPU percent, queue depth |
Percentiles: reading the tail
Latency is the signal most often measured badly, because people summarise it with a mean. The honest summary is a percentile: the p95 latency is the value below which 95 percent of requests fall. The simplest correct definition is the nearest-rank method -- sort the samples, then pick the value at position ceil(p / 100 * n).
import math
LATENCIES = [50] * 18 + [100, 2000]
def percentile(values, p):
s = sorted(values)
k = math.ceil(p / 100.0 * len(s)) # nearest-rank, 1-based index
return s[k - 1]
mean = sum(LATENCIES) / len(LATENCIES)
print('count: %d' % len(LATENCIES))
print('mean latency: %.0f ms' % mean)
print('p50 latency: %d ms' % percentile(LATENCIES, 50))
print('p95 latency: %d ms' % percentile(LATENCIES, 95))
print('p99 latency: %d ms' % percentile(LATENCIES, 99))
Output:
count: 20
mean latency: 150 ms
p50 latency: 50 ms
p95 latency: 100 ms
p99 latency: 2000 ms
Look at how far apart these numbers are for the very same data. The median request (p50) is a brisk 50 ms and half of all users see that or better. Yet the mean is 150 ms -- already pulled upward by a single slow outlier -- and the p99 is a dreadful 2000 ms. No single average could have told you both that the typical experience is fine and that the unluckiest one percent are waiting two full seconds. That gap between the median and the tail is the entire reason percentiles exist.
Real World Example: The Alert That Watched the Wrong Number
A payments team runs an API behind a published service level objective: ninety-nine percent of requests must complete in under 500 milliseconds. They wire a latency alert to fire when the service breaches that budget, and to keep the alerting query cheap they point it at the average request latency reported by their metrics pipeline -- one number, one comparison, easy to reason about. For months the alert stays quiet and everyone assumes the SLO is being met.
Then support tickets start arriving: a steady trickle of customers report the checkout "hanging" for seconds at a time. The dashboard, however, is stubbornly green. The program below reproduces the exact situation with the same twenty-request sample, comparing the alert the team actually built against the one the SLO demanded.
import math
LATENCIES = [50] * 18 + [100, 2000]
SLO_MS = 500
def percentile(values, p):
s = sorted(values)
k = math.ceil(p / 100.0 * len(s))
return s[k - 1]
mean = sum(LATENCIES) / len(LATENCIES)
p99 = percentile(LATENCIES, 99)
naive_ok = mean < SLO_MS # the alert the team built
correct_ok = p99 < SLO_MS # the alert the SLO actually demands
print('SLO: latency must stay under %d ms' % SLO_MS)
print('mean latency: %.0f ms' % mean)
print('p99 latency: %d ms' % p99)
print('naive check (mean < SLO): %s' % naive_ok)
print('correct check (p99 < SLO): %s' % correct_ok)
print('naive and correct agree: %s' % (naive_ok == correct_ok))
Output:
SLO: latency must stay under 500 ms
mean latency: 150 ms
p99 latency: 2000 ms
naive check (mean < SLO): True
correct check (p99 < SLO): False
naive and correct agree: False
The two checks disagree, and the disagreement is the whole story. The mean-based alert reports the service as healthy because 150 ms sits comfortably under the 500 ms budget, while the p99-based alert -- the one that actually reflects the wording of the SLO -- correctly fires, because one request in twenty is taking 2000 ms. The team's dashboard was not broken; it was faithfully answering a question nobody should have asked.
The design flaw sits in the choice of aggregate, and it is worth stating precisely: a mean-based latency alert is mathematically invariant under tail blow-ups. You can make a small fraction of requests arbitrarily slow without moving the average enough to trip the threshold, because the average is dominated by the fast majority. An SLO written about the ninety-ninth percentile can therefore only be honestly enforced by measuring the ninety-ninth percentile. This sample also exposes two narrower limits worth naming. First, the nearest-rank percentile on just twenty points is coarse -- p99 here can only land on one of the top few values, so on tiny windows you should widen the time range before trusting the number. Second, percentiles do not average across machines: you cannot take the p99 from ten hosts and average them to get a fleet p99, which is why real systems aggregate latency into histogram buckets and compute percentiles from the merged histogram instead.
Common Mistakes
- Summarising latency with an average. The mean is dominated by the bulk of fast requests and hides the slow tail your users actually complain about. Alert and report on percentiles such as p95 and p99 instead.
- Logging unstructured strings. A line like "User 42 failed from 1.2.3.4" cannot be filtered or aggregated at scale. Emit structured records with stable field names so the logs are queryable.
- Treating logs as metrics. Counting log lines to derive a rate is slow and expensive. Emit a real counter metric for anything you want to alert on or chart over months.
- Putting high-cardinality values in metric labels. Tagging a metric with user id, request id, or full URL explodes the number of time series and can bankrupt a metrics backend. Keep those in logs or traces.
- Tracing every request. Full-fidelity tracing of 100 percent of traffic is usually too heavy to store. Sample traces, and make sure the sampling keeps the interesting ones such as errors and slow requests.
- Alerting on saturation you cannot act on. An alert that fires on 80 percent CPU with no runbook and no autoscaling just trains the team to ignore alerts. Alert on symptoms users feel, not every raw resource number.
- Forgetting the clock skew between pillars. A log timestamped by the application and a metric scraped by the server can disagree by seconds. Correlate on request id or trace id, not on wall-clock time alone.
- Storing everything forever. Logs are the expensive pillar; retaining raw debug logs for a year with no downsampling is how observability bills quietly dwarf the compute bill. Set retention deliberately per pillar.
- Non-deterministic log fields. Emitting fields in a random order, or including timestamps and memory addresses in a message you later want to group on, makes logs impossible to aggregate. Keep the groupable fields stable and structured.
Best Practices
- Instrument the four golden signals first -- latency, traffic, errors, and saturation cover most user-facing incidents before you add anything bespoke.
- Report latency as a distribution, not a point. Publish p50, p95, and p99 side by side so the typical case and the tail are both visible.
- Emit structured logs with a stable schema and a consistent key order, so every line is machine-queryable rather than only human-readable.
- Propagate a trace id and a request id through every service hop, and stamp them onto logs and metrics so the three pillars can be joined.
- Keep high-cardinality data such as ids, URLs, and user identifiers in logs and traces, and keep metric labels low-cardinality so the time-series count stays bounded.
- Set retention per pillar: short for raw logs, long for aggregated metrics, medium and sampled for traces, matching each pillar's cost to its value.
- Define alerts against service level objectives and symptoms users feel, and give every alert a runbook link so a page always has a next action.
- Aggregate percentiles from histograms, never by averaging per-host percentiles, so a fleet-wide p99 stays mathematically honest.
Practice Exercises
- Extend the syntax example to also compute the p50, p95, and p99 latency and print them next to the error rate, so a single run shows all four golden signals for the sample.
- Write a function that takes a list of latencies and a threshold and returns the fraction of requests that breached the threshold (the "error budget burn"). Confirm that for the lesson's sample and a 500 ms threshold it returns 0.05.
- Change the sample so that three of the twenty requests take 2000 ms instead of one, and work out by hand what p95 and p99 become under the nearest-rank method before running the code to check.
- Take two hosts, each with its own list of latencies, and show numerically that averaging their individual p99 values gives a different, and wrong, answer than computing the p99 over the combined list of all requests.