Metrics

What a metric is

Four words come up all the time:

  • Metric: a named measurement, like http_requests_total.
  • Label: a key="value" tag on a measurement, like method="GET". (OpenTelemetry calls it an attribute.)
  • Time series: one stream of numbers for one metric name plus one exact set of labels. Change one label value and you get a different series.
  • Sample: one point in a series: a timestamp and a number. If Prometheus reads the series every 15 s, that is 4 samples a minute and 5,760 a day.
The metric name http_requests_total fans out into four series, each a distinct set of label values, each holding its own stream of timestamp and value samples at a 15 second scrape interval. The fourth series, with an added route label, starts later and is highlighted in red because adding a label value created a brand new series.
The metric data model: a name plus labels names a stream of samples. Read it as: every distinct label combination is its own independent stream. Series 4 appeared at t+45s because a code change started emitting route on one path: nothing was "added to" series 3, a new time series was created, with its own memory and its own index entries.

Prometheus collects metrics by reading a plain-text page. Each line is one sample: the name, the labels in braces, then the value.

# HELP http_requests_total Total HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 1140
http_requests_total{method="GET",status="500"} 6
http_requests_total{method="POST",status="200"} 281
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.1"} 13
http_request_duration_seconds_bucket{le="+Inf"} 40
http_request_duration_seconds_sum 14.2
http_request_duration_seconds_count 40

How to read the histogram lines. Say 40 requests have finished since the app started:

LineWhat it means
_bucket{le="0.1"} 1313 requests took 0.1 s or less.
_bucket{le="+Inf"} 4040 requests took any time at all. That is every request.
_sum 14.2All the request durations added together come to 14.2 seconds.
_count 4040 requests in total.

From these four lines you can work out that 40 − 13 = 27 requests were slower than 0.1 s, and that the average is 14.2 / 40 = 0.355 s. A real histogram has more buckets (0.25, 0.5, 1 and so on). Only two are shown here to keep the example short.

The four metric types

The type tells you how to read the number. To pick one, ask: does it only go up, does it go up and down, or do I need percentiles?

TypeWhat it isUse it forWatch out
CounterOnly goes up (back to 0 if the app restarts). Read it with rate().Requests, errors, bytes sent, jobs doneNever graph the raw counter. Never use it for a value that can go down.
GaugeThe value right now. Goes up and down. Read it directly.Queue depth, memory in use, in-flight requestsDo not use it to count events. Anything that happens between two readings is invisible.
HistogramCounts measurements into buckets, plus a sum and a count. Can be added across pods.Latency, payload size: anything you want percentiles ofPut a bucket edge exactly on your SLO number (see below).
SummaryEach app works out its own percentiles and sends only the result.Rarely. One process, fixed percentiles.Never add or average summaries across pods. The answer is wrong.

Histograms

A histogram answers "how long do requests take?" without storing every request. It is the most important metric type for latency, and the one that is easiest to get wrong.

The idea: a row of jars

Picture jars labelled ≤ 50ms, ≤ 100ms, ≤ 250ms, ≤ 500ms, ≤ 1s and +Inf. When a request finishes, you drop a marble into the jar for its duration. You do not keep the exact time (137 ms). You only keep "between 100 and 250 ms".

This keeps the cost fixed: about a dozen numbers per pod, whether you serve 10 or 10,000 requests a second.

What Prometheus actually stores

  • One counter per bucket. Each is labelled le ("less than or equal") with its upper limit.
  • Buckets are cumulative. le="0.5" counts every request ≤ 0.5 s, including the ones already counted in le="0.1".
  • The last bucket, le="+Inf", counts everything. It always equals _count.
  • _count is the number of requests. _sum is all their durations added up.

Example: four requests of 0.1, 0.2, 0.3 and 1.4 s give _count = 4 and _sum = 2.0, so the average is 2.0 / 4 = 0.5 s. This average is exact. Only the percentiles are estimates.

A bar chart of seven cumulative histogram buckets with upper bounds 0.05, 0.1, 0.25, 0.5, 1, 2.5 and plus infinity, with cumulative counts 4, 13, 26, 33, 37, 39 and 40. A red dashed line at rank 36 crosses the le equals 1 bucket, from which histogram_quantile interpolates a p90 of about 0.875 seconds.
Cumulative le buckets: every bucket includes everything below it. Read it as: each bar is the cumulative count (light = already counted by the bucket to its left, dark = observations that landed in this bucket). The last bucket always equals _count. Prometheus finds the bucket where the target rank crosses a bar and interpolates inside it, so the answer is only as precise as the bucket is narrow.

