BEGINNERCHAPTER 04

Metrics 101: counters, gauges, histograms, and cardinality

The Prometheus data model, the four types and what each one is for, and the label that takes the server down

50 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

orders exposes http_requests_total. The pod restarts at 10:04 and the counter falls from 48 212 to 9. You graph rate(http_requests_total[5m]) across 10:00 to 10:10. What does the line do at 10:04?

A metric is a number you are willing to store every fifteen seconds for a year. That constraint is the whole design. Logs can carry anything; a metric carries one number and a handful of labels, which is why a Prometheus server on one machine can hold millions of them and answer a question about last Tuesday in milliseconds. It is also why a single careless label can destroy it. This chapter gives you the data model, the four types, the two functions you will type more than any other, and the arithmetic that tells you in advance whether a label is safe.

The data model

Prometheus stores time series. A series is identified by a metric name and a set of label name/value pairs, written like this:

http_requests_total{job="orders", method="POST", route="/orders", status="200"}

Every distinct combination is a separate series. Change any label value, add a label, remove a label, and you have a new series with its own storage. A series holds samples: a float64 value and a millisecond timestamp. Prometheus pulls a fresh sample from every target on a schedule, the scrape interval, which defaults to 1 minute in a fresh config and is set to 5 s in the lab stack.

Two labels arrive without the service doing anything. job is the scrape job name from prometheus.yml, and instance is the host:port scraped. The lab stack names its jobs after the services, so job="gateway", job="orders" and job="payments" are how you will group by service in every query below.

The /metrics endpoint is plain text. One line per series, with a # HELP and # TYPE comment above each family:

# HELP http_requests_total HTTP requests handled
# TYPE http_requests_total counter
http_requests_total{method="GET",route="/checkout",status="200"} 1832.0
http_requests_total{method="GET",route="/checkout",status="500"} 12.0

That format is the contract. Any process that can print it over HTTP can be scraped, which is why there is an exporter for everything from Postgres to your fridge.

The four types

The type comment tells Prometheus nothing it enforces; it tells the human and the client library how the number behaves. There are four.

type behaviour ask it never
counter only increases, resets to 0 on restart how fast is this happening? rate() graph the raw value; use for things that go down
gauge goes up and down what is it now? what was the max? max_over_time() apply rate(); it has no meaning
histogram counts observations into cumulative buckets, plus _sum and _count what is p95? what share is under 300 ms? pick buckets without looking at the real distribution
summary client-side quantiles over a sliding window, plus _sum and _count p99 of one instance aggregate quantiles across instances

Counters are the default. Requests, errors, bytes, retries, items sold: anything you would say “how many so far” about. The absolute value is rarely interesting, because it depends on when the process started. The slope is interesting, and that is what rate() gives you.

Gauges are measurements: queue depth, in-flight requests, temperature, free memory, the number of goroutines. You read them as they are. max_over_time(inflight_requests[1h]) tells you the worst moment; delta() tells you how much a gauge changed over a window. Applying rate() to a gauge produces a number that means nothing, and PromQL will not stop you.

Histograms turn a stream of observations, almost always durations, into a fixed set of counters. A classic histogram named http_request_duration_seconds exposes three things: http_request_duration_seconds_bucket{le="0.1"} for every bucket bound (le is “less than or equal”), http_request_duration_seconds_sum, and http_request_duration_seconds_count. The buckets are cumulative: the le="0.25" bucket counts every observation at or below 250 ms, including those under 100 ms. The le="+Inf" bucket equals _count. Each bucket is a counter, which is why you can rate() them and why you can add them across instances.

The Python client’s default bounds are .005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0 seconds, chosen for web request latency. That is 15 series per histogram, per label combination. A histogram with method, route and status labels over 20 routes is 20 × 3 × 3 × 15, about 2 700 series, before you add a second service.

Summaries compute quantiles inside the process: http_request_duration_seconds{quantile="0.99"}. They are exact for one instance and useless across many. You cannot combine the p99 of pod A with the p99 of pod B into the p99 of the service; the average of two p99s is not a p99 of anything. The Prometheus docs put it as “aggregating the precomputed quantiles from a summary rarely makes sense.” Since every real service has more than one instance, you will almost never want one. Use a histogram.

rate() and irate()

rate(http_requests_total[5m]) looks at the samples inside the last five minutes for each series, takes the increase from the first to the last sample, divides by the time between them, and extrapolates a little to the ends of the window to account for scrape timing. The result is a per-second rate. With a 15 s scrape interval a 5 m window holds about 20 samples; a 1 m window holds four, which is the smallest range you should use, and it is noisy.

