Useful Functions: absent, predict_linear & *_over_time
PromQL has around 80 functions. A dozen of them cover most real dashboards and alerts.
| Function | Does | Typical use |
|---|---|---|
rate, irate, increase, resets |
counters | everything (previous lessons) |
avg_over_time, max_over_time, min_over_time, sum_over_time, count_over_time, quantile_over_time, last_over_time |
aggregate one series over a time window | smoothing gauges, "peak in the last hour" |
absent(v), absent_over_time(v[d]) |
1 if the selector returns nothing | "metric missing" alerts |
predict_linear(v[d], s) |
linear regression: the value s seconds from now |
"disk full in 4 hours" |
deriv(v[d]), delta(v[d]) |
slope / change of a gauge | "memory grows 2 MB/min" |
changes(v[d]) |
how many times the value changed | flapping configs, restarts |
time(), timestamp(v) |
current time / sample time, Unix seconds | freshness: time() - last_success_timestamp |
clamp_min, clamp_max, clamp, abs, round, ceil, floor |
arithmetic hygiene | avoid negative or absurd values |
label_replace, label_join |
build labels with a regex | joining metrics with different label names |
sort, sort_desc, sort_by_label |
order results | tables |
vector(s), scalar(v) |
convert | … or vector(0) to show 0 instead of "no data" |
Running the important ones
The data: a disk that fills steadily (node_filesystem_avail_bytes drops by 2 MiB every 15 s from 6 GiB), a gauge for queued items that peaks briefly, and linkly_build_info for only one of two instances:
python3 - > data.om <<'PY'
start = 1767225600
MiB = 1024 * 1024
print("# TYPE node_filesystem_avail_bytes gauge")
print("# TYPE linkly_queue_items gauge")
print("# TYPE linkly_build_info gauge")
for i in range(121):
t = start + 15 * i
print(f'node_filesystem_avail_bytes{{instance="db-1",mountpoint="/var/lib/postgresql"}} {6144 * MiB - 2 * MiB * i} {t}')
print(f'linkly_queue_items{{instance="api-1"}} {40 if 60 <= i < 64 else 3} {t}')
print(f'linkly_build_info{{instance="api-1",version="1.5.0"}} 1 {t}')
print("# EOF")
PY
promtool tsdb create-blocks-from openmetrics data.om data >/dev/null
echo "global: {}" > prometheus.yml
prometheus --config.file=prometheus.yml --storage.tsdb.path=data --storage.tsdb.retention.time=100y \
--web.listen-address=127.0.0.1:9090 >prom.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:9090/-/ready >/dev/null && break; sleep 0.2; done
q() { echo "> $1"; promtool query instant --time=2026-01-01T00:30:00Z http://127.0.0.1:9090 "$1" |
sed 's/ @\[.*//' | awk '$NF ~ /^[-+.0-9e]+$/ { $NF = sprintf("%.6g", $NF) } { print }' | sort; }
q 'node_filesystem_avail_bytes / 2^30'
q 'deriv(node_filesystem_avail_bytes[10m])'
q 'predict_linear(node_filesystem_avail_bytes[30m], 4 * 3600) / 2^30'
q '(node_filesystem_avail_bytes / -deriv(node_filesystem_avail_bytes[30m])) / 3600'
q 'linkly_queue_items'
q 'max_over_time(linkly_queue_items[30m])'
q 'avg_over_time(linkly_queue_items[30m])'
q 'absent(linkly_build_info{instance="api-2"})'
q 'absent(linkly_build_info{instance="api-1"})'
q 'sum(rate(nonexistent_errors_total[5m])) or vector(0)'
q 'label_replace(linkly_build_info, "major", "$1", "version", "(\\d+)\\..*")'> node_filesystem_avail_bytes / 2^30
{instance="db-1", mountpoint="/var/lib/postgresql"} => 5.76562
> deriv(node_filesystem_avail_bytes[10m])
{instance="db-1", mountpoint="/var/lib/postgresql"} => -139810
> predict_linear(node_filesystem_avail_bytes[30m], 4 * 3600) / 2^30
{instance="db-1", mountpoint="/var/lib/postgresql"} => 3.89062
> (node_filesystem_avail_bytes / -deriv(node_filesystem_avail_bytes[30m])) / 3600
{instance="db-1", mountpoint="/var/lib/postgresql"} => 12.3
> linkly_queue_items
linkly_queue_items{instance="api-1"} => 3
> max_over_time(linkly_queue_items[30m])
{instance="api-1"} => 40
> avg_over_time(linkly_queue_items[30m])
{instance="api-1"} => 4.23333
> absent(linkly_build_info{instance="api-2"})
{instance="api-2"} => 1
> absent(linkly_build_info{instance="api-1"})
> sum(rate(nonexistent_errors_total[5m])) or vector(0)
{} => 0
> label_replace(linkly_build_info, "major", "$1", "version", "(\\d+)\\..*")
linkly_build_info{instance="api-1", major="1", version="1.5.0"} => 1
Notes on each:
- Disk: 5.77 GiB left, falling at 2 MiB per 15 s (the
derivslope is in bytes per second).predict_linearover 30 minutes says that in 4 hours about 3.9 GiB will be left; the last query divides the free space by the slope: about 12.3 hours until full. The standard node alert ispredict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs"}[6h], 4 * 3600) < 0: "will be full within 4 hours if the trend holds", much better than a fixed "90% used" threshold, which pages too early for slow growth and too late for fast growth. - Peaks: the queue had a one-minute spike to 40. The current value (3) and the average (about 4.2) hide it;
max_over_timeshows it. Usemax_over_timefor gauges you alert on with long scrape intervals, so short peaks are not missed between samples. - absent() returns
{instance="api-2"} 1when nothing matches, and nothing (the empty line) when the series exists. Each important job should have anabsent(up{job="…"})alert: if the whole job disappears (deleted ServiceMonitor, renamed label),up == 0alerts can't fire, because there is noupseries to compare. - or vector(0): a sum over nothing is "no data" in Grafana;
or vector(0)turns it into 0. Note it drops all labels, so use it only on fully aggregated expressions. - label_replace(v, dst, replacement, src, regex) adds
major="1"from the version string (the regex is anchored and needs\\in the shell string here).
A freshness alert
Timestamps exported as values (Unix seconds, like backup_last_success_timestamp_seconds in Exporters) are checked with time(). In a promtool test, time() is the virtual evaluation time:
cat > rules.yml <<'YML'
groups:
- name: batch
rules:
- alert: BackupTooOld
expr: time() - backup_last_success_timestamp_seconds > 26 * 3600
labels: {severity: ticket}
annotations:
summary: 'last backup {{ $value | humanizeDuration }} ago'
YML
cat > test.yml <<'YML'
rule_files: [rules.yml]
tests:
- interval: 1h
input_series:
# the last successful backup finished at t = 1 h (3600 s) and no backup succeeded since
- series: 'backup_last_success_timestamp_seconds{job="pg-nightly"}'
values: '3600x40'
alert_rule_test:
- eval_time: 26h
alertname: BackupTooOld
exp_alerts: []
- eval_time: 28h
alertname: BackupTooOld
exp_alerts:
- exp_labels: {severity: ticket, job: pg-nightly}
exp_annotations:
summary: 'last backup 1d 3h 0m 0s ago'
YML
promtool test rules test.yml SUCCESS
'3600x40' repeats the value 3600 forty times (one per hour): the timestamp stays the same because no new backup succeeds. At 26 h the backup is 25 h old, no alert; at 28 h it's 27 h old and the alert fires, with a human-readable duration from the humanizeDuration template function.
Test yourself
Why have an absent(up{job="linkly"}) alert next to up{job="linkly"} == 0?
- They're the same
- If the job's series vanish entirely,
up == 0has nothing to compare and can't fire - absent() is faster
- Alertmanager needs both
Which expression alerts when a disk will be full within 4 hours at the current trend?
node_filesystem_avail_bytes < 0.1predict_linear(node_filesystem_avail_bytes[6h], 4 * 3600) < 0rate(node_filesystem_avail_bytes[4h]) < 0deriv(node_filesystem_avail_bytes[6h]) > 4
A gauge is scraped every minute and spikes for 20 seconds. Which function on [10m] is most likely to reveal the spike?
avg_over_timemax_over_timelast_over_time- None: it may not be sampled at all