Sub topic 4
Counters, gauges, histograms, and summaries
Every Prometheus metric has a type. The type tells you which PromQL functions make sense and which ones return nonsense. This chapter assumes you know the metric data model (names, labels, series) from the previous chapter, and that you can run a query in the Prometheus web interface. Prometheus defines four types: counter, gauge, histogram, and summary.
One detail first. The server does not store the type as a property of the series. The type appears in the # TYPE line of the text exposition format that exporters serve, and client libraries enforce it. In PromQL you must remember the type yourself. A naming convention helps: counters end in _total, and values with units carry the unit in the name, such as _seconds or _bytes.
Counters
A counter is a number that only goes up, or resets to zero when the process restarts. Use it for things that accumulate: requests served, bytes sent, CPU seconds spent, errors raised.
# HELP http_requests_total Total HTTP requests handled.
# TYPE http_requests_total counter
http_requests_total{method="get",code="200"} 10234
http_requests_total{method="get",code="500"} 17The raw value of a counter is rarely useful. A value of 10234 does not tell you whether traffic is high now. The useful quantity is the rate of change, which rate() computes over a time window:
# Requests per second, averaged over the last 5 minutes
rate(http_requests_total[5m])
# Network receive throughput per server, in bits per second
8 * sum by (instance) (rate(node_network_receive_bytes_total{device!="lo"}[5m]))
# Total new requests over the last hour
increase(http_requests_total[1h])rate() detects resets. If a sample is lower than the one before it, rate() assumes the counter restarted from zero and adjusts the result. This is why you should never compute value_now - value_before yourself.
Three rules keep counter queries correct:
- Apply
rate()first, then aggregate. Writesum(rate(x[5m])), neverrate(sum(x)[5m]). If you sum first, a reset in one series looks like a drop in the total and the reset is not detected correctly. - Make the range window at least four times the scrape interval. With a 15 s interval,
[1m]is the practical minimum. A window with fewer than two samples returns nothing. - Use
increase()for "how many in this period" andrate()for "how fast".increase()israte()multiplied by the window length in seconds.
Gauges
A gauge is a value that can go up and down. It is a snapshot of the current state: memory available, load average, temperature, number of open connections, free disk bytes.
# Use the value directly
node_memory_MemAvailable_bytes
# Smooth a noisy gauge over 10 minutes
avg_over_time(node_load1[10m])
# Peak memory use over the last day
max_over_time(node_memory_Active_bytes[1d])
# Is free disk space shrinking? Predict free bytes in 4 hours
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[1h], 4 * 3600)Do not call rate() on a gauge. It treats every decrease as a counter reset and produces misleading output. For a gauge's change over time, use delta() or deriv().
A gauge has a weakness: Prometheus only sees it at scrape time. A spike that rises and falls between two scrapes is invisible. If you need to catch short events, expose a counter or a histogram instead, because these accumulate information between scrapes.
Histograms
A histogram records observations, such as request durations or response sizes, by counting how many fell into each of a set of buckets. One histogram produces three kinds of series:
<name>_bucket{le="..."}is a cumulative count of observations less than or equal to the boundle.<name>_sumis the sum of all observed values.<name>_countis the number of observations. It equals the+Infbucket.
# TYPE request_duration_seconds histogram
request_duration_seconds_bucket{le="0.1"} 240
request_duration_seconds_bucket{le="0.5"} 900
request_duration_seconds_bucket{le="1"} 980
request_duration_seconds_bucket{le="+Inf"} 1000
request_duration_seconds_sum 312.4
request_duration_seconds_count 1000All of these series are counters, so you apply rate() to them. Buckets are cumulative: the 0.5 bucket includes the 240 requests from the 0.1 bucket.
You estimate a percentile with histogram_quantile(). Prometheus itself exposes a histogram you can try on any installation:
# 95th percentile request duration, per handler
histogram_quantile(
0.95,
sum by (handler, le) (rate(prometheus_http_request_duration_seconds_bucket[5m]))
)
# Mean request duration from _sum and _count
sum(rate(prometheus_http_request_duration_seconds_sum[5m]))
/
sum(rate(prometheus_http_request_duration_seconds_count[5m]))The le label must survive the aggregation, so it appears in the by clause.
The result is an estimate. Prometheus assumes observations are spread evenly inside a bucket and interpolates. In the example above, the 95th percentile of 1000 requests is rank 950. That falls in the 0.5 to 1 bucket, where the count goes from 900 to 980, so the estimate is 0.5 + (950 − 900) / (980 − 900) × 0.5 = 0.8125 seconds. The true value might be anywhere between 0.5 and 1. Choose bucket bounds near the thresholds you care about, such as your service-level target.
Each bucket is a separate time series, so a histogram with many buckets and many label values costs real memory. Keep buckets to roughly ten and avoid high-cardinality labels.
Summaries
A summary also tracks observations, but the application calculates quantiles itself and exposes them directly:
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 2.1e-05
go_gc_duration_seconds{quantile="0.5"} 4.1e-05
go_gc_duration_seconds{quantile="1"} 0.00118
go_gc_duration_seconds_sum 0.52
go_gc_duration_seconds_count 9800The quantile series are gauges. You read them directly and do not call rate() on them. The _sum and _count series are counters and work with rate() just as in a histogram.
The trade-off is aggregation. You cannot combine quantiles from several servers. The average of two servers' 95th percentiles is not the 95th percentile of the combined traffic. Histogram buckets can be added together, so histograms support fleet-wide percentiles. Summaries do not.
Choosing a type
| Question | Type | Typical query |
|---|---|---|
| How many events happened, or how fast? | Counter | `rate()`, `increase()` |
| What is the value right now? | Gauge | the value, `avg_over_time()` |
| What is the latency percentile across many servers? | Histogram | `histogram_quantile()` |
| What are the exact quantiles of one process? | Summary | read `quantile` series |
Common mistakes
- Graphing a raw counter. The line climbs forever and drops to zero on restart. Wrap it in
rate(). - Using
rate()on a gauge such asnode_memory_MemFree_bytes. Use the value orderiv(). - Averaging percentiles. Use a histogram and aggregate the buckets.
- Dropping
leinsum by (...)beforehistogram_quantile(). The query then returns no data. - Setting a window shorter than two scrape intervals, which gives empty results.
Exercise
A counter named appjobsprocessedtotal reads 4000 at the start of a 5-minute window and 4900 at the end, with no restart. What does rate(appjobsprocessedtotal[5m]) return, and what does increase(appjobsprocessed_total[5m]) return?
Show answer
The counter grew by 900 over 300 seconds, so rate() returns about 3 jobs per second and increase() returns about 900 jobs. Prometheus extrapolates slightly to the window edges, so real results can differ a little from these round figures.
Exercise
You run the same web service on 10 servers, and each exposes a histogram httprequestduration_seconds. Write the PromQL query for the 99th percentile across all servers, and explain why a summary could not give you this number.
Show answer
histogramquantile(0.99, sum by (le) (rate(httprequestdurationseconds_bucket[5m]))). The bucket counters from all servers are added per le value, and the quantile is estimated from the combined distribution. A summary exposes precomputed quantiles per server, and quantiles from separate servers cannot be combined into a correct overall quantile.