Advanced PromQL
offset, @, subqueries, absent, predict_linear, and label functions
With selectors, rates, aggregation, and histograms you can write 90% of real queries. This lesson covers the rest: comparing against the past, predicting the future, detecting missing data, and reshaping labels.
offset: compare with the past
offset shifts a selector back in time:
# traffic now vs the same time last week
sum(rate(http_requests_total[5m]))
/
sum(rate(http_requests_total[5m] offset 1w))
# how much did the error count grow in the last hour vs the hour before?
increase(http_requests_total{status=~"5.."}[1h])
- increase(http_requests_total{status=~"5.."}[1h] offset 1h)Week-over-week ratios make good anomaly signals for traffic with a weekly pattern: "traffic is 40% below last Tuesday at this time" catches an outage that a fixed threshold would miss at 3 a.m.
@: pin to a moment
@ evaluates a selector at a fixed Unix time, regardless of the query's
evaluation time. @ start() and @ end() refer to the graph's range.
# the 5 routes that were busiest at the END of the graph's range,
# graphed across the whole range (fixes the topk-per-step problem)
sum by (route) (rate(http_requests_total[5m]))
and on (route)
topk(5, sum by (route) (rate(http_requests_total[5m] @ end())))Subqueries
A subquery turns an instant-vector expression into a range vector by
evaluating it repeatedly: expr[range:resolution].
# the highest 5-minute request rate seen in the last day
max_over_time(sum(rate(http_requests_total[5m]))[1d:1m])
# p99 latency, smoothed: average of the p99 over the last hour
avg_over_time(job_route:http_request_duration_seconds:p99_rate5m[1h])The first one evaluates sum(rate(...)) 1440 times (every minute for a
day) and takes the max. That's expensive. If you need it often, make
the inner expression a recording rule
and use a plain max_over_time on that, as in the second query.
Subqueries are the easiest way to write a query that's slow enough to
hurt Prometheus. [30d:15s] over a high-cardinality expression
evaluates it 172,800 times. Use them for ad-hoc investigation; for
dashboards and alerts, record the inner expression first.
predict_linear: alert before it happens
predict_linear(gauge[window], seconds) fits a straight line to the
window with linear regression and extrapolates:
# will this filesystem run out of space within 4 hours, based on the last hour's trend?
predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}[1h], 4 * 3600) < 0This is the expression behind DiskWillFillIn4Hours in
config/rules/alerts.yml. That rule also requires the disk to be at
least 60% full, because a nearly empty disk with a brief burst of writes
would otherwise be "predicted" to fill.
deriv(gauge[window]) returns the per-second slope of the same
regression: useful for "memory is growing by 2 MB/min" leak detection.
absent: alert on missing data
An alert on rate(errors[5m]) > 1 can never fire if the metric
disappears entirely. The exporter crashed, a label was renamed, or the
job was removed from the config. absent() returns a single series with
value 1 when the selector matches nothing:
absent(up{job="demo-app"}) # the job vanished from discovery
absent_over_time(up{job="demo-app"}[10m]) # ...and has been gone for 10 minutes
absent(nightly_backup_last_success_timestamp_seconds) # the batch job never pushedFor every critical alert, ask: "what if this metric didn't exist?" If
the answer is "the alert silently never fires", add an absent()
companion alert. This is the most common blind spot in alerting
setups.
Label manipulation
label_replace(v, dst, replacement, src, regex) matches regex against
the src label and writes replacement (with $1 capture groups) into
dst. It's mostly used to make two metrics' labels line up for vector
matching, when one calls it instance and the other host.
Other useful functions
hour() is handy for quiet-hours logic: ... and on() hour() >= 8 < 20
restricts an alert to working hours (UTC).
Query performance
PromQL is fast when it touches few series and few samples. When a dashboard is slow, check in this order:
- How many series does the selector match? Run
count(...)on the bare selector. Tens of thousands is a lot. - How long is the range?
rate(x[1d])reads a day of samples per series at every step. - How many steps? A 30-day graph at 15s step is 172,800 evaluations.
Grafana usually raises the step automatically; a hard-coded
steporMin intervalcan stop it. - Is it recomputing something? Move repeated heavy expressions into recording rules.
To see how much work a query did, add stats=all to an API call:
curl -s 'localhost:9090/api/v1/query' --data-urlencode 'query=...' -d stats=all | jq .data.stats
reports total samples loaded and time spent in each phase.
Lab
# 1. week-over-week isn't possible yet (no week of data), so compare with 10 minutes ago:
sum(rate(http_requests_total{job="demo-app"}[1m]))
/ sum(rate(http_requests_total{job="demo-app"}[1m] offset 10m))
# 2. peak request rate in the last hour, via subquery
max_over_time(sum(rate(http_requests_total{job="demo-app"}[1m]))[1h:15s])
# 3. is the batch job's metric present?
absent(nightly_backup_last_success_timestamp_seconds)
# 4. how many times has demo-app restarted in the last hour?
resets(http_requests_total{job="demo-app", route="/", status="200"}[1h])
# 5. add a host label from instance
label_replace(up, "host", "$1", "instance", "([^:]+):.*")Query 1 should oscillate around 1, following the load generator's 10-minute sine wave.