Counter resets are handled inside rate(). When a sample is lower than the one before, Prometheus assumes the counter was reset to zero and adds the previous value back. A pod restart therefore costs you the seconds it was down, not a negative spike. The price of this is a rule: rate first, then aggregate. sum(rate(http_requests_total[5m])) is right; rate(sum(http_requests_total)[5m]) is not valid PromQL, and the version people write by accident, a recording rule that sums counters then rates the result, hides every reset inside the sum where rate() cannot see it.

irate() uses only the last two samples in the range. It reacts instantly and it is noisy, which the docs describe as “should only be used when graphing volatile, fast-moving counters.” Never alert on it: an alert evaluated on two samples pages you on a single scrape. Use rate() for alerts and for anything slower than a few seconds. increase() is rate() multiplied by the window, giving a count instead of a per-second value; it is the same calculation with the same extrapolation, so increase(x[5m]) can be 3.9 when four events happened.

The three queries you will write for every service:

# request rate per service, per second
sum by (job) (rate(http_requests_total[5m]))

# error ratio per service, 0 to 1
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
  /
sum by (job) (rate(http_requests_total[5m]))

# p95 latency per service, seconds
histogram_quantile(0.95,
  sum by (job, le) (rate(http_request_duration_seconds_bucket[5m])))

histogram_quantile

histogram_quantile(φ, buckets) takes a quantile between 0 and 1 and an instant vector of bucket series, each carrying an le label. It finds the bucket where the cumulative count crosses φ of the total, then interpolates linearly inside that bucket, assuming observations are spread evenly across it. That assumption is the source of every histogram’s error: if your buckets are 0.5 and 1.0 and all your requests take 510 ms, p95 reports around 975 ms. The quantile is only as precise as the bucket bounds around it, so look at a real distribution before you choose them and put a bound near every latency you care about, such as your SLO threshold.

Two mechanics matter. You rate() the buckets first so the quantile reflects the last five minutes rather than the lifetime of the process. And when you aggregate you must keep le in the by clause: sum by (job, le). Drop it and you have summed the buckets together into one number, and histogram_quantile returns NaN.

This is what summaries cannot do. Buckets from ten pods add up to the buckets of the service, so one query gives the service’s true p95. Summaries give you ten p95s and no honest way to combine them. The chapter on histograms and percentiles in module two goes further, into why the average of latencies lies and what native histograms change.

Scrape vs push

Prometheus pulls. Every target exposes /metrics; the server fetches it on the interval. This decides several things at once. Prometheus knows when a target is down, because the scrape fails and up{job="orders"} goes to 0; a push system sees only silence. A misbehaving service cannot flood the server, because the server decides when to ask. You can point a second Prometheus, or curl, at any target and see exactly what it exposes, which is the first debugging step in the lab.

Pull has a gap: short-lived jobs. A batch job that runs for 20 s between scrapes is never seen. The answer is the Pushgateway, where the job pushes its final values and Prometheus scrapes the gateway, or in the OpenTelemetry world the Collector, which receives pushed OTLP metrics and exposes them for scraping. The lab stack has both paths: the services expose /metrics directly, and the Collector exposes what the OTel SDK sends it. Both are pull from Prometheus’s point of view.

Pushed metrics have a second cost: the pusher decides the labels, and a pusher that includes something unbounded has no server between it and your storage. The arithmetic below applies either way, but with pull you can drop a label at scrape time with metric_relabel_configs; with push you need the Collector to do it.

Cardinality: the arithmetic

The number of series a metric produces is the product of the number of distinct values of each label:

series = Π (distinct values of label_i) × (buckets, for a histogram)

http_requests_total{method, route, status} with 3 methods, 10 routes and 6 observed statuses is at most 180 series per instance. Add instance for 20 pods and it is 3 600. Fine. Prometheus on a laptop handles a few hundred thousand series with ease; a well-provisioned single server holds low tens of millions. Each active series costs memory for its labels, its index entries and its in-memory chunk; budget a few kilobytes per series and you are in the right order of magnitude.

Now add user_id. The demo app has 1 000 users, so the counter goes from 180 series to 180 000 per instance, and the histogram with it, times 15 buckets. That is on a laptop with a thousand users. With a million users the product is 180 million series for one metric on one instance, and the server is dead long before the loadgen finishes the first pass. The Prometheus instrumentation guide’s own example: filesystem metrics across 10 000 nodes come to around 100 000 series, “fine”; add a per-user quota label and “you would quickly reach a double digit number of millions”, which it calls too much for the current implementation. Brian Brazil’s rule of thumb is to keep any one metric’s cardinality under about 10 label values per label, and a handful of metrics in the hundreds.

