Metric Types and Aggregation
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Checked on 2026-11-09 against Grafana 13.3.x and Kibana 9.5.x.
A raw series of samples is almost never what a dashboard shows or an alert evaluates. A panel draws one point per pixel or per bucket, an alert compares one number with a threshold, and both get that number by aggregating: over time (many samples of one series into one), across series (many series into one), or both. Choosing the wrong aggregation is the usual reason a dashboard looks calm while users suffer, or an alert flaps. This page explains the metric types that decide which aggregations are meaningful, the arithmetic of rates and percentiles, how step and resolution are chosen, and how the same ideas appear as PromQL in Grafana and as Elasticsearch aggregations and ES|QL in Kibana.
It builds on Observability Fundamentals (series, labels and
cardinality). The Prometheus side is covered in depth by
Data Model and Metric Types,
PromQL Functions and
PromQL Operators and Aggregation; the Elasticsearch side by
Aggregations. Examples use the Bookshelf metric
http_server_requests_seconds produced by Micrometer, as set up in
Metrics and Observability.
Metric types
The Prometheus documentation defines four core types (Source: Prometheus metric types); OpenTelemetry’s data model uses different names for similar shapes (Source: OpenTelemetry metric points).
| Type | What it is | Use it for | Never do this |
|---|---|---|---|
Counter |
A cumulative value that only goes up, or resets to zero when the process restarts. OpenTelemetry calls a monotonic sum a counter. |
Requests served, errors, bytes sent. Always look at it through |
Graph or alert on the raw value, or use it for a value that can decrease. |
Gauge |
One value that can rise or fall: a sampled value at a point in time. |
Memory in use, queue length, connections in the pool, temperature. |
Take |
Histogram |
Observations counted into configurable buckets, plus a sum and a count. Classic histograms are several series; native histograms are one composite sample. |
Latency and size distributions, where you need percentiles or the share of requests under a limit. |
Average the percentiles computed on different instances. |
Summary |
Observations with quantiles computed inside the application over a sliding window, plus sum and count. |
Legacy instrumentation that already exposes it. |
Aggregate its quantiles across instances. OpenTelemetry marks summaries legacy and advises against them for new applications. |
Histograms: classic and native
A classic Prometheus histogram exposes cumulative <name>_bucket{le="..."} counters, one per bucket upper bound, plus
<name>_sum and <name>_count. The bucket boundaries are chosen at instrumentation time, and a quantile can only be as
accurate as the width of the bucket it falls in. A native histogram (called an exponential histogram in OpenTelemetry) is
ingested as a single composite sample with dynamically sized exponential buckets, so it needs no boundaries chosen in
advance, transfers atomically and is generally more efficient and of higher resolution. Classic histograms can also be
ingested as native histograms with custom bucket boundaries, which keeps the classic layout but gains some of the
efficiency
(Source: Prometheus native histograms). The OpenTelemetry
exponential histogram uses a scale parameter that controls resolution, can be downscaled without error and keeps a
zero_count bucket for values near zero
(Source: ExponentialHistogram). The Prometheus
histogram practices page tells you to prefer native histograms over classic histograms and summaries if you can
(Source: Histograms and summaries).
In Elasticsearch a latency distribution can be stored the same way: a time series data stream field can be mapped with
time_series_metric of counter, gauge or histogram
(Source: Time series data stream).
Elasticsearch can also compute percentiles at query time from raw values (see below).
Aggregation temporality
OpenTelemetry sums and histograms are exported with a temporality. With cumulative temporality each point repeats the start
timestamp and reports the total since then, which is what Prometheus expects. With delta temporality each point covers only a
new interval
(Source: Temporality). A backend that stores
cumulative counters and receives deltas (or the reverse) shows nonsense rates, so the collector or exporter must convert. On the Prometheus side the feature flags
--enable-feature=otlp-deltatocumulative and --enable-feature=otlp-native-delta-ingestion exist for OTLP ingestion and
cannot be enabled together
(Source: Prometheus feature flags). The Elasticsearch counter
type uses cumulative temporality by default.
Rates and increases
A counter is meaningful only as a change over time. Prometheus defines rate() as the per-second average increase of a counter
over the range; it compensates for counter resets and extrapolates to the range edges so that missed or misaligned scrapes are
tolerated, and the page says it is best suited for alerting and for graphing slow-moving counters. increase() is roughly
rate() multiplied by the window in seconds and can return non-integers. irate() uses only the last two samples, reacts
fast and is volatile, so it is for graphing fast counters and not for alerts. The rule for combining them is to apply the rate
function first and aggregate afterwards, otherwise resets go undetected
(Source: PromQL functions).
# requests per second, per route, over a 5 minute window
sum by (uri) (rate(http_server_requests_seconds_count{job="bookshelf"}[5m]))
# fraction of requests that failed, the numerator and denominator of the "high 5xx ratio" alert
sum(rate(http_server_requests_seconds_count{job="bookshelf", status=~"5.."}[5m]))
/
sum(rate(http_server_requests_seconds_count{job="bookshelf"}[5m]))
Reference: Prometheus query functions.
In ES|QL the equivalent works on a time series data stream with the TS source command. RATE requires a counter field, and
TS is generally available on Elastic Cloud Serverless and in the Elastic Stack since 9.4, as a preview in 9.2 to 9.3
(Source: ES|QL TS command):
TS metrics
| WHERE @timestamp >= now() - 1 hour
| STATS SUM(RATE(search_requests)) BY TBUCKET(1 hour), host
Reference: ES|QL TS command (the example from the
reference, with its generic metrics index and search_requests counter; substitute your own data stream and field
names).
Percentiles, and why averages lie
An average of latency hides the tail. If 99 requests take 100 ms and one takes 10 s, the mean is about 199 ms, a number that describes no request that actually happened, while the p99 shows the 10 s. Users experience the tail, and SLOs are written against percentiles, so an alert on the mean is late and quiet. For a histogram the mean is the ratio of two counters, , and a quantile is estimated from the bucket counts.
# p95 latency from a classic histogram, aggregated across all instances
histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{job="bookshelf"}[5m])))
# the same for a native histogram
histogram_quantile(0.95, sum(rate(http_server_requests_seconds{job="bookshelf"}[5m])))
# mean latency (classic): sum over count
rate(http_server_requests_seconds_sum{job="bookshelf"}[5m])
/
rate(http_server_requests_seconds_count{job="bookshelf"}[5m])
Source: Prometheus: histograms and summaries (the sum by (le) and native
forms are taken from its examples) and histogram_quantile.
Three rules follow from the documentation.
-
Aggregate buckets, not quantiles. Averaging summary quantiles across instances is described as statistically meaningless, which is why the page marks
avg(...{quantile="0.95"})as bad. Sum the buckets (sum by (le)) first and take the quantile of the sum. -
Keep
lein the grouping for classic histograms. Dropping it makeshistogram_quantilefail, and the highest bucket must be+Infor the result isNaN. -
The estimate is only as good as the buckets. Between two boundaries Prometheus interpolates linearly for classic histograms. The practices page shows a spike that moved to 320 ms being estimated as 443 ms. If your SLO is 300 ms, make sure a bucket boundary sits exactly there. Native histograms limit the error by their configured resolution, which is why the page prefers them.
Micrometer publishes a latency histogram for a timer only if you enable percentile histograms or service level objective boundaries for it, so the Bookshelf configuration must enable them before any of the histogram queries below return data (see Metrics and Observability).
In Elasticsearch the percentiles aggregation is approximate by design: it uses the TDigest algorithm by default, accuracy is
proportional to so extreme percentiles are more accurate than the median, and an HDR histogram can be selected
for latency work (positive values only, larger memory footprint)
(Source: Percentiles aggregation).
{
"size": 0,
"aggs": {
"load_time_outlier": {
"percentiles": {
"field": "load_time",
"percents": [ 95, 99, 99.9 ],
"hdr": { "number_of_significant_value_digits": 3 }
}
}
}
}
Source: Percentiles aggregation
(the HDR example of that page; replace load_time with a latency field in milliseconds from your data).
Aggregation over time and across series
Every chart query is two aggregations in sequence, and keeping them apart makes queries readable.
| Dimension | PromQL (Grafana) | Elasticsearch (Kibana) |
|---|---|---|
Over time: many samples of one series into one value per step |
|
Bucket aggregations such as |
Across series: many series into fewer |
|
A bucket aggregation ( |
Between aggregations |
Rate function first, then aggregate across series. |
Pipeline aggregations that consume the output of other aggregations (for example a derivative or a moving average of a date histogram). |
Elasticsearch groups aggregations into three families: metric aggregations calculate values such as a sum or an average
from field values, bucket aggregations group documents into bins, and pipeline aggregations use the output of other
aggregations as input
(Source: Aggregations). A chart over time is a bucket
aggregation with a metric inside. For time buckets, date_histogram accepts either a calendar_interval (calendar-aware: a
unit or a single-unit quantity such as 1d, adjusting for daylight saving time and month length, so 2d fails) or a
fixed_interval (fixed SI units up to days, multiples allowed such as 30d, but weeks, months and quarters are not
supported)
(Source: Date histogram aggregation).
By default the buckets run from the first one with matching documents to the last; min_doc_count filters them and
extended_bounds extends the histogram beyond the data. That last detail is why an Elasticsearch chart can show a gap as a
missing bucket rather than as zero, which matters for the "no data" alert.
{
"size": 0,
"aggs": {
"per_minute": {
"date_histogram": { "field": "@timestamp", "fixed_interval": "1m" },
"aggs": {
"p95": { "percentiles": { "field": "http.server.request.duration", "percents": [95] } }
}
}
}
}
Reference: Date histogram aggregation, assembled with the percentiles aggregation above. The field name is an assumption: use the duration field that your mapping (ECS or OpenTelemetry-native) produces for Bookshelf, and check it in Discover first.
ES|QL expresses the same thing as a pipeline of commands. BUCKET(field, buckets, from, to) picks a bucket size that produces
at most the requested number of buckets in the range (the goal is not to hit the count exactly), BUCKET(field, size) takes
a fixed size, it does not filter rows (combine it with WHERE), and by default only buckets that contain at least one row are returned
(include_empty_buckets adds the others)
(Source: BUCKET).
TBUCKET creates timestamp-based buckets aligned to calendar boundaries
(Source: ES|QL grouping functions).
FROM logs-*.otel-*
| WHERE @timestamp >= NOW() - 1 day AND severity_text == "ERROR"
| STATS errors = COUNT(*) BY minute = BUCKET(@timestamp, 25, NOW() - 1 day, NOW())
| SORT minute
Reference: BUCKET
(the hourly-buckets-for-the-last-day pattern described there, with a target of 25 buckets over NOW() - 1 day to NOW()),
applied to the Bookshelf error logs. severity_text is the field name in the lab’s OTel-mapped logs data streams; ECS-mapped logs use log.level instead.
Step and resolution
A chart cannot draw more points than it has pixels, so the query is asked for a bounded number of points and the backend aggregates to match. The vocabulary is similar in both tools.
-
Grafana max data points defaults to the panel width in pixels, so the same dashboard can look different at different panel sizes or in view mode. Set a fixed value for consistent results (Source: Query and transform data).
-
Grafana min interval is a lower bound on the automatically calculated interval, typically the scrape interval; going lower than the scrape interval gains nothing. In Prometheus it corresponds to the min step, which can shift the query range because Prometheus aligns it to the interval.
-
$__intervalis the calculated time span for aggregating or grouping data points. It is derived from the graph width, so zooming out makes it larger. It is available in seconds as$__intervaland in milliseconds as$__interval_ms. -
$__rate_intervalis designed forrate()andincrease(). The documented formula is where is$__intervaland is the scrape interval, taken from the query’s min step if set and otherwise from the data source’s scrape interval setting. With a 15 s scrape interval and a 30 s interval the window is 60 s, which guarantees at least four samples in every window (Source: Prometheus template variables).
sum by (uri) (rate(http_server_requests_seconds_count{job="bookshelf"}[$__rate_interval]))
Reference: Prometheus template variables and Prometheus query editor, where Min step, the Range and Instant query types and Format as (Time series, Table or Heatmap) are described.
The usual failure is a fixed range such as [1m] with a 30 s scrape interval: at narrow zooms a window can hold a single sample
and the graph shows holes; at wide zooms a short window makes the rate noisy. Using the rate interval variable avoids both. Make the
scrape interval in the data source settings match the real one, because the formula trusts it. In Kibana the interval of a time axis is a Lens setting (see
Lens); the same trade-off applies, and an interval smaller than the
reporting interval of the data leaves empty buckets.
Downsampling and retention of resolution
Fine resolution is expensive to keep. Downsampling stores time series data at lower granularity as it ages, on the premise that metrics become less relevant over time. Elasticsearch offers it for time series data streams and lists it as generally available in the Elastic Stack and on Serverless (Source: Downsampling a time series data stream). Prometheus takes a different route: it keeps raw samples for the retention period (15 days by default when no retention flag is set) and relies on recording rules or long-term storage for coarser series (Source: Prometheus storage). The consequence for alerting is that an alert must evaluate data at the resolution it was designed for: a p95 over a 5 minute window cannot be reproduced from hourly rolled-up data. The cost side of this trade-off is in Storage, Retention and Cost.
Panels and charts are aggregations
Every Grafana panel runs a query (PromQL, LogQL, SQL, Elasticsearch) against a data source and draws the returned frames. Every
Kibana Lens chart builds an Elasticsearch aggregation (or an ES|QL query) from the fields you drag, and draws its buckets: the
horizontal axis is a bucket aggregation on time, the vertical axis a metric aggregation, and break down by adds a terms
bucket. Understanding the underlying aggregation explains behaviours that otherwise look like bugs: why a rate is empty until
two scrapes exist, why a terms breakdown shows only the top values, why percentile lines from two data sources disagree, and why zooming changes a value.
This is also exactly what an alert rule evaluates, so a panel that shows the right number is the best first draft of a rule
query.
What can go wrong
-
Rate of a gauge, or a raw counter on a graph. The first is meaningless; the second is an ever-rising line that hides every incident.
-
Quantile of averages. Averaging percentiles from several instances, or from a summary, gives a number that no request experienced.
-
Window shorter than the scrape interval. Use
$__rate_intervaland set the data source scrape interval. -
Missing bucket boundary at the SLO. If the SLO is 300 ms and no bucket ends there, the share of fast requests is estimated, not measured.
-
Calendar versus fixed intervals. A
fixed_intervalof30dis not a month. Usecalendar_intervalfor calendar units. -
Temporality mismatch. Delta data sent to a backend expecting cumulative totals yields wrong rates.
Verify it in the lab
-
In Explore (Grafana profile) run the 5xx ratio query above and the p95 query, and confirm both change when you start the load generator with an error-producing route.
-
Resize the panel and change the time range, and watch
$__rate_intervalin the query inspector change. The p95 line must keep its shape, and only its resolution changes. -
Run the p95 query with and without
sum by (le)and note the error from the second one. -
In Kibana (kibana profile) open Discover in ES|QL mode and run the
BUCKETexample against the Bookshelf log data stream; then compare the minute counts with a Lens chart of the same data.
In the books
Madhusudhan Konda (chapter 13) and Alberto Paro (chapter 7) teach Elasticsearch aggregations as metric, bucket and pipeline
families, with parent and sibling pipeline aggregations and terms, range and histogram buckets. That material is still accurate for the aggregation
framework, but both predate ES|QL, the TS command and time series data streams as the metrics store, and Paro’s
recipes use 7.0 syntax. Krishna Shah (chapters 4 and 5) shows Kibana charts built with Lens, the aggregation-based editors and TSVB; the
aggregation-based and TSVB editors are now legacy and Lens is the default. Rob Chapman and Peter Holmes (chapter 2) compare
counters, gauges, histograms and summaries; Michael Hausenblas (chapter 2) covers the metric signal and its cost. None of the books covers
native histograms. See the section index for the publisher links.
Where to go next
-
RED, USE and the Golden Signals uses these aggregations to build the standard service dashboards.
-
SLIs, SLOs and Error Budgets depends on the histogram and ratio queries above.
-
Grafana and Kibana show where to enter these queries in each tool.