PromQL

Data Types and Selectors

PromQL (Prometheus Query Language) has four types:

TypeMeaningExample
Instant vectorA set of series, each with one sample, all at the same evaluation timehttp_requests_total{job="api"}
Range vectorA set of series, each with a list of samples over a window. Cannot be graphed; it is input to functions such as rate()http_requests_total{job="api"}[5m]
ScalarA single float with no labels0.99, scalar(sum(up))
StringA literal; rarely used (label_replace arguments)"api"

A selector picks series by label matchers, resolved through the postings lists of the Prometheus part: = equal, != not equal, =~ regex match, !~ regex non-match. Regexes are fully anchored (env=~"prod" means ^prod$); since 3.0 . also matches a newline. A selector must contain at least one matcher that cannot match the empty string.

  • Lookback delta: an instant selector returns, for each series, the most recent sample within the last 5 minutes (--query.lookback-delta), unless it is a staleness marker. This is why a series that stopped 4 minutes ago still appears on a graph.
  • offset 1w shifts evaluation back in time: rate(x[5m]) / rate(x[5m] offset 1w) is week-over-week change. It must follow the selector directly.
  • @ 1735689600 (or @ start() / @ end()) pins the selector to a fixed timestamp, useful for topk(5, rate(x[5m] @ end())) so the top-5 is chosen at the end of the graph and then plotted over the whole range.
  • Range selectors are left-open, right-closed since 3.0: x[60s] at time t covers (t-60s, t]. At a 15 s scrape that is exactly 4 samples.

rate, irate, increase: What They Really Compute

A counter only goes up (until the process restarts and it falls back to 0), so its raw value is useless on a graph; what you want is how fast it rises. rate(v[w]) is the per-second average increase over the window; increase(v[w]) is the same quantity not divided by the window (exactly rate × w); irate(v[w]) uses only the last two samples in the window.

  1. Take the samples inside the window (left-open). With fewer than 2, the result is empty for that series.
  2. Fix counter resets. Whenever a sample is lower than its predecessor, the counter is assumed to have restarted from zero, so the predecessor's value is added to everything after it. The result is last - first + (sum of values just before each reset). This assumes at most one reset between two scrapes and treats the whole post-reset value as increase.
  3. Extrapolate to the window edges. The first and last scrapes rarely land exactly on the window boundaries, so the measured increase is scaled by (sampled interval + gap to start + gap to end) / sampled interval. A gap is extended in full only if it is under 1.1 × the average scrape spacing; otherwise only half a spacing. For a counter, the start is also clamped so the extrapolation never goes below zero.
  4. Divide by the window length (for rate).
Two stacked plots sharing a time axis from 28 to 112 seconds. Panel A: raw counter samples at 32, 47, 62, 77, 92, 107 seconds with values 940, 1000, 1060, 30, 85, 140; the drop from 1060 to 30 is a counter reset. A shaded window from 40 to 100 seconds contains four samples. Panel B: the reset-adjusted series 1000, 1060, 1090, 1145 with orange dashed extrapolation to 977.4 at 40 seconds and 1170.8 at 100 seconds. Result: measured increase 145, extrapolated increase 193.33, rate 3.222 per second, irate 3.667 per second.
A counter with a reset, drawn to scale: what rate(), increase() and irate() compute. Read it as: both panels share the time axis (about 10 units per second). Panel A is what is stored; panel B is the same data after the reset is folded in, with the orange dashed ends showing where rate() extends the line to the window edges because the first and last scrapes rarely land on the window boundary.

This is why increase(http_requests_total[5m]) returns non-integers like 193.33 for a counter that only ever moves by 1: it is an estimate scaled to the window, not a count. Do not alert on increase(...) == 3. If you need exact counts use last - first yourself or an event store.

rate()irate()
Usesall samples in the window, extrapolatedlast two samples
Smooth?yes: averages across the windowno: jumps with every scrape
Fast spikessmoothed awayvisible, but you may miss spikes between scrapes entirely at a coarse graph step
Use foralerts, recording rules, almost every dashboardzoomed-in debugging of a volatile counter, with a short window