The labels that explode are the ones whose values come from data rather than from code: user ids, order ids, email addresses, request ids, raw URL paths with ids embedded (/orders/4521 rather than the route template /orders/{id}), container ids, pod names under churn, IP addresses, full user agents. Anything you would want to search on belongs in a log or a span attribute, where high cardinality is the point. A metric label answers “which of a known, small set”; a span attribute answers “which one exactly”.

Watch two series on the Prometheus server itself. prometheus_tsdb_head_series is the count of active series in the in-memory head block. process_resident_memory_bytes{job="prometheus"} is what that costs. When the first climbs without a deploy, something is leaking labels; find it with

topk(10, count by (__name__) ({__name__=~".+"}))

which lists the ten metric names with the most series, and then count by (user_id) (http_requests_total) or the equivalent to see which label is doing it. The emergency fix is a metric_relabel_configs rule with action: labeldrop and regex: user_id on that scrape job; the real fix is deleting the label from the code, which you do in the lab.

Naming, units and the things that bite

Prometheus naming has conventions, and tools assume them. Counters end in _total. Base units, not derived ones: _seconds, _bytes, not _milliseconds or _megabytes. Suffixes describe what is measured, not the type: http_request_duration_seconds, not http_request_latency_histogram. Label names are snake_case; label values can be anything, which is the problem.

A few things catch everyone once. A counter that is never incremented does not exist until the first .inc(), so rate() on a brand-new error counter returns nothing rather than zero; initialise the label combinations you know at start-up with .labels(...).inc(0) or guard with or vector(0) in the query. A gauge for in-flight requests that is incremented in one code path and decremented in a path that is skipped on an exception drifts upward forever. A histogram whose buckets stop at 10 s makes a 40 s request look like “somewhere above 10 s”, and the p99 pins at 10. And the five-minute lookback window means a series whose target has stopped exposing it keeps returning its last value for five minutes before it goes stale, so a dashboard can look healthy for five minutes after a pod has lost its metric.

LAB Read /metrics, write the three queries, then explode the series count ~30 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2the ATLAS repo cloned, with labs/observabilitycurl and a browserabout 2 GB of RAM free for the stack

Start the demo app with the telemetry stack and let the load generator run for two minutes so there is something to query.

cd labs/observability
OTEL_SDK_DISABLED=false docker compose --profile telemetry up -d

1. Read the raw metrics.

curl -s http://localhost:8080/metrics | grep -E '^(# TYPE|http_requests_total|http_request_duration_seconds_bucket)' | head -30
curl -s http://localhost:8081/metrics | grep -c '^http_request_duration_seconds_bucket'
Text, one series per line. # TYPE http_requests_total counter, then lines like http_requests_total{method="GET",route="/checkout",status="200"} 614.0. The second command prints the number of bucket series orders exposes: the lab sets its own 13 bounds (5 ms to 10 s, with 1.5, 2 and 3 s added for the slow-payments fault) plus +Inf, so 14 per method × route × status combination, which is 14 while every order succeeds. Note that every bucket value is at least as large as the bucket below it, and le="+Inf" equals _count. Count how many lines the whole endpoint has; that is this instance’s contribution to prometheus_tsdb_head_series.

2. Confirm the scrape and write the three queries. Open http://localhost:9090/targets and check that gateway, orders, payments, otel-collector, otel-collector-internal and prometheus are UP. Then in http://localhost:9090/graph run each of these, switching to the Graph tab:

sum by (job) (rate(http_requests_total[1m]))
sum by (job) (rate(http_requests_total{status=~"5.."}[1m]))
  / sum by (job) (rate(http_requests_total[1m]))
histogram_quantile(0.95, sum by (job, le) (rate(http_request_duration_seconds_bucket[1m])))
Three lines in the first graph, one per service, each near 5 requests per second (the LOADGEN_RPS default), because one checkout is one request to each service. The error ratio is empty or 0, because the fault switches are off; an empty result for a division where the numerator has no series is normal, and or vector(0) would fix it. The p95 shows gateway highest and payments lowest, since each hop includes the ones below it, somewhere between 20 and 200 ms on a laptop. Try removing le from the by clause: the result is NaN.

3. Watch the series count before you break it.

prometheus_tsdb_head_series
process_resident_memory_bytes{job="prometheus"} / 1024 / 1024
A flat line in the low thousands (the stack plus Prometheus’s own metrics), and a resident memory figure of roughly 60 to 150 MB. Write both numbers down.