How a percentile is estimated

p90 means "90% of requests were faster than this". The histogram only knows how many requests landed in each bucket, not their exact times. So Prometheus has to guess. Here is the p90 from the diagram above:

Step 1: find the right bucket.

  • Line up the 40 requests from fastest to slowest. p90 is request number 36 (90% of 40).
  • 33 requests took 0.5 s or less. 37 took 1 s or less. So request 36 is somewhere between 0.5 s and 1 s.
  • That bucket holds 4 requests (numbers 34 to 37). Request 36 is the 3rd of the 4.

Step 2: guess where it sits inside the bucket.

  • Prometheus cannot see the real times, so it pretends the 4 requests are spread evenly between 0.5 s and 1 s.
  • The 3rd of 4 is 3/4 of the way across. 0.5 + (3/4 × 0.5) = 0.875 s.

This kind of even-spread guess is called linear interpolation.

Why the guess can be wrong:

  • Say those 4 requests all really took 0.51 s. The true p90 is 0.51 s, but Prometheus still says 0.875 s. It cannot see inside the bucket.
  • The error can be as big as the bucket is wide. Take one wide bucket from 1 s to 10 s. A true p99 of 1.1 s and a true p99 of 9.9 s would both come out as about the same answer, because Prometheus cannot tell them apart.

Narrow buckets give close guesses. Wide buckets give useless ones.

Put a bucket edge on your SLO

More buckets cost more

Prometheus stores every bucket as its own series, once for each label combination. Say you have 50 routes × 4 status codes × 5 pods = 1,000 combinations.

  • A counter costs 1,000 series.
  • A histogram with 12 buckets costs 12 buckets + _sum + _count = 14 series per combination, so 14,000 series.

More buckets give better guesses but multiply storage. Add edges where they matter (around your SLO), not everywhere.

Two kinds of histogram

Classic (explicit buckets)

You pick the edges in code. Each bucket is a separate series. Prometheus client default: .005 .01 .025 .05 .1 .25 .5 1 2.5 5 10 seconds. OTel's default edges are 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000 (in milliseconds). If you guess badly, you cannot fix it after the fact.

Native / exponential

The edges are computed for you. Each edge is a fixed factor bigger than the last (schema 3 ≈ 1.09×), so the error is about 4–9% at any size. Only non-empty buckets are stored, and the whole histogram is one sample, so cardinality drops sharply. Native histograms are stable in Prometheus v3.8, but you must switch on scraping them (scrape_native_histograms: true).

Average latency: use rate() on both _sum and _count

The goal: the average latency over the last 5 minutes, not since the pod started. _sum and _count never reset. They only grow, like a car's odometer. Dividing them directly gives the average over the pod's whole life, which barely moves when something breaks. Example, a pod that has been up for weeks:

Time_count_sumLifetime average (_sum / _count)
10:001,000,000100,000 s0.10 s
10:051,060,000130,000 s0.12 s (looks fine)

A million old fast requests drowned out the new slow ones. To see what happened in the 5 minutes, ignore the old totals and look only at what was added.

The fix, in three steps:

  1. Take two readings: the one from 5 minutes ago (10:00) and the one now (10:05).
  2. Subtract. New requests = 1,060,000 − 1,000,000 = 60,000. New time spent = 130,000 − 100,000 = 30,000 s.
  3. Divide. 30,000 s ÷ 60,000 requests = 0.5 s per request. That is five times slower, and the lifetime average hid it.

That subtraction is what rate() does. rate(x[5m]) means "how much did x grow over the last 5 minutes, per second" = (growth) ÷ 300. Run it on both counters and divide:

  rate(http_request_duration_seconds_sum[5m])
/ rate(http_request_duration_seconds_count[5m])
  • rate(_sum[5m]) = 30,000 / 300 = 100 (seconds of work done per second)
  • rate(_count[5m]) = 60,000 / 300 = 200 (requests per second)
  • 100 / 200 = 0.5 s. The ÷ 300 appears on both sides and cancels, so the answer is exactly step 3.

rate() also copes with a pod restart (the counters drop back to 0, and it does not read that as a huge negative drop). A hand-written subtraction would break there.

