Course contents

13. Observability Lesson 2 of 6

Metrics

Counters, gauges and histograms; why P50 hides a slow server while P99 shows it; RED for services, USE for resources, and label cardinality.

14 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Counters only go up and are read as rates; gauges are snapshots; histograms record distributions.
  • Little’s law ties them together: requests in flight = arrival rate × latency.
  • An average blends fast and slow requests into a number nobody experiences; P50 hides a minority of slow requests, P95/P99 show them.
  • RED (rate, errors, duration) says whether users hurt; USE (utilisation, saturation, errors) says which resource is the cause.
  • Labels give breakdowns; unbounded label values (user ids) explode the number of time series.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A metric is a numeric measurement sampled over time and stored as a time series: a name, a set of labels and a sequence of (timestamp, value) points. Because each series stores aggregates rather than individual events, its cost depends on the number of series, not on traffic.

Why it exists

You need to know continuously, and cheaply, whether a system is healthy: how much traffic, how many errors, how slow, how full. Metrics feed dashboards and alerts, show trends over months, and let you compare before and after a change.

How it works

Counters only increase (requests served, errors, bytes sent) and reset on restart. You query their rate over a window, e.g. rate(http_requests_total[5m]), which handles resets.

Gauges go up and down: in-flight requests, queue depth, memory in use, pool connections. You read the value or an aggregate (average, max) over time.

Histograms count observations into buckets (≤ 50 ms, ≤ 100 ms, …). Percentiles are estimated from the buckets, so bucket boundaries should bracket the values you care about; native/exponential histograms (Prometheus, OpenTelemetry) adjust resolution automatically. Histograms can be aggregated across instances; pre-computed per-instance percentiles (summaries) cannot be averaged meaningfully.

Collection. Either the backend scrapes an HTTP endpoint on each process every 10–60 s (Prometheus model), or processes push (OTLP, StatsD). Either way a time series database stores the points.

Little's law links them: average requests in flight = arrival rate × average time in system. At 80 req/s and 90 ms, about 7 requests are in flight; if latency rises at the same traffic, the gauge rises with it.

Percentiles. Pxx is the latency xx% of requests beat. A percentile reacts once more than (100 − xx)% of requests are affected: P50 needs a majority, P99 just 1%. Averages move partially and describe neither the fast nor the slow group.

RED and USE. For each request-serving service, track Rate, Errors and Duration (Tom Wilkie). For each resource, track Utilisation, Saturation (queued work) and Errors (Brendan Gregg). RED is the user's view; USE finds the cause.

When to use it

For anything you want to graph, alert on or trend: traffic, errors, latency distributions, resource usage, queue depths, business counters (orders per minute). Metrics are the basis of SLOs and burn-rate alerts.

When not to

  • To explain individual requests: use logs and traces.
  • For high-cardinality dimensions (user id, request id, full URL with ids): each value creates a new series.
  • For exact billing or audit records: scrapes can miss the last interval before a crash.

Trade-offs

Choice You gain You pay
Histogram instead of average Percentiles, tail visibility More series (one per bucket)
More labels Finer breakdowns Multiplied series count, memory, cost
Short scrape interval Faster detection, finer graphs More load and storage
Long retention / downsampling Long-term trends Storage cost, or lost detail when downsampled
Pull (scrape) Simple target discovery, up/down signal Needs network reachability to every process

Alternatives

  • Logs for per-event detail; log-derived metrics exist but cost more.
  • Traces for per-request timing; span metrics (RED from spans) can be generated in the collector.
  • Continuous profiling for "which code uses the CPU" questions metrics cannot answer.

Failure modes

  • Averages hiding tails: an average-latency dashboard stays calm while 5% of users wait seconds.
  • Cardinality explosion: a user-id or URL label creates millions of series and takes the TSDB down.
  • Averaging percentiles: averaging per-instance P99s is mathematically meaningless; aggregate histograms instead.
  • Rate over counter resets handled wrongly, or gauges graphed as rates.
  • Aggregation hiding one bad instance: a fleet-wide P99 can look fine while one instance is awful; break down by instance.
  • Missing saturation signals: utilisation looks fine (60%) while a queue grows behind a single slow resource.

In production

Instrument every service with RED metrics as histograms, labelled by route template, status class and instance; add USE metrics for pools, queues, CPU and memory; expose runtime metrics (GC, threads). Keep label sets bounded and review cardinality. Build dashboards top-down (user journey → service → instance → resource) and alert on SLO burn, not on every metric.

Common misconceptions

  • "Average latency is a good summary." It describes no one when latency is bimodal.
  • "P50 is what most users experience." A page that makes 30 requests almost certainly includes one beyond the P95.
  • "High utilisation means the resource is the problem." Check saturation: a 100% busy pool with an empty queue is fine; a growing queue is not.
  • "More labels are free." Every new value is a new series.

Interview angle

Expect "what would you monitor for this service?" Answer with RED per service, USE per resource, latency as histograms with P95/P99, breakdowns by instance and route, and SLO-based alerts. Explain why averages and per-instance percentile averaging mislead, use Little's law to sanity-check numbers, and mention cardinality limits.

Model assumptions

