PromQL
Data Types and Selectors
PromQL (Prometheus Query Language) has four types:
| Type | Meaning | Example |
|---|---|---|
| Instant vector | A set of series, each with one sample, all at the same evaluation time | http_requests_total{job="api"} |
| Range vector | A 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] |
| Scalar | A single float with no labels | 0.99, scalar(sum(up)) |
| String | A 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 1wshifts 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 fortopk(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.
- Take the samples inside the window (left-open). With fewer than 2, the result is empty for that series.
- 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. - 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. - Divide by the window length (for
rate).
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() | |
|---|---|---|
| Uses | all samples in the window, extrapolated | last two samples |
| Smooth? | yes: averages across the window | no: jumps with every scrape |
| Fast spikes | smoothed away | visible, but you may miss spikes between scrapes entirely at a coarse graph step |
| Use for | alerts, recording rules, almost every dashboard | zoomed-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 valuesNote 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
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 windowup == 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, sosum by (le)of rates followed byhistogram_quantileyields 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 writeabsent(). Cheap subqueries or regex matchers.