Where does the 10:00 reading come from? Not the app. The pod only holds the current totals. Prometheus reads them on a schedule (a scrape, usually every 15–30 s) and saves each reading with its timestamp. That saved list is the time series, and rate() looks back through it. Keep the window at least about 4× the scrape interval ([5m] is safe at a 30 s scrape) so it always contains enough readings.

For a whole service (many pods), add first, then divide:

  sum(rate(http_request_duration_seconds_sum[5m]))
/ sum(rate(http_request_duration_seconds_count[5m]))

# per route: put the same "by" on both sides
  sum by (route) (rate(..._sum[5m])) / sum by (route) (rate(..._count[5m]))

Do not divide per pod and then average the results. Say pod A served 10 requests at 0.1 s and pod B served 1,000 at 1 s. Averaging the two pod averages gives 0.55 s. The true service average is (1 + 1,000) ÷ (10 + 1,000) = 0.99 s, because most requests went to the slow pod. Adding the totals first weights each pod by its traffic.

Limit: an average hides the tail. A few very slow requests barely move it. Use it for a trend line, and use histogram_quantile on the buckets for p95/p99.

Why histograms can be added across pods

Each bucket is a plain count, so counts from different pods add up. Pod A has 900 of 1,000 requests ≤ 100 ms. Pod B has 300 of 1,000. The service has 1,200 of 2,000 requests ≤ 100 ms. That is true, so you can add the buckets first and work out the service-wide p99 from the total.

Histograms ship counts, so you add first and compute the percentile last. Percentiles themselves cannot be added.

Summaries (and why you cannot add them)

A summary works out its percentiles inside the app and sends only the result, like {quantile="0.99"} 0.84. That is accurate for one process, but it throws information away. It says "my p99 is 100 ms" and does not say how many requests that came from.

Here are two pods on two different days. Each day the dashboard receives exactly the same two numbers:

Pod APod BTrue service p99
Day 19,950 requests, all 100 ms50 requests, all 4 s100 ms (only 0.5% are slow)
Day 250 requests, all 100 ms9,950 requests, all 4 s4 s (99.5% are slow)
  • On both days the pods send "p99 = 100 ms" and "p99 = 4 s". Averaging gives about 2 s on both days, which is wrong on both days.
  • No formula can fix this, because the right answer depends on the request counts, and the summary threw them away.
  • A histogram sends the counts ("9,950 in the ≤ 100 ms bucket, 50 in the ≤ 4 s bucket"), so adding the pods' buckets tells Day 1 and Day 2 apart.

Fixed percentiles are also decided at deploy time. Use a summary only if you need exact percentiles from one process and will never combine them.

OpenTelemetry instruments

An instrument is the object in your code that you hand numbers to. OpenTelemetry (OTel) has its own set. They differ in two ways:

  • What kind of number: a count that only goes up, a count that goes up and down, a distribution (like latency), or a current reading (like temperature).
  • Who calls it:
    • A synchronous instrument is called by your code the moment something happens: "a request just finished, it took 120 ms".
    • An asynchronous (observable) instrument works the other way round. You give OTel a small function, and OTel calls it once per export to ask for the current value: "how many connections are in the pool right now?" Use it when the number already lives somewhere else.
OTel instrumentWho calls itWhat you give itBecomes in Prometheus
Counteryour code"add 1" (or add N). Never negative.Counter (_total)
UpDownCounteryour code"add 1" or "subtract 1"Gauge
Histogramyour codeone measurement each time ("this request took 0.12 s"). OTel sorts it into buckets.Histogram
Gaugeyour code"the value is now X". Only the latest value is kept.Gauge
ObservableCounterOTel asks youthe running total so far (e.g. total CPU seconds)Counter
ObservableUpDownCounterOTel asks youa total that can also fall (e.g. pool size)Gauge
ObservableGaugeOTel asks youa current reading (e.g. memory used, read from /proc)Gauge

UpDownCounter or Gauge? Ask: "does adding this number across pods make sense?"

  • Active connections: pod A has 40, pod B has 60, the service has 100. Adding works, so use an UpDownCounter.
  • CPU temperature: 60° + 70° = 130° means nothing, so use a Gauge. The same goes for ratios and percentages.

Counters: cumulative vs delta

When an app sends a counter's value, it can send it in one of two styles. This is called temporality. Say a request counter reads 1,140 at one export and 1,171 at the next:

  • Cumulative sends the running total each time: 1140, then 1171. Like a car's odometer.
  • Delta sends only what changed since the last send: 31. Like a trip meter that resets after each reading.