Simulated: four app servers with 4 workers, 40 ms mean service time (lognormal, cv 0.3) and room for 8 waiting requests each, behind a round-robin balancer; the degraded server is 4× slower (about 25 req/s capacity). Arrivals are Poisson; network hops are 20 ms and 5 ms. Metric tiles show the simulation's exact percentiles over a 5-second window, not histogram estimates; metric names, labels and queries in the annotations are illustrative Prometheus-style examples, and the metrics database is scenery. Numbers show behaviour, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Counters: numbers that only go up

    A metric is a number sampled over time, cheap enough to keep for every request without storing the requests themselves. Users send about 80 requests a second to four app servers.

    The simplest kind is a counter: http_requests_total, incremented once per request and never decreased (it only resets when the process restarts). Nobody reads the raw value. You read its rate: the increase per second over a window, which is what the throughput tile shows, about 80 a second, all of them successful.

    The metrics database (TSDB) scrapes each server every few seconds and stores one point per series, not one row per request.

    Scene: Users send about 80 requests per second through a load balancer to four app servers. Every request succeeds; the throughput tile shows about 80 per second. A metrics database collects counters from the servers.

    Key idea: A counter only goes up; what you graph is its rate over a window.

  2. 2. Gauges: a value right now

    A gauge is a value that goes up and down: requests in flight, queue depth, busy workers, memory in use. You read it as it is, or average it, but its rate means nothing.

    The in-flight tile is a gauge. It hovers around 7 or 8, and that is no accident: Little’s law says requests in flight = arrival rate × time in the system. 80 per second × about 0.09 s ≈ 7. If latency doubled at the same traffic, the gauge would double too.

    Scene: The same healthy system. The in-flight gauge stays around 7 to 8 requests, which matches 80 requests per second times about 90 ms each.

    Key idea: A gauge is a snapshot; in flight = rate × latency (Little’s law) ties gauges and counters together.

  3. 3. Histograms: the shape of latency

    For latency, one number per request is too much and one average is too little. A histogram counts requests in buckets (≤ 50 ms, ≤ 100 ms, ≤ 250 ms, …) and from the buckets you estimate percentiles: P50 is the latency half of the requests beat, P99 the one 99 in 100 beat.

    Right now the distribution is narrow: P50 is a little under 100 ms and even P99 stays well below twice the median. Every server is equally fast, so every request looks alike.

    Scene: Healthy system with latency percentiles shown: P50 just under 100 ms and P99 less than twice the median.

    Key idea: Record latency as a histogram; read percentiles from it, not an average.

  4. 4. One server becomes slow

    One second in, App 4 becomes four times slower (a noisy neighbour, a bad disk, garbage collection). Round robin does not notice and keeps sending it a quarter of the traffic.

    Watch the tiles. P50 barely moves: three quarters of the requests never touch App 4. P95 and P99 jump to several hundred milliseconds. The mean (not on a tile; it is what a naive "average latency" graph shows) rises by about 40%, to a value almost no request actually has: requests take either about 90 ms or well over 200 ms, and the average describes neither.

    Scene: App 4 slows down to a quarter of its speed. P50 latency stays about the same, while P95 and P99 rise to several hundred milliseconds. The average rises by about 40% but hardly any request has that latency.

    Key idea: Averages blend fast and slow requests into a number nobody experiences. Tails show the problem; the median hides it.

  5. 5. Which percentile sees what

    About one request in four is now slow, the share App 4 receives. That decides which percentile sees the incident: P50 would only move once more than half the requests were slow; P95 and P99 moved the moment more than 5% and 1% were.

    This is why latency SLOs and alerts use high percentiles. A user loading a page makes dozens of requests, so a 1-in-100 slow request is something most users meet on every page.

    Scene: App 4 is slow and receives about a quarter of all requests. Those requests make up the slow tail; requests to App 1, 2 and 3 stay fast.

    Key idea: A percentile Pxx reacts once more than (100 − xx)% of requests are affected.

  6. 6. RED: Rate, Errors, Duration

    For every service that answers requests, start with three signals: Rate (requests per second), Errors (failed requests per second, or their share) and Duration (latency percentiles). That is the RED method, and it is what users feel.

    Traffic grows to 140 requests a second. App 4 now receives about 35 a second but can finish only about 25: its queue fills and it rejects the excess with 503. The error tile turns red, and every rejection comes from App 4.

    Scene: Traffic rises to 140 requests per second. App 4 cannot keep up, its queue fills and it rejects requests; the error rate rises and all rejections come from App 4.

    Key idea: RED (rate, errors, duration) per service tells you whether users are hurting.

  7. 7. USE: Utilisation, Saturation, Errors

    RED says users hurt; USE says which resource is the cause. For every resource (CPU, workers, connection pool, disk), check Utilisation (how busy), Saturation (how much work waits) and Errors.

    App 4 is at about 100% utilisation with a full queue. Apps 1 to 3 sit around a third busy with nothing waiting. RED pointed at the service; USE points at the machine.

    Scene: App 4 is fully busy with a full queue and rejects requests. App 1, 2 and 3 are about a third busy with empty queues.

    Key idea: RED for services (the user’s view), USE for resources (the cause).

  8. 8. Labels, and taking App 4 out

    You only found App 4 because the metrics carry an instance label. Labels (dimensions) let you split one metric by service, instance, route or status code. Each distinct combination is a separate time series, so keep label values bounded: instance and route yes, user id or request id never (that is a job for logs and traces).

    With the culprit known, App 4 is drained: taken out of the pool so it can be investigated without users waiting on it. The other three carry 140 a second comfortably, rejections stop and P99 falls back near the healthy level.

    Scene: App 4 is drained from the pool. The three remaining servers handle 140 requests per second without rejections and P99 latency returns close to normal.

    Key idea: Labels turn one number into a breakdown; unbounded label values turn your TSDB into a bill.

  9. 9. What metrics are for

    Metrics are cheap aggregates: perfect for dashboards and alerts, fixed in cost no matter how much traffic flows. Counters for things that happen, gauges for current state, histograms for distributions.

    What they cannot do is tell you about one request. When a metric says "P99 is bad", logs and traces tell you which requests and why. The next lessons pick up from there.

    Scene: Three healthy app servers serve 140 requests per second; App 4 is out of the pool.

    Key idea: Metrics tell you that and where; logs and traces tell you why.