Observability and SREVol. 9 · Part IX
0 / 0

Shelves / Observability and SRE

OB·100

Metrics

Metrics from first principles: the data model (name, labels, samples), counters, gauges, histograms and summaries (and OpenTelemetry's instruments), the Prometheus pull model and exposition format, PromQL for rates, aggregations and quantiles, cardinality and how to control it, why averages lie and percentiles can't be averaged, histogram bucket design and native histograms, saturation, the four golden signals with RED and USE, recording rules, dashboards, and instrumentation in Java, Go, Python, Rust and Node.

31 topics · ~19 min read · 30-question quiz
Updated Suggest a correction

Start here: numbers over time

A metric is a named number, sampled again and again

A time series is a metric name plus a set of labels, with a value recorded at each scrape:

Text
app_requests_total{route="/order", status="200"}   at 09:40:01 → 18,204   at 09:40:02 → 18,977   …

Prometheus pulls (scrapes) each service's /metrics page every few seconds and stores the values. You almost never look at a raw counter value; you ask how fast it grows:

Text
rate(app_requests_total[1m])          requests per second, averaged over the last minute

Three kinds of metric cover almost everything

Type Goes Example You usually ask
Counter only up (resets to 0 when the process restarts) requests served, errors, bytes sent rate() or increase()
Gauge up and down queue length, memory in use, temperature its current value, max_over_time()
Histogram counts observations into buckets request duration, response size histogram_quantile(0.99, …) for percentiles

A restart resets counters, and rate() handles it: in the lab a service was restarted mid-window and increase() reported 394,773 requests (correct: about 8,800 per second), while a naive max − min reported 2,612,000.

Labels are powerful and dangerous

Labels let you slice: by route, by status, by region. But every distinct combination of label values is a separate time series. Adding a user_id label with 10,000 users to a counter that had 8 series:

Text
without user_id:  head series 112,     Prometheus RSS 87 MiB,   app's /metrics page 3 KB
with user_id:     head series 160,128, Prometheus RSS 350 MiB,  app's /metrics page 12.2 MB, scrape 1.3–2.4 s

One label made the monitoring system four times bigger and the service's metrics page too slow for a 1-second scrape (the first attempt timed out and the target went down). That is a cardinality explosion. User IDs, order IDs, email addresses, full URLs and error messages don't belong in labels; put them in logs and trace attributes.

Averages hide the users who suffer

Latency is lopsided: most requests are quick, a few are very slow. Use percentiles: p50 is the typical request, p99 the slowest 1%. And never average percentiles: in the lab, the true p99 across two instances was 0.81 s (computed from their combined histogram), but averaging each instance's p99 gave 1.11 s.

How deep to go in metrics

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain counters, gauges, histograms, labels and percentiles
L2 Instrument a service with RED metrics and write basic PromQL
L3 Choose buckets, control cardinality, aggregate histograms correctly, write recording rules
L4 Diagnose cardinality explosions, misleading rates and percentile errors
L5 Design metrics standards and a scalable metrics platform (remote write, Mimir/Thanos, retention)
L6 Run metrics as a platform with cardinality budgets, cost attribution and governance

The data model

A metric is a named numeric measurement tracked over time. In the Prometheus/OpenMetrics model (which OpenTelemetry metrics map onto), a time series is identified by:

  • a metric name: http_server_request_duration_seconds
  • a set of labels (attributes, dimensions): {service="orders", method="GET", route="/orders/{id}", status_code="200"}

and consists of samples: (timestamp, float64 value) pairs, typically every 15–60 seconds.

Every unique combination of name and label values is a separate time series. That single fact drives the cost and design of everything in this chapter.

Metric types

Counter

A counter only goes up (or resets to zero when the process restarts). It counts events: requests, errors, bytes sent, orders placed.

  • You almost never look at a counter's raw value; you look at its rate: rate(http_requests_total[5m]) = per-second average increase over the last 5 minutes, handling resets automatically.
  • Naming convention: suffix _total (orders_placed_total), with a base unit where relevant (_bytes_total, _seconds_total).

Gauge

A gauge goes up and down: current value of something: queue depth, in-flight requests, memory in use, temperature, connection pool size, cache entries.

  • Query the value directly, or avg_over_time, max_over_time, deriv (rate of change).
  • Don't use a gauge for things that are really counters (rate() on a gauge is meaningless).

Histogram

A histogram samples observations (usually durations or sizes) into buckets and records:

  • _bucket{le="0.1"}: cumulative count of observations ≤ 0.1 (one series per bucket),
  • _sum: total of all observed values,
  • _count: number of observations.

From these you can compute rates, averages (sum/count), and approximate quantiles with histogram_quantile(), aggregated across instances (sum the buckets, then compute the quantile), which is the key advantage over summaries.

count 5ms 10ms 25ms 50ms 100ms 250ms 500ms +Inf 95% of 1000 = 950 p95 ≈ 91 ms (interpolated in 50–100 ms) 120410780
A classic Prometheus histogram. Observations are counted into cumulative buckets (≤ 5 ms, ≤ 10 ms … ≤ +Inf). To estimate the 95th percentile, find the bucket where the cumulative count crosses 95% of the total and interpolate linearly within it; accuracy depends on bucket boundaries near the quantile.

Bucket design matters: quantile estimates are only as good as the bucket boundaries near the quantile you care about. Put boundaries around your SLO thresholds (if the target is "95% under 300 ms", have a bucket at exactly 0.3 s) and spread them roughly exponentially across the range you expect. Too many buckets multiply series (each bucket is a series per label combination).

Native histograms (Prometheus; also OpenTelemetry exponential histograms) replace fixed buckets with sparse, exponentially sized buckets encoded in a single series, with configurable resolution. They give much better quantile accuracy at far lower cardinality, and they're aggregatable. Prometheus 3.x has made them a first-class, stable feature; OTel exponential histograms map onto them.

Summary

A summary computes quantiles on the client (e.g. p50, p90, p99 over a sliding time window) and exports them directly, plus _sum and _count.

  • Accurate quantiles for that one instance.
  • But quantiles can't be aggregated: the p99 of 20 pods is not the average (or max) of their p99s. You can't compute a fleet-wide percentile from summaries.
  • Fixed at instrumentation time (you can't ask for p95 later if you only exported p99).

Prefer histograms (especially native/exponential) for latency in distributed systems; summaries are mostly legacy.

OpenTelemetry instruments

OTel instrument Behaves like Example
Counter Monotonic counter Requests, bytes
UpDownCounter Counter that can decrease (sum) Active connections, queue size (when you track increments)
Histogram Histogram (explicit or exponential buckets) Durations, payload sizes
Gauge (synchronous) Gauge Current temperature reading
Observable Counter / UpDownCounter / Gauge Values read via callback at collection time CPU time, memory used, pool size from a library

OTel SDKs aggregate in-process and export via OTLP (push) or expose a Prometheus endpoint (pull). Views change aggregation, bucket boundaries, or drop attributes to control cardinality.

Prometheus

Pull model

Prometheus (SoundCloud, 2012; the second CNCF graduated project) scrapes HTTP endpoints (/metrics) on a schedule, discovered via service discovery (Kubernetes, Consul, EC2, file):

  • Pull makes "is the target up?" a free signal (up == 0), lets Prometheus control load, and keeps applications simple.
  • Short-lived jobs that can't be scraped push to the Pushgateway (sparingly) or use OTLP push.
  • Prometheus also accepts pushes today: remote-write receiver and an OTLP receiver (Prometheus 3.0 improved OTLP and UTF-8 metric names to align with OpenTelemetry).

Text exposition format:

Text
# HELP http_server_request_duration_seconds Duration of HTTP server requests.
# TYPE http_server_request_duration_seconds histogram
http_server_request_duration_seconds_bucket{route="/orders/{id}",method="GET",le="0.05"} 905
http_server_request_duration_seconds_bucket{route="/orders/{id}",method="GET",le="0.1"} 960
http_server_request_duration_seconds_bucket{route="/orders/{id}",method="GET",le="+Inf"} 1000
http_server_request_duration_seconds_sum{route="/orders/{id}",method="GET"} 31.7
http_server_request_duration_seconds_count{route="/orders/{id}",method="GET"} 1000
# TYPE orders_in_flight gauge
orders_in_flight 7

A single Prometheus server stores data in its local TSDB (compressed chunks, about 1–2 bytes per sample) and handles millions of active series. For long retention, high availability and global queries, use Thanos, Grafana Mimir, Cortex or VictoriaMetrics, or managed services (Amazon Managed Service for Prometheus, Google Managed Prometheus, Grafana Cloud). Prometheus Agent mode scrapes and remote-writes without local querying.

PromQL essentials

PromQL
# Per-second request rate per route (counters → rate)
sum by (route) (rate(http_server_request_duration_seconds_count{service="orders"}[5m]))

# Error ratio (5xx / all), the core of an availability SLI
sum(rate(http_server_request_duration_seconds_count{service="orders", status_code=~"5.."}[5m]))
/
sum(rate(http_server_request_duration_seconds_count{service="orders"}[5m]))

# p99 latency across all pods: sum the bucket rates FIRST, then compute the quantile
histogram_quantile(0.99,
  sum by (le) (rate(http_server_request_duration_seconds_bucket{service="orders"}[5m])))

# Native histogram equivalent (no le label needed)
histogram_quantile(0.99, sum(rate(http_server_request_duration_seconds{service="orders"}[5m])))

# Average latency = sum / count
sum(rate(http_server_request_duration_seconds_sum[5m])) / sum(rate(http_server_request_duration_seconds_count[5m]))

# Saturation: memory working set vs limit per pod
max by (pod) (container_memory_working_set_bytes{namespace="shop"})
  / max by (pod) (kube_pod_container_resource_limits{namespace="shop", resource="memory"})

# Targets that are down
up == 0

Key functions: rate (per-second average over the window, for alerting and graphs), irate (last two samples, spiky), increase (total increase over the window), sum/avg/max/min/count by (labels), topk, histogram_quantile, absent (alert when a series disappears), predict_linear (disk will fill in 4 hours), *_over_time.

Range windows should cover at least 4× the scrape interval so rate has enough samples.

Recording rules

Expensive queries used by dashboards and alerts should be precomputed with recording rules, which also give stable names for SLO computations:

YAML
# rules/orders.yml
groups:
- name: orders-sli
  interval: 30s
  rules:
  - record: service:http_requests:rate5m
    expr: sum by (service) (rate(http_server_request_duration_seconds_count[5m]))
  - record: service:http_errors:rate5m
    expr: sum by (service) (rate(http_server_request_duration_seconds_count{status_code=~"5.."}[5m]))
  - record: service:http_error_ratio:rate5m
    expr: service:http_errors:rate5m / service:http_requests:rate5m

Cardinality

Why it matters

Cardinality is the number of unique time series. For one metric it's the product of the number of distinct values of each label:

series = routes × methods × status codes × pods × buckets …

Example: 50 routes × 4 methods × 10 status codes × 30 pods × 12 histogram buckets = 720,000 series for one histogram. Add a user_id label with 1 million users and the backend falls over.

route50 method4 status10 pod30 buckets12 =720k + user_id1,000,000 values → 720 billion series ✕ put unbounded identifiers in traces, logs or exemplars, not metric labels
Cardinality multiplies. Each label multiplies the number of time series by its number of distinct values; bounded labels like method and status are fine, but an unbounded label such as user ID or request ID turns one metric into millions of series, exploding memory, storage and query cost.

High cardinality costs memory (each active series sits in the TSDB head), storage, query time, and money (most vendors bill per series). Sudden cardinality explosions (a bug that puts raw URLs or error messages into labels) are a common cause of monitoring outages.

Controlling it

  • Never use unbounded values as labels: user IDs, emails, request IDs, trace IDs, raw URLs/paths, SQL text, error messages, timestamps. Use templated routes and error classes.
  • Bucket continuous values into a few ranges if you must (payload size class).
  • Drop or aggregate at the source with OTel views or at collection (metric_relabel_configs drop, Collector filter/transform, Mimir/Grafana adaptive metrics).
  • Monitor cardinality itself: prometheus_tsdb_head_series, top series by metric (topk(10, count by (__name__)({__name__=~".+"})), use carefully), and per-team quotas.
  • Put high-cardinality context in traces and logs, and link with exemplars.

Averages, percentiles and rates

Why averages lie

Latency distributions are skewed with long tails. An average of 120 ms can hide that 2% of requests take 4 seconds. And because users make many requests, most users experience the tail: if a page load makes 20 backend calls, the chance that at least one hits the p99 is 1 − 0.99²⁰ ≈ 18%.

Use percentiles (quantiles):

  • p50 (median): the typical experience.
  • p90 / p95 / p99: the tail; p99 means 1% of requests are slower.
  • p99.9 and max: for very high-volume or critical paths, and for spotting pathological cases.

Percentiles can't be averaged

The average of per-pod p99s is not the fleet p99 (a pod with very few slow requests and one with many get equal weight). The p99 over an hour is not the average of per-minute p99s. To aggregate correctly, aggregate the underlying distributions (sum histogram buckets) and compute the percentile from the combined distribution. This is why histograms beat summaries.

Also remember percentiles from histograms are estimates limited by bucket resolution (native/exponential histograms improve this a lot).

Rates and windows

  • Rate = change per unit time. Request rates, error rates, throughput.
  • Window length trades responsiveness for noise: rate(...[1m]) reacts fast but is noisy; [1h] is smooth but slow. Alerting uses multiple windows (chapter 102).
  • Error ratio (errors / total) is usually better than absolute error counts: 100 errors/min is a crisis at 200 req/min and noise at 1 million req/min.

Saturation

Saturation measures how full a resource is, and how much work is waiting:

  • CPU: utilisation and run-queue length, cgroup throttling (container_cpu_cfs_throttled_periods_total).
  • Memory: working set vs limit; swap; OOM kills.
  • Thread/connection pools: active vs max, wait time to acquire.
  • Queues: depth and age of oldest message.
  • Disk: I/O queue depth, await; file descriptors used vs limit.
  • Downstream quotas: rate-limit headroom.

Saturation is the leading indicator: latency degrades as utilisation approaches 100% (chapter 105 shows why with queueing theory), so alert on saturation before errors appear.

What to monitor: golden signals, RED and USE

Google's SRE book names four golden signals for any user-facing system:

Signal Question Typical metric
Latency How long do requests take? (Separate successful from failed request latency: fast errors can make latency look good) Duration histogram, p50/p95/p99
Traffic How much demand? Requests/s, messages/s, concurrent sessions
Errors How many fail? (Explicit 5xx, wrong content, policy violations like "too slow") Error ratio
Saturation How full is the system? Utilisation, queue length, pool usage

Two derived methods make it practical:

  • RED (Tom Wilkie), for request-driven services: Rate, Errors, Duration, for every service and endpoint. Spans (via the span metrics connector) or HTTP instrumentation give these for free.
  • USE (Brendan Gregg), for resources: Utilisation, Saturation, Errors, for every CPU, memory, disk, network interface, and pool (Vol. 6 ch. 79).

RED tells you users are affected; USE tells you why (which resource is the bottleneck).

Instrumenting code

// Java: Micrometer (Spring Boot's metrics facade; exports to Prometheus or OTLP)
@Component
class OrderMetrics {
    private final Counter placed;
    private final Timer pricing;
    private final AtomicInteger inFlight = new AtomicInteger();

    OrderMetrics(MeterRegistry registry) {
        this.placed = Counter.builder("orders.placed").tag("channel", "web").register(registry);
        this.pricing = Timer.builder("orders.pricing.duration")
            .publishPercentileHistogram()                        // histogram buckets → aggregatable quantiles
            .serviceLevelObjectives(Duration.ofMillis(300))       // bucket exactly at the SLO threshold
            .register(registry);
        Gauge.builder("orders.in_flight", inFlight, AtomicInteger::get).register(registry);
    }

    Order place(Cart c) {
        inFlight.incrementAndGet();
        try {
            Order o = pricing.record(() -> priceAndSave(c));
            placed.increment();
            return o;
        } finally { inFlight.decrementAndGet(); }
    }
}
// Spring Boot exposes /actuator/prometheus; HTTP server metrics (http.server.requests) are automatic.

Dashboards

A dashboard should answer a specific question for a specific audience:

  • Service overview (one per service, same layout everywhere): RED for each endpoint, saturation of its resources, dependencies' RED, SLO status and error budget, deploy annotations.
  • SLO dashboard (chapter 102): SLIs vs targets, budget remaining, burn rates.
  • Capacity dashboard: utilisation trends, forecasts.

Design rules: put the most important (user-facing) panels top-left; show rates and percentiles, not raw counters or averages; use consistent units and time ranges; annotate deploys; link panels to traces (exemplars) and logs; avoid walls of 40 graphs nobody reads. Manage dashboards as code (Grafana JSON or Jsonnet/Grafonnet, Grafana's Terraform provider, dashboards generated from service templates).

Lab: cardinality, resets and percentile traps

Prometheus 3.15 (1-second scrapes, 15 seconds for the high-cardinality job) scraping four small Python services built with prometheus_client 0.26: a counter labelled by route and status, the same counter with a user_id label for 10,000 users, and two instances of one service with different latency.

Experiment 1: one label, 1,400× the series

Text
without user_id:  head series 112,     Prometheus RSS 87 MiB
with user_id:     head series 160,128, Prometheus RSS 350 MiB
the app's /metrics page: 3 KB → 12.2 MB; one scrape took 1.3–2.4 s
first attempt with a 1 s scrape interval: scrape_samples_scraped 0, scrape_duration_seconds 1.0 (timed out, target down)

Three costs hit at once:

  • The monitoring system: 160,000 series took about 260 MiB more memory in Prometheus's head block (roughly 1.7 KB per series here, including labels and indexes) before any long-term storage, and every query touching the metric now scans 20,000× more series.
  • The service: rendering 12 MB of text on every scrape costs it 1–2 seconds of CPU, which in Python also holds the GIL that request handling needs.
  • Observability itself: with the default timeout the target simply went down, so you lose all its metrics, not just the new ones.

Why 160,128 and not 80,000? 4 routes × 2 statuses × 10,000 users = 80,000 counters, and the Python client also exposes a _created timestamp series for each (set PROMETHEUS_DISABLE_CREATED_SERIES=True to turn those off). Check what your client library actually emits before estimating.

How you'd find it in production: topk(10, count by (__name__) ({__name__=~".+"})) shows the metrics with the most series, and Prometheus's TSDB status page (/tsdb-status) lists the label names with the most values. Fixes: drop the label in code, or at scrape time with metric_relabel_configs (action labeldrop), set sample_limit per job so one bad deploy can't take down Prometheus, and move per-user questions to logs and traces.

Experiment 2: a counter reset mid-window

The route service was killed and restarted, so its counters dropped from about 2.6 million to zero:

Text
resets(app_requests_total{route="/order",status="200"}[45s])   1
sum(increase(app_requests_total[45s]))                          394,773
sum(max_over_time(…[45s]) - min_over_time(…[45s]))            2,612,000   ← wrong
sum(rate(app_requests_total[45s]))                              8,773 per second

rate() and increase() treat any decrease as a reset and add the post-reset value, so they stay right. Hand-rolled arithmetic on raw counter values doesn't. Two corollaries: always rate() before sum() (summing raw counters from several instances mixes their resets), and expect small extrapolation effects: increase() estimates the window's edges, which is why it returned a non-integer for whole requests.

Experiment 3: percentiles across instances

Two instances of one service: the fast one serves 900 requests per second with a 20 ms mean latency, the slow one (on a busy node) 100 per second with a 300 ms mean. Buckets: 10, 25, 50, 100, 250, 500 ms, 1, 2.5 s.

Text
p99, fast instance (from its histogram)            0.098 s     exact from raw samples: 0.092 s
p99, slow instance (from its histogram)            2.130 s     exact from raw samples: 1.452 s
average of the two p99s                             1.114 s     ← meaningless
p99 of the combined histogram (sum by le)           0.811 s     exact from raw samples: 0.693 s

Two lessons. First, aggregate distributions, not percentiles: histogram_quantile(0.99, sum by (le) (rate(…_bucket[1m]))) weights each instance by its traffic; the average of p99s gave the slow instance's 10% of traffic half the weight. Second, histogram percentiles are estimates bounded by bucket width: the slow instance's p99 fell in the 1–2.5 s bucket and linear interpolation reported 2.13 s against a true 1.45 s. Put bucket boundaries where your SLO thresholds and typical latencies are, or use native histograms (exponential buckets with a few percent error; Prometheus 3 supports them, and the Go and Java clients emit them; the Python client doesn't yet).

Try it yourself

  1. Add metric_relabel_configs: [{action: labeldrop, regex: user_id}] to the users job. What happens to the counters for different users that now share a label set?
  2. Add sample_limit: 50000 to the job and look at the target's error.
  3. Change the buckets to include 1.5 s and 2 s and recompute the slow instance's p99.

Revision sheet: metrics

Key ideas

  • Data model: name + labels = series; samples of (timestamp, value).
  • Types: counter (rate/increase), gauge, histogram (buckets, _sum, _count), summary (client-side quantiles, not aggregatable); OpenTelemetry instruments map onto these.
  • Prometheus: pull scrapes, service discovery, PromQL, recording and alerting rules, remote write to Mimir/Thanos/Cortex/managed services.
  • Cardinality: series = product of label values; keep labels bounded; drop or limit at scrape time.
  • Percentiles: averages lie; percentiles aren't averageable; aggregate histogram buckets; bucket choice limits accuracy; native histograms.
  • What to measure: golden signals (latency, traffic, errors, saturation), RED for services, USE for resources.

Numbers to remember

  • Lab: one user_id label → 112 to 160,128 series, 87 to 350 MiB Prometheus RSS, a 12 MB metrics page and scrape timeouts.
  • Counter restart: increase() 394,773 (right) vs max − min 2,612,000 (wrong).
  • Combined p99 0.81 s vs average of p99s 1.11 s.

Pitfalls

  • Unbounded labels (IDs, URLs, emails, error messages).
  • sum() before rate(); arithmetic on raw counters.
  • Averaging percentiles; summaries when you need aggregation.
  • Buckets that don't straddle the SLO threshold.
  • Rate windows shorter than about four scrape intervals.

Glossary

  • Head block: Prometheus's in-memory recent data.
  • Recording rule: precomputed query saved as a new series.
  • Exemplar: trace ID attached to a sample.
  • Native histogram: sparse exponential-bucket histogram in one series.
  • Relabelling: rewriting or dropping targets and labels at discovery or scrape time.