Prometheus only understands cumulative. It stores the running totals and works out the change itself with rate(). This has two benefits:

  • If one reading is lost, nothing is lost for good, because the next total still includes everything.
  • If a pod restarts, the total drops to 0. Prometheus spots the drop and handles it.

With delta, a lost send is a lost chunk of data.

Example 1: a lost reading

The pod's counter keeps counting no matter what. Prometheus just reads it every 15 s.

TimePod's counterWhat Prometheus got
10:00:001,0001,000
10:00:151,030lost (network blip)
10:00:301,0701,070

There is no 10:00:15 reading, and none is needed. 1,070 − 1,000 = 70 requests between 10:00:00 and 10:00:30, which is exactly right, because the missed 30 are already inside the 1,070. You only lose when inside those 30 s they happened.

With delta, the pod would have sent "+30" at 10:00:15 and forgotten it. If that message is lost, those 30 requests are gone for good, because the next message only says "+40".

Example 2: a restart

A restart wipes the pod's memory, so its counter starts again from 0. Prometheus does not keep a separate "corrected" count. It stores the raw readings exactly as they arrived, drop included, and rate() fixes the numbers each time a query runs:

TimeStored readingDrop?Corrected by rate()
10:00:001,0001,000
10:00:151,0301,030
10:00:3025yes: pod restarted25 + 1,030 = 1,055
10:00:456060 + 1,030 = 1,090
  • The rule: a counter should never go down. When rate() sees a reading lower than the one before (1,030 → 25), it assumes a restart and adds the last value before the drop (1,030) to everything after.
  • The result: growth is 1,090 − 1,000 = 90 requests in 45 s, so the rate is 90 / 45 = 2 requests per second. No negative dip.
  • Nothing is rewritten. The correction happens inside each query and is thrown away afterwards. The stored data still says 25. That is why a raw counter graph looks like a sawtooth, and why you never graph one.
  • How the graph is drawn: Grafana does not plot the stored readings. For each point on the x-axis (say every 15 s) it asks Prometheus to run rate(x[5m]) as of that moment. Each answer is one dot, and joining the dots gives the line.
  • The small catch: if the pod reached 1,050 before it crashed, but the last reading was 1,030, those 20 requests died with the pod. rate() cannot recover them. Around a restart you can lose up to one scrape interval of counts. That is tiny at 15 s.

Why delta exists, and what to do with it

  • Why delta exists: it is cheaper for the app. With cumulative, the app must remember every total forever, even for a label value that showed up once. With delta it sends the change and forgets it. Some backends (Datadog, Dynatrace, New Relic) prefer delta.
  • How to choose: set OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE to cumulative (the default), delta or lowmemory.
  • Common mistake: sending delta to Prometheus. It expects totals, so the numbers come out wrong.
  • If an app sends delta anyway: convert it in the OpenTelemetry Collector. Its deltatocumulative processor adds the changes into running totals: app sends +30, +40, +25 → Collector keeps 30, 70, 95 → Prometheus gets totals. This only works if the Collector receives every delta.

Combining series: rate first, then sum

"Aggregate" means "combine many numbers into fewer". In PromQL you can do it in two directions, and people mix them up:

DirectionWhat it doesExampleCalled
Across timeOne series, many moments → one numberrate(x[5m]) turns 5 minutes of readings into requests per secondrange functions
Across seriesMany series, one moment → fewer seriessum by (route) (...) adds all pods, so you get one line per routeaggregation operators

The order matters. Do sum(rate(http_requests_total[5m])): rate each pod first, then sum. Never do rate of an already-summed total.

Why: when a counter drops, rate() assumes it restarted from 0 and adds back the value before the drop. That is true for one pod. It is false for a sum, where only one pod restarted.

Example: two pods, pod A restarts just before 10:00:30

TimePod APod BSum
10:00:005,0003,0008,000
10:00:155,0303,0208,050
10:00:3010 (restarted)3,0403,050
10:00:45403,0603,100

True answer: A served 30 + 10 + 30 = 70, B served 60, so 130 requests in 45 s (≈ 2.9 req/s).

Wrong: sum first, then rate

The summed line drops 8,050 → 3,050, so rate() adds back 8,050. Growth = (3,100 + 8,050) − 8,000 = 3,150 requests, about 70 req/s. That is a fake spike, 24× too high.

Why: only A's 5,030 really vanished. Adding back the whole 8,050 also adds B's 3,040 again, so B's requests are counted twice.

Right: rate each pod, then sum