4. Add a user_id label to the request counter. The counter lives in services/common/metrics.py, shared by all three services, and is updated by an ASGI middleware that sees the raw scope. It looks like this:

REQUESTS = Counter(
    "http_requests_total", "HTTP requests handled", ["method", "route", "status"]
)
# ... in PrometheusMiddleware.__call__, in the finally block:
            REQUESTS.labels(method=method, route=route, status=status).inc()

Change both places so the user id from the query string becomes a label (add from urllib.parse import parse_qs at the top):

REQUESTS = Counter(
    "http_requests_total", "HTTP requests handled", ["method", "route", "status", "user_id"]
)
# ...
            user_id = parse_qs(scope.get("query_string", b"").decode()).get("user", ["none"])[0]
            REQUESTS.labels(method=method, route=route, status=status, user_id=user_id).inc()

Each service’s image copies common/ at build time, so rebuilding only the gateway changes only the gateway. Rebuild it and raise the load so the thousand users arrive faster:

LOADGEN_RPS=50 OTEL_SDK_DISABLED=false docker compose --profile telemetry up -d --build gateway loadgen

Now re-run the prometheus_tsdb_head_series query every 30 seconds, and this one:

count by (job) (http_requests_total)
The gateway’s count climbs from a handful to about 1 000 within a couple of minutes, one series per user the loadgen has used, and prometheus_tsdb_head_series climbs by the same amount. Resident memory rises by a few megabytes: a thousand series is small. Now do the arithmetic the lab cannot: the production shop has 500 000 customers, so the same change is 500 000 series for one counter on one instance, and if you had added the label to the histogram as well it is 7.5 million. Run topk(5, count by (__name__) ({__name__=~".+"})) and http_requests_total is at the top, which is how you would find this in an incident.

5. Remove it. Revert the two edits, rebuild, and watch the count fall:

git checkout -- services/common/metrics.py
LOADGEN_RPS=5 OTEL_SDK_DISABLED=false docker compose --profile telemetry up -d --build gateway loadgen
The new gateway exposes the old series. The thousand user_id series stop receiving samples and go stale after five minutes; prometheus_tsdb_head_series drops back when the head block is next cut, up to two hours later. Series are cheap to create and slow to forget, which is why the fix has to be in the code and not in a dashboard.
Instead of removing the label from the code, keep it and add this to the gateway job in prometheus/prometheus.yml, then docker compose restart prometheus (or kill -HUP the process): a metric_relabel_configs entry with action: labeldrop and regex: user_id. The series count falls back, because the label is stripped before storage. Then look at the gateway’s /metrics output: still a thousand lines, still built and serialised on every scrape. You have moved the cost from the server to the scrape, and anyone who points a second scraper at that endpoint gets the explosion. Relabelling is the tourniquet; the code change is the surgery. Undo both before moving on (git checkout -- services/common/metrics.py prometheus/prometheus.yml, then rebuild the gateway and restart Prometheus): later chapters assume neither.
DECIDE

Your account manager wants a dashboard panel: p95 checkout latency per customer, for the 40 enterprise accounts, out of 500 000 customers total. The request counter and the latency histogram currently have method, route and status labels. How do you give them the panel?

READING
  1. DOC
    Prometheus: Metric types

    The canonical definitions of counter, gauge, histogram and summary, including the _bucket, _sum and _count series a classic histogram exposes. Ten minutes; read it before the data model page.

  2. DOC
    Prometheus: Data model

    What a time series is, the notation, and the sentence that explains cardinality: changing any label value, adding or removing a label, creates a new series.

  3. DOC
    Prometheus: Query functions

    The reference for rate(), irate(), increase() and histogram_quantile(). Read the rate() entry for counter resets and extrapolation, and the histogram_quantile() entry for the le requirement. Skip the trigonometric functions.

  4. DOC
    Prometheus: Histograms and summaries

    Why summaries cannot be aggregated and histograms can, the error from bucket interpolation, and the Apdex example. The native histograms section previews module two.

  5. DOC
    Prometheus: Instrumentation best practices

    The 'Do not overuse labels' section with the 10 000 nodes times 10 000 users example, and the guidance on which things to count, which to time, and how to name them.

  6. POST
    Cardinality is key Brian Brazil, 2019

    The rule of thumb (keep each metric under about 10 label values; a handful can reach 100) from the author of the Prometheus book, and why moving a label value into the metric name does not help.

  7. POST
    How we scaled our Prometheus setup trivago engineering, 2022

    The incident in the Why: pod churn as a label, OOM kills, and the fixes in order of desperation. Read for the shape of a cardinality incident; skip the Thanos details until module four.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Distributed tracing 101: spans, context, propagation →