Choosing the window

The window must contain at least 2 samples, and in practice you want to survive one missed or slow scrape: the rule is window ≥ 4 × scrape interval (1 m for 15 s scrapes). A [30s] window at 15 s gives 2 samples and a single timed-out scrape makes the graph show holes. In Grafana use $__rate_interval, defined as max($__interval + scrape_interval, 4 × scrape_interval): it follows the panel's resolution but never drops below the safe minimum (set the data source's scrape interval correctly or it will be wrong). A very long window is the opposite error: [1h] averages a 30-second outage into nothing.

The Golden Rule: rate, Then Sum

✗ Wrong: sum, then rate

rate( sum(http_requests_total)[5m:] )
# or the "obvious" dashboard form:
sum(http_requests_total)  # then rate in a recording rule

✓ Right: rate per series, then sum

sum by (route) (
  rate(http_requests_total{job="api"}[5m])
)

Why. rate() detects resets by seeing a value go down. Summing hides the individual resets: pod A is at 1000, pod B at 2000, the sum is 3000. Pod A restarts and starts again at 10: the sum is now 2010. rate() sees a drop from 3000 to 2010, concludes the whole fleet counter was reset to zero, and adds the previous 3000 back: the computed increase over that step is 2010 instead of the true ~20. A single deploy produces a spike of about 100× on every dashboard. Taking rate() first (each series gets its own reset handling), then sum, is always correct. The same applies to increase, and to histogram _bucket counters.

Aggregation Operators

An aggregation collapses many series into fewer. by (a,b) keeps only the listed labels; without (a,b) drops the listed labels and keeps the rest (safer when new labels appear later).

sum by (route) (rate(http_requests_total[5m]))        # one series per route
avg without (instance) (node_load1)                   # drop only instance
max by (pod) (container_memory_working_set_bytes)
topk(5, sum by (route) (rate(http_requests_total[5m])))   # 5 largest series; keeps labels
count by (version) (build_info)                       # how many series per version
count_values("code", http_response_code_gauge)        # how many series have each VALUE
quantile(0.9, node_cpu_seconds_total)                 # 0.9-quantile across SERIES values

Note quantile() is an aggregation across the series at one instant. It is unrelated to histogram_quantile(), which reads buckets. count counts series; count_values makes a new label from the sample values and counts series per value.

Binary Operators and Vector Matching

Between two instant vectors, an operator pairs samples whose label sets are identical (excluding __name__); unmatched samples are dropped. You steer matching with on(labels) (match only on these) or ignoring(labels) (match on everything but these). When one side has several series per match (many-to-one), you must say which side is "many" with group_left (many on the left) or group_right, and may copy labels from the "one" side into the result.

Worked example: add the node name to container memory. container_memory_working_set_bytes (cAdvisor) has namespace, pod, container but no node. kube_pod_info (kube-state-metrics) has the value 1 and the labels namespace, pod, node, host_ip, ..., one series per pod.

sum by (node) (
    container_memory_working_set_bytes{container!="", namespace="shop"}   # many per pod
  * on (namespace, pod) group_left (node)                                 # match on pod, copy 'node'
    kube_pod_info                                                         # exactly one per pod
)

Multiplying by 1 leaves the value unchanged; its only job is to carry the node label across. Without on(...) nothing matches, because instance and job differ between the two metrics; with group_left missing you get "many-to-one matching must be explicit". Set operators work on label sets: a and b keeps a series that exist in b; a unless b keeps those that do not; a or b is a union. Comparisons (>, ==) filter by default; append bool to get 0/1 instead.

Histograms: histogram_quantile

Classic histograms (see Metrics) store the cumulative count of observations ≤ each upper bound le. histogram_quantile(φ, b) finds the bucket where the φ-rank falls and then interpolates linearly inside it, assuming observations are spread evenly in that bucket. The result is therefore exactly as accurate as your bucket boundaries.

