Sub topic 14
Precomputing queries with recording rules
This chapter assumes you can write PromQL selectors, use rate() and avg by, and have Prometheus scraping node_exporter targets as set up earlier. It also assumes you can edit prometheus.yml and reload a systemd service.
What a recording rule does
A recording rule is a PromQL expression that Prometheus evaluates on a schedule. It stores each result as a new time series. Dashboards and alerts then query the stored series instead of recomputing the expression.
Take the per-server CPU query:
1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))A server with 8 cores exposes 8 idle series, plus series for every other CPU mode. Each time a dashboard refreshes, Prometheus reads the samples for all of them over the window, computes rate() per series, and averages the results. With a few servers this is cheap. With dozens of servers, several panels, and many viewers, the same work repeats constantly.
A recording rule does that work once per evaluation interval. A panel then reads one series per server.
Why use recording rules
- Lower query cost. Heavy expressions run once per interval, not once per panel refresh.
- Faster dashboards. Reading a stored series is quicker than aggregating raw data over a long range.
- One definition. A dashboard and an alert can share the same recorded series, so they cannot drift apart.
- Shorter alert expressions. An alert can compare a recorded series against a threshold.
Recording rules do not make every query faster. If an expression is cheap, a rule adds a stored series without a real benefit. Add one when a query is expensive, used in many places, or both.
The rule file
Rules live in rule files. The prometheus.yml from the scrape chapter already loads them:
rule_files:
- rules/*.ymlThe path is relative to the directory containing prometheus.yml. Here is a recording rule file:
groups:
- name: node-recording
rules:
- record: instance:node_cpu_utilisation:rate5m
expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))The pieces:
groupsis a list. Prometheus evaluates the rules in a group in order, at the same interval, in sequence. A later rule in a group can use the result of an earlier one.nameidentifies the group. It must be unique within the file.recordis the name of the new series.expris the PromQL expression to evaluate.
You can also add a labels map to a rule. Those labels are set on every recorded series and override labels with the same name from the expression.
The evaluation interval comes from evaluation_interval in the global section (15 seconds in our configuration). A group can override it with its own interval field.
Naming convention
The Prometheus project recommends naming recorded series as level:metric:operations:
| Part | Meaning | In the example |
|---|---|---|
| level | The labels the result is aggregated to | `instance` |
| metric | The underlying metric name, without `_total` for counters | `node_cpu_utilisation` |
| operations | The functions applied, newest first | `rate5m` |
The name instance:node_cpu_utilisation:rate5m tells you that the series is per instance, concerns CPU utilisation, and was built with a 5-minute rate. Colons are legal in metric names and are reserved for recording rules, so exporters should not use them. That makes recorded series easy to spot.
Rule evaluation flow
Validate and load the rules
Check the syntax before reloading. promtool ships with Prometheus:
promtool check rules /etc/prometheus/rules/node-recording.ymlIt reports the number of rules found, or the line that is wrong. Then reload Prometheus without a restart:
sudo systemctl reload prometheusThis works if your unit file defines ExecReload to send SIGHUP. Otherwise send the signal yourself with sudo kill -HUP $(pidof prometheus). If Prometheus was started with --web.enable-lifecycle, you can also use curl -X POST http://localhost:9090/-/reload.
After the reload, open Status > Rules in the Prometheus web interface. Your group should appear with its last evaluation time and duration. The first result appears one evaluation interval after the reload. Then run the recorded name in the expression browser:
instance:node_cpu_utilisation:rate5mYou should see one series per server, with values between 0 and 1.
Using the recorded series
A panel or alert now refers to the short name. Compare:
instance:node_cpu_utilisation:rate5m > 0.9with repeating the full rate() and avg by expression everywhere. You can also build further rules on top of recorded series. For example, a rule that averages CPU across the fleet reads the per-instance series:
groups:
- name: node-recording
rules:
- record: instance:node_cpu_utilisation:rate5m
expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
- record: job:node_cpu_utilisation:avg
expr: avg by (job) (instance:node_cpu_utilisation:rate5m)Both rules are in one group, so the second sees the first rule's output from the same evaluation cycle. If they were in separate groups, the second might read the previous cycle's value, because groups are evaluated independently and concurrently.
Edge cases and common errors
Empty result. If the expression returns nothing, no series is written. Nothing is recorded for a rule whose inputs do not exist yet, such as a metric from a target that is down. Check the expression in the expression browser first.
Labels are lost by aggregation. avg by (instance) keeps only instance. The job, mountpoint, and other labels are gone from the recorded series. Decide which labels dashboards and alerts will need before you write the rule. For disk space, keep mountpoint and device, or you cannot say which filesystem is low.
Changing a rule does not rewrite history. A recorded series starts when the rule is first loaded. Prometheus does not backfill it. A new rule has no data before it was added, so a dashboard that switches to a recorded series shows a gap in older time ranges. Keep the raw expression available if you need to look back. Backfilling is possible with promtool tsdb create-blocks-from rules, but it is a manual, offline step.
Renaming breaks consumers. A panel or alert that uses instance:node_cpu_utilisation:rate5m stops working if you rename the rule. Treat recorded names as an interface. Rename by adding the new rule, switching the consumers, and then removing the old one.
The window must fit the scrape interval. rate(...[5m]) needs at least two samples in the window. With a 15 second scrape interval, 5 minutes holds about 20. A window shorter than twice the scrape interval gives empty results.
Slow evaluation. If a group takes longer than its interval, Prometheus skips evaluations and the recorded series has gaps. Check prometheus_rule_group_last_duration_seconds against prometheus_rule_group_interval_seconds. Split a large group, or raise its interval.
Cardinality. Each recorded series costs storage like any other. A rule that keeps a high-cardinality label, such as per-core data, can add as many series as the query reads. Aggregate to the level you actually use.
When not to record
- Do not precompute every query you write. Start from the expressions that are slow or repeated.
- Do not record raw
rate()of a single series with the same labels. It adds a series without saving work. - Keep ad-hoc exploration against raw metrics, where all labels are available.
Exercise
You write a recording rule record: instance:node_cpu_utilisation:rate5m with expr: avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])), reload Prometheus, and use it in an alert for high CPU. The alert never fires even when servers are busy. What mistake did you make, and how do you fix it?
Show answer
The expression returns the idle fraction, not utilisation, because the 1 - is missing. Busy servers have a low value, so a "greater than 0.9" alert stays quiet. Fix the rule to 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])), validate it with promtool check rules, and reload. The name says "utilisation", so the expression must match it.
Exercise
Why do two rules in separate groups give no guarantee that the second sees the first one's latest result, and how do you make the order reliable?
Show answer
Prometheus evaluates groups independently and concurrently, while rules inside one group run in order. Put both rules in the same group, with the dependent rule after the one it reads.