Learn Labs
PromQL

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.

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) < 0

This 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 pushed

Label manipulation

label_replace(up, "host", "$1", "instance", "([^:]+):.*")new label host from instance minus portlabel_join(up, "target", "/", "job", "instance")target="demo-app/demo-app:8080"sort_desc(sum by (route) (rate(http_requests_total[5m])))order results (instant queries only)

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

clamp_min(x, 0) / clamp_max(x, 1)bound valuesround(x, 0.1)round to nearest 0.1abs(x), ceil(x), floor(x), sqrt(x), ln(x)timestamp(up)when was the sample takenresets(http_requests_total[1h])how many counter resets (restarts) in the windowchanges(app_build_info[1d])how often a gauge's value changed (deploys)double_exponential_smoothing(x[1h], 0.5, 0.5)smoothed trend; needs --enable-feature=promql-experimental-functionshistogram_count / histogram_sum / histogram_fractionnative histogram helpersday_of_week(), hour()time-of-day conditions in alerts

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:

  1. How many series does the selector match? Run count(...) on the bare selector. Tens of thousands is a lot.
  2. How long is the range? rate(x[1d]) reads a day of samples per series at every step.
  3. How many steps? A 30-day graph at 15s step is 172,800 evaluations. Grafana usually raises the step automatically; a hard-coded step or Min interval can stop it.
  4. 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.

On this page