A: drops 5,030 → 10, so add back 5,030. Growth = (40 + 5,030) − 5,000 = 70.

B: no drop. Growth = 3,060 − 3,000 = 60.

Sum: 70 + 60 = 130. Correct.

How people get this wrong: PromQL makes the wrong order awkward to type, so it sneaks in through:

  • a recording rule that saves sum(http_requests_total) as a new metric, which someone later runs rate() on, or
  • a subquery like rate(sum(http_requests_total)[5m:]).

Every pod restart then shows up as a false spike. A deploy that restarts many pods fills the graph with them.

Histograms follow the same rule, because every bucket is a counter. In order: (1) rate each bucket, (2) sum by (le) across pods, (3) histogram_quantile last.

Cardinality: why labels cost money

Cardinality is how many separate series a metric creates. Prometheus makes a new series for every different combination of label values, so you multiply the number of values of each label:

series(metric) = |values(label1)| × |values(label2)| × … × |values(labeln)| (× (buckets + 2) for a histogram)

Watch how fast one latency metric grows:

Labels on http_request_duration_secondsValuesSeries
method × status × route5 × 8 × 2008,000
… × pod× 100800,000
… × 14 histogram series× 1411.2 million
… replace pod with user_id (1M users)× 1,000,0008 × 109 (never reached; the server dies first)

What it costs: memory

  • Prometheus keeps every active series in RAM. Plan for roughly 3–4 KB of RAM per active series. This is a field rule of thumb, not an official figure (see Prometheus). Check your own number with process_resident_memory_bytes / prometheus_tsdb_head_series.
  • So 10 million series needs about 30–40 GB of RAM, even if they get almost no traffic.
  • Disk is cheap by comparison: about 1.4 bytes per sample. A series read every 15 s (5,760 samples a day) costs about 8 KB of disk per day.

Memory is the real bill. That is why one bad label can crash a server with out-of-memory.

Why user_id must never be a metric label

  • No upper limit. Series count grows with your user base instead of with how your system behaves.
  • Mostly empty series. Each user's series gets only a few samples, so the fixed per-series cost dominates.
  • Churn. Users come and go, so series appear once and never again. This bloats the index.

The same user_id is fine on a log line or a trace, where you pay per event, not per series. Deciding which detail goes on which signal is the main design question of the Cost and vendors part.

How much detail to keep

Four settings decide how much detail you keep, for how long, and how the data reaches the server.

  • Resolution: how often you take a reading.
    • This is the scrape interval, usually 15 s or 30 s (10 s or less if alerts must fire fast).
    • Reading twice as often doubles the samples and the disk used. It does not change the series count or RAM, because it is the same series with more points.
    • A spike shorter than the interval can fall between two readings. A counter still catches it, because the running total includes it. A gauge misses it: if a queue jumps to 5,000 and back to 10 within 15 s, both readings say about 10.
  • Retention: how long you keep the readings. Prometheus keeps 15 days on its own disk by default. For months or years, send the data to a long-term store (see Scaling Prometheus).
  • Downsampling: keep old data in less detail.
    • Nobody needs 15-second points from last year. Downsampling replaces old points with summaries, for example one point per 5 minutes, later one per hour.
    • Prometheus itself never downsamples. Long-term stores such as Thanos do (for blocks older than about 40 hours and 10 days).
    • Fine for "how did traffic grow this year?", too coarse for precise alerting.
  • Pull vs push: who starts the conversation.
    • Pull (the Prometheus way): the server finds targets and visits each one's /metrics page on a schedule. If a target stops answering, you know at once (up == 0), and the server controls how much load it takes.
    • Push: the app sends its numbers to a collector or backend (OTLP, StatsD, Pushgateway). You need this for jobs that finish before anyone can scrape them, and for apps behind a firewall. The catch: an app that stops sending looks the same as an app with nothing to report, so a dead app can go unnoticed.
    • Prometheus 3 can also accept OTLP pushes. More in the Prometheus part.

Traps

The Invariants

  • Guarantees: Series count equals the number of distinct (name, label set) pairs, whatever the traffic. A counter plus rate() survives restarts and missed scrapes. Histogram buckets add across instances, so combined percentiles can be computed, with error limited by bucket width.
  • Does not guarantee: Exact percentiles from classic histograms (they interpolate). Per-event detail (it was discarded). Seeing spikes shorter than the scrape interval in a gauge. A free new label: each new label value is a new series that costs RAM until it ages out of the head.