Prometheus recording rules help anyone whose Grafana dashboards or alerts have slowed down because the same heavy query keeps running. Each panel recomputes it from raw series on every load and for every viewer, and each alert does the same work again. A series is the stream of samples Prometheus stores for one metric and one set of labels. A 30-day panel can end up reading a million of them to draw a few lines.
A recording rule fixes this by doing the work once, on a schedule. It tells Prometheus to evaluate a PromQL expression (a query in Prometheus’s own language) at a fixed interval and save the result under a new metric name you choose. Dashboards and alerts then read that small, precomputed series instead. You will write a rule file, name the output with the level:metric:operation convention, load it through rule_files, check it with promtool and pick an evaluation interval. One caveat matters from day one. Recording rules are not retroactive, so a new series has no history unless you backfill it.
What you’ll accomplish
- Write a rule file with
groups,interval,record,expr, andlabels, and name the output series with the convention from the Prometheus docs. - Wire the file into
prometheus.ymlviarule_filesand reload without a restart. - Validate the rules with
promtool check rulesbefore they ever reach a running server. - Point Grafana panels and alerting rules at the recorded series and confirm the numbers match.
- Find rule groups that overrun their interval using
prometheus_rule_group_last_duration_seconds.
Prerequisites
- A Prometheus server, 2.30 or newer. Everything here also applies to Prometheus 3.x; the rule file schema has not changed.
promtoolships in the same release tarball and container image. - Write access to the Prometheus config directory, plus a way to reload: either you can send
SIGHUPto the process, or the server was started with--web.enable-lifecyclesoPOST /-/reloadworks. The lifecycle flag is off by default. - Read access to the HTTP API on port 9090. Examples use
localhost:9090; substitute your address. curlandjqfor the inspection commands.jqis convenience only — the API returns plain JSON.- Know your
scrape_intervalbefore you start. It sets the floor for a sensible evaluation interval.
How it works
Prometheus runs a rule manager alongside the scrape loop. At startup, and on every config reload, it reads the files matched by rule_files and builds a list of rule groups. Each group has its own timer. When a group fires, the manager evaluates every rule in it as an instant query at that moment in time, and for a recording rule it ingests the result back into the local TSDB as a normal sample — same storage, same retention, same query path as scraped data.
Two ordering guarantees matter. Rules within a group run sequentially, in file order, all stamped with the same evaluation timestamp — which is exactly why a later rule in the group can reference a series produced by an earlier one in the same cycle. Groups themselves run in parallel and independently, so two rules that depend on each other must live in the same group or you will read stale, one-interval-old values.
The difference from an alerting rule is only what the rule does with its result. A recording rule uses the record: key and writes a new series. An alerting rule uses alert: and, when the expression returns anything, produces a pending or firing alert that Alertmanager sees. Both live in the same file format and both are loaded by the same rule_files setting — see writing Prometheus alerting rules for the alerting half.
Naming is a convention, not a rule the parser enforces, and it is worth following because it makes the series self-documenting. The Prometheus docs recommend level:metric:operations: the aggregation level (the labels you kept, e.g. job), the underlying metric name, and the operations applied, read right to left. So job:http_requests:rate5m is “per job, of http_requests, a 5-minute rate.” Colons are reserved for exactly this — exporters never emit them — so a colon in a metric name is an immediate signal that a rule produced it.
The labels: block attaches labels to the output series. It is applied after evaluation and overwrites any label of the same name that survived the expression, which is how you stamp a tier, an environment, or a severity onto a recorded series.
Step-by-step
1. Find the expression worth precomputing. Any query that aggregates across a large number of series, or that a dashboard runs over a long range, is a candidate. Run it once with timing to get a baseline:
curl -s -o /dev/null -w 'total: %{time_total}s\n' \
--data-urlencode 'query=sum by (job) (rate(http_requests_total[5m]))' \
http://localhost:9090/api/v1/query
total: 1.842s
Almost two seconds for one instant query. A dashboard with six panels on that pattern is unusable, and an alerting rule evaluating it every 30 seconds is burning CPU permanently.
2. Write the rule file. Create /etc/prometheus/rules/http.yml. The third rule reuses the output of the first two, which works because they are in the same group:
groups:
- name: http
interval: 1m
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
- record: job:http_request_errors:rate5m
expr: sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
- record: job:http_request_error_ratio:ratio_rate5m
expr: job:http_request_errors:rate5m / job:http_requests:rate5m
labels:
tier: edge
interval is optional. Omit it and the group inherits the global evaluation_interval.
3. Check the file before it touches the server. promtool parses the YAML and every expression in it:
promtool check rules /etc/prometheus/rules/http.yml
Checking /etc/prometheus/rules/http.yml
SUCCESS: 3 rules found
On a bad expression or an unknown key it prints FAILED: with the offending line and exits non-zero, which makes it the right gate in CI — run it on every rule file in the repo before merge.
4. Wire the file into prometheus.yml. rule_files takes a list of globs:
global:
scrape_interval: 15s
evaluation_interval: 30s
rule_files:
- /etc/prometheus/rules/*.yml
Use absolute paths. Relative globs are resolved against the process working directory, which differs between a systemd unit and a container, and a glob that matches nothing is not an error — it fails silently and you spend an hour wondering why no series appeared.
5. Validate the whole config, then reload. check config also follows rule_files and checks each matched file:
promtool check config /etc/prometheus/prometheus.yml
Checking /etc/prometheus/prometheus.yml
SUCCESS: 1 rule files found
Checking /etc/prometheus/rules/http.yml
SUCCESS: 3 rules found
Then reload in place — no restart, no gap in scraping:
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:9090/-/reload
200
If that returns 403 Lifecycle API is not enabled, use kill -HUP $(pidof prometheus) instead, or add --web.enable-lifecycle to the startup flags.
6. Confirm the rules are loaded and healthy. /api/v1/rules is the authoritative view of what the running server thinks it has, and ?type=record filters out the alerting rules:
curl -s 'http://localhost:9090/api/v1/rules?type=record' \
| jq -r '.data.groups[].rules[] | "\(.name) \(.health) \(.evaluationTime)"'
job:http_requests:rate5m ok 0.004182
job:http_request_errors:rate5m ok 0.006031
job:http_request_error_ratio:ratio_rate5m ok 0.000219
health is ok, err, or unknown. Anything other than ok comes with a lastError field on the same object explaining why.
7. Use the recorded series in Grafana. Replace the panel’s query with the recorded name. Nothing else about the panel changes:
job:http_requests:rate5m
The tier="edge" label from the rule file is available as a Grafana variable or filter like any other label. The one thing to fix by hand is the panel legend — it was probably showing a template based on the raw metric’s labels, and the recorded series only has the labels the aggregation kept.
8. Use the recorded series in an alerting rule. This is where recording rules pay off twice: the alert and the dashboard now read the same precomputed number, so they can never disagree:
groups:
- name: http-alerts
rules:
- alert: HttpErrorRatioHigh
expr: job:http_request_error_ratio:ratio_rate5m > 0.05
for: 10m
labels:
severity: warning
annotations:
summary: 'Edge 5xx ratio above 5 percent'
One caution on for: the alert only counts continuous time above the threshold, and the recorded series only gets a new sample every interval. A 1-minute rule interval with for: 2m gives the alert two or three samples to work with. Keep for comfortably larger than the rule interval.
9. Choose the evaluation interval deliberately. The floor is the scrape interval — evaluating faster than you scrape produces duplicate values and wasted CPU. A rule that feeds an alert on a fast-moving signal wants an interval close to the scrape interval. A rule that only backs a capacity dashboard is fine at 1m or 5m, and a longer interval is how you keep the recorded series small enough to stay cheap over multi-month ranges.
Validate it works
Confirm the new series exists and has plausible values. Give it at least one full interval after the reload, then query it:
curl -s --data-urlencode 'query=job:http_requests:rate5m' \
http://localhost:9090/api/v1/query \
| jq -r '.data.result[] | "\(.metric.job) \(.value[1])"'
api 41.32162162162162
web 128.7018018018018
Confirm it is fast now. Same timing command as step 1, against the recorded name:
curl -s -o /dev/null -w 'total: %{time_total}s\n' \
--data-urlencode 'query=job:http_requests:rate5m' \
http://localhost:9090/api/v1/query
total: 0.009s
Confirm the recorded value matches the raw expression. Subtracting one from the other should give a number at or very near zero on every job:
curl -s --data-urlencode 'query=job:http_requests:rate5m - sum by (job) (rate(http_requests_total[5m]))' \
http://localhost:9090/api/v1/query | jq -r '.data.result[].value[1]'
0
0
A small non-zero difference is normal — the rule was evaluated a few seconds ago and the raw expression is evaluated now.
Confirm no group is overrunning its interval. A group that takes longer to evaluate than its own interval will start skipping cycles. Query the ratio:
prometheus_rule_group_last_duration_seconds / prometheus_rule_group_interval_seconds
Anything above roughly 0.5 deserves attention; above 1.0 the group is already missing iterations, which you can confirm with prometheus_rule_group_iterations_missed_total. For per-rule detail, prometheus_rule_evaluation_duration_seconds gives you the distribution across all rules, and prometheus_rule_evaluation_failures_total counts hard failures.
Troubleshooting
- The reload succeeded but no new series appear. Check
/api/v1/rulesfirst. If the groups array is empty,rule_filesmatched nothing — almost always a relative path resolved against an unexpected working directory, or a.yamlfile matched by a*.ymlglob. If the group is listed andhealthisokbut the series still does not exist, the expression itself returns an empty result: run theexprby hand in the expression browser. A recording rule whose expression returns nothing writes nothing, silently and without error. health: errwith “vector contains metrics with the same labelset after applying rule labels”. Two output samples ended up identical after thelabels:block overwrote a distinguishing label. Either drop that label from thelabels:block, or aggregate it away in the expression withsum by (...)so the result is unique per label set before the block is applied.- The graph is empty before today. This is the caveat, not a bug: rule evaluation runs forward in time only. A rule added this morning has no data from yesterday and never will, so a 30-day panel on a new recorded series shows one day of line and 29 days of nothing. If you genuinely need the history,
promtool tsdb create-blocks-from rulesreads a rule file and generates TSDB blocks from existing raw data, which you then move into the data directory. Treat it as a one-time migration step, not routine operation. - A rule group takes longer than its interval.
prometheus_rule_group_last_duration_secondsexceedsprometheus_rule_group_interval_secondsandprometheus_rule_group_iterations_missed_totalclimbs. Because rules in a group are sequential, one slow rule delays every rule behind it. Split the group so unrelated rules stop waiting on each other, raise that group’sinterval, or narrow the expression’s range selector and label matchers. - The recorded name collides with something already in the TSDB. If you name a rule after a metric an exporter also produces, both write to the same series and the result is nonsense. This is the practical reason for the colon convention — a name like
job:http_requests:rate5mcannot collide with anything scraped, because exporters cannot emit colons.
When this is the wrong approach
Recording rules make queries cheaper. They do not make ingestion cheaper, and reaching for them to fix the wrong problem wastes a cycle.
- They do not reduce stored cardinality. The raw series are still scraped, still stored, and still counted against your active-series total — you have added series, not removed them. If the actual problem is ingest volume, the tools are
metric_relabel_configsto drop labels or series at scrape time, and fixing the instrumentation that emits a user ID as a label. See federation and cardinality budgets for how to size that. - Where they do earn their place on cardinality is federation. A
/federateendpoint that exposes only recorded aggregates lets a global Prometheus pull a few hundred series per leaf instead of hundreds of thousands. Define the aggregation on the leaf, federate the recorded names, and the global server never sees the raw labels. - Deciding which expressions deserve a rule is a separate question from writing one. This guide is the mechanics; for choosing what to pre-compute, what to leave at query time, and how to hold the whole rule set to a cardinality budget, see recording rule strategy and cardinality budgets.
- They are not for exploration. A rule you write to answer one question this afternoon is overhead forever. Ad-hoc analysis belongs in the expression browser, where a wider
stepon a range query solves the same slowness for free. - They are not long-term storage or downsampling. A recording rule at a 5-minute interval reduces resolution as a side effect, but it does not extend retention or give you a global query view. If that is the goal, Thanos, Mimir, or a remote-write backend is the answer, not a longer rule interval.
- They cannot fix an expression that is wrong. Precomputing a misleading aggregate just makes the wrong number arrive faster, on more dashboards, and in the alert too. Validate the expression against reality first, then record it.
The authoritative references are the Prometheus recording rules configuration page for the exact schema, and rule naming and recording best practices for the naming convention.
If alerts fire into an empty room after hours, that’s exactly what 24/7 Monitoring & Response closes — book a monitoring and response review.