quantile = lower + (upper − lower) × (rank − countlower) / (countupper − countlower), rank = φ × total

Panel A: cumulative histogram with le boundaries 0.05, 0.1, 0.25, 0.5, 1 and +Inf at counts 200, 600, 900, 960, 990 and 1000, joined by straight lines. Panel B zooms into the bucket from 0.25 to 0.5 where cumulative goes from 900 to 960. The p95 rank of 950 interpolates to 0.4583 seconds. Two dashed alternative distributions with the same bucket counts would have a true p95 of about 0.26 or 0.49 seconds. The p99 rank of 990 lands exactly on the le=1 boundary and reports 1.0 second.
histogram_quantile on classic buckets, to scale: a straight line between stored boundaries. Read it as: Prometheus stored only the six dots in panel A. The teal line between them is assumed (linear interpolation); panel B magnifies the amber box (about 2.3× horizontally, 14× vertically) to show how little the stored data pins down. Bucket boundaries, not PromQL, set the precision.

Two edge rules to remember. If the quantile falls in the +Inf bucket the function returns the upper bound of the highest finite bucket, so a p99 that "caps at 10 s" usually means your top bucket is 10 s. If the quantile lands exactly on a boundary (as the p99 does above), treat the answer as "somewhere below this bound", not a measurement.

You cannot average p99s

A percentile is an order statistic, not a mean; it has no algebra. Instance A serves 990 req/s, all in 100 ms; instance B serves 10 req/s, all in 5 s. Their p99s are 0.1 s and 5 s. The "average of p99s" is 2.55 s, which describes no request at all. The fleet-wide p99 is close to 0.1 s (99 % of requests were fast); the max is 5 s and overstates it. What you can do is add the buckets (bucket counts are additive across instances) and compute the quantile from the sum:

✗ Wrong: quantile per instance, then average

avg(
  histogram_quantile(0.99,
    rate(http_request_duration_seconds_bucket[5m]))
)

✓ Right: aggregate buckets first, keep le

histogram_quantile(0.99,
  sum by (le) (
    rate(http_request_duration_seconds_bucket[5m])
  )
)
# per route: sum by (le, route)

If you write sum by (route) and forget le, the bucket label is gone and histogram_quantile has nothing to work with: it returns an empty result (no error). The same rule is why per-instance histograms must share identical bucket boundaries: otherwise the buckets cannot be added.

Native histograms

With native (sparse, exponential-bucket) histograms (stable since 3.8, opt-in with scrape_native_histograms; see Metrics for the data model) there is no _bucket series and no le: the histogram is one sample type under the base name, and aggregation just works on it.

histogram_quantile(0.99, sum by (route) (rate(http_request_duration_seconds[5m])))
histogram_fraction(0, 0.25, sum(rate(http_request_duration_seconds[5m])))   # share of requests under 250 ms
histogram_avg(rate(http_request_duration_seconds[5m]))

Interpolation is still linear within a bucket, but bucket boundaries grow by a fixed factor: at the common schema 3 there are 8 buckets per doubling, each ~9 % wider than the last, so the relative error is bounded (about 4.5 % worst case) and nobody has to guess boundaries in advance.

Recording Rules and Alerting Rules

A recording rule evaluates an expression every evaluation_interval and stores the result as a new series, so dashboards read one cheap series instead of recomputing a heavy query. Convention for the name is level:metric:operations: the labels that remain, the metric, the operations applied (newest first), joined by colons.

rules/api.yml

groups:
  - name: api-recording
    interval: 30s
    rules:
      - record: route:http_requests:rate5m           # level=route, metric=http_requests, op=rate5m
        expr: sum by (route) (rate(http_requests_total{job="api"}[5m]))
      - record: job:http_request_duration_seconds_bucket:rate5m
        expr: sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))
  - name: api-alerts
    rules:
      - alert: ApiHighErrorRatio
        expr: |
          sum(rate(http_requests_total{job="api",status=~"5.."}[5m]))
            / sum(rate(http_requests_total{job="api"}[5m])) > 0.02
        for: 10m                                       # must be true continuously for 10 minutes
        labels: {severity: page}
        annotations: {summary: "API 5xx ratio above 2% for 10m"}

Note the second recording rule keeps le, so histogram_quantile(0.99, job:http_request_duration_seconds_bucket:rate5m) stays correct. How for:, grouping and routing behave is the subject of the Alerting and SLOs part.

Subqueries and Their Cost

A subquery expr[range:resolution] evaluates an instant expression at many past steps to build a range vector, so you can apply a range function to a computed series: max_over_time(rate(http_requests_total[5m])[1h:1m]) is "the peak 5-minute rate in the last hour". The cost is the number of steps times the inner expression: that query runs the inner rate over every matching series 60 times, at every evaluation. Put the inner expression in a recording rule and use max_over_time(route:http_requests:rate5m[1h]) instead. A graph panel with a subquery multiplies that by the panel's step count.

Useful Detectors

absent(up{job="api"})                       # 1 if NO series match: the only way to alert on "target vanished"
absent_over_time(up{job="api"}[10m])        # same, tolerant of gaps
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0   # disk full within 4h
changes(process_start_time_seconds[1h]) > 2    # restarts: value changed 3+ times
resets(http_requests_total[1h])             # counter resets in the window

up == 0 fires only while the series exists; once SD drops the target the series is stale and the alert silently resolves. Pair it with absent() on a job you expect to exist. predict_linear fits a least-squares line to a gauge over the window; it needs at least two samples and returns NaN if any is infinite.

A RED Query Set for an HTTP Service

The RED method (see RED, USE and SLOs) is Rate, Errors, Duration. For a service exposing http_requests_total{route,status} and http_request_duration_seconds_bucket{route,le}, in Grafana:

# Rate: requests per second, per route
sum by (route) (rate(http_requests_total{job="api"}[$__rate_interval]))

# Errors: ratio of 5xx, per route (division is by series with the same labels)
  sum by (route) (rate(http_requests_total{job="api",status=~"5.."}[$__rate_interval]))
/ sum by (route) (rate(http_requests_total{job="api"}[$__rate_interval]))

# Duration: p50 / p95 / p99 from summed buckets
histogram_quantile(0.95,
  sum by (le, route) (rate(http_request_duration_seconds_bucket{job="api"}[$__rate_interval])))

# Mean latency (exact, from _sum and _count, unlike a quantile)
  sum(rate(http_request_duration_seconds_sum{job="api"}[$__rate_interval]))
/ sum(rate(http_request_duration_seconds_count{job="api"}[$__rate_interval]))

# Saturation hint: in-flight requests and the ratio of requests slower than 500 ms
sum(http_in_flight_requests{job="api"})
1 - ( sum(rate(http_request_duration_seconds_bucket{job="api",le="0.5"}[5m]))
    / sum(rate(http_request_duration_seconds_count{job="api"}[5m])) )

The last query is a latency SLI without any interpolation: it reads a bucket boundary directly (le="0.5" must exist in your histogram). That is why SLOs (see Alerting and SLOs) are written on bucket boundaries, not on histogram_quantile.

Production Traps

The Invariants

  • Guarantees: Evaluation is deterministic for a given TSDB state and evaluation time. rate()/increase() correct for counter resets within a window. Bucket counts are additive, so sum by (le) of rates followed by histogram_quantile yields a valid fleet-wide estimate. Recording rules keep the labels you aggregate by, so results compose.
  • Does not guarantee: Exact counts (increase() is extrapolated and fractional). Quantiles more precise than the bucket width. Correctness when two resets fall between consecutive scrapes, or when sum-before-rate is used. Results from a window containing fewer than two samples. That a vanished series raises an alert unless you write absent(). Cheap subqueries or regex matchers.