Data and monitoring · Intermediate · 20 min
Speed up dashboards with Prometheus recording rules
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Prometheus 3.16.0 · Node Exporter 1.12.1
You will turn a slow CPU dashboard query and a request-rate query into Prometheus 3.16 recording rules with level:metric:operations names, prove them with promtool test rules, load them into a running Prometheus and point a Grafana panel at the recorded series.
On this page
Every time a Grafana dashboard refreshes, each panel sends its PromQL to Prometheus, and Prometheus works the answer out from raw samples again. A panel that averages rate() over every CPU of every server reads thousands of samples per refresh, and a dashboard left open on a wall screen does that all day. Multiply by ten panels and a few people looking, and the dashboard becomes slow for everyone.
A recording rule moves that work to Prometheus's own schedule. Prometheus evaluates the expression every 30 seconds or every minute, stores the answer as a new series with its own name, and the dashboard reads that one small series instead. The answer is the same; the cost is paid once per interval instead of once per viewer per refresh.
In this tutorial you build two groups of rules on the server from the Prometheus tutorial: CPU utilisation per server and across the fleet, and Prometheus's own HTTP request rate by handler. You measure the query before and after, check and unit-test the rules with promtool before Prometheus ever loads them, and finish by deciding which queries are not worth recording.
Step 1 · Measure the query you want to speed up
Start with a query from a real dashboard. The CPU busy panel from the Grafana tutorial asks for the share of time all CPUs were not idle. Run it against the HTTP API with stats=true, which makes Prometheus report how much work the query took:
promtool --version | head -n 1
RAW='1 - avg(rate(node_cpu_seconds_total{mode="idle"}[5m]))'
curl -s http://127.0.0.1:9090/api/v1/query \
--data-urlencode "query=${RAW}" --data-urlencode 'stats=true' |
jq '{value: .data.result[0].value[1], samples: .data.stats.samples.totalQueryableSamples, seconds: .data.stats.timings.evalTotalTime}'samples is the number of stored samples Prometheus had to read for this one answer. With a 15-second scrape interval, a 5-minute window holds about 20 samples per series, and there is one idle series per CPU core, so a 4-core server gives about 80. A dashboard draws a line, not a single point: for a 6-hour graph Grafana asks for hundreds of points, and each point costs that much again.
Check it worked
The first line starts with promtool, version 3.16.0. The JSON shows a value between 0 and 1 (the busy fraction), a samples count of at least 2, and a small seconds figure, typically around a millisecond or less on one server. Write down samples: you compare it with the recorded version later. On a fleet of 200 servers the same query reads 200 times as much, which is when panels start to feel slow.
Step 2 · Write the rules with names that explain themselves
Recording rules live in a YAML file of groups. Each group has a name, an interval (how often its rules run) and a list of rules. Each rule has a record (the new series name) and an expr (the PromQL). Rules in a group run one after another at the same evaluation time, so a later rule can build on a series recorded earlier in the same group.
Prometheus's naming convention is level:metric:operations:
levelis the labels left on the result, joined with_:instancemeans one series per server,jobone per job,job_handlerone per job and handler.metricis the original metric name, with_totaldropped oncerate()has been applied.operationslists what was done to it, newest first:rate5m, orratio_rate5mfor a ratio of 5-minute rates.
A name like job:node_cpu_utilisation:ratio_rate5m therefore tells a reader, without opening the file, that it holds one series per job, comes from CPU seconds, and is a ratio of 5-minute rates.
Create a folder for rule files and write the file. If you followed the Alertmanager tutorial, the folder already exists and holds server.yml; this adds a second file next to it:
sudo install -d -m 0755 /etc/prometheus/rules
sudo tee /etc/prometheus/rules/recording.yml > /dev/null <<'YAML'
groups:
- name: node_cpu
interval: 30s
limit: 1000
rules:
# CPU seconds per second, per server and mode, summed over cores.
- record: instance_mode:node_cpu_seconds:rate5m
expr: sum without (cpu) (rate(node_cpu_seconds_total[5m]))
# Share of time each server's CPUs were busy (0 to 1).
- record: instance:node_cpu_utilisation:ratio_rate5m
expr: |
1 - (
sum without (mode) (instance_mode:node_cpu_seconds:rate5m{mode="idle"})
/
sum without (mode) (instance_mode:node_cpu_seconds:rate5m)
)
# Share of time all CPUs in the job were busy, weighted by core count.
- record: job:node_cpu_utilisation:ratio_rate5m
expr: |
1 - (
sum without (instance, mode) (instance_mode:node_cpu_seconds:rate5m{mode="idle"})
/
sum without (instance, mode) (instance_mode:node_cpu_seconds:rate5m)
)
- name: prometheus_http
interval: 1m
rules:
# Requests per second to each Prometheus HTTP handler, all status codes.
- record: job_handler:prometheus_http_requests:rate5m
expr: sum without (instance, code) (rate(prometheus_http_requests_total[5m]))
YAML
promtool check rules /etc/prometheus/rules/recording.ymlA few choices in this file are worth knowing:
- The first rule does the expensive part,
rate()over every core, once. The other two read its small output. - The fleet-wide rule adds up idle time and total time across servers and then divides. It does not average the per-server ratios: a 1-core server and a 16-core server would then count equally, which gives the wrong answer for the fleet.
without (cpu)names the labels to remove rather than the ones to keep, so labels such asjobandinstancesurvive, along with any you add later, such asenv.limit: 1000makes a rule fail, rather than quietly write thousands of new series, if a mistake ever multiplies its output. The first rule writes one series per server per CPU mode (about eight modes), so 1000 leaves room for over 100 servers. Raise it as you grow.- The CPU group runs every 30 seconds because a dashboard can show its result at that resolution. The request-rate group runs every minute, which is enough for a trend line.
Check it worked
promtool prints Checking /etc/prometheus/rules/recording.yml and then SUCCESS: 4 rules found. A typo in PromQL or YAML prints the line and the problem instead, and the command exits with status 1.
Step 3 · Prove the rules give the right numbers
promtool check rules only proves the file parses. To prove the rules calculate what you mean, give promtool test rules some made-up input series with known values and state the exact answers you expect.
The test below invents two servers. Server a has one core that is idle 15 seconds of every minute. Server b has three cores, each idle 45 seconds of every minute. The notation 0+15x10 means "start at 0 and add 15 at each of the next 10 samples", one sample per minute, which is how a counter grows:
mkdir -p ~/recording-rules-demo
cat > ~/recording-rules-demo/recording-test.yml <<'YAML'
rule_files:
- /etc/prometheus/rules/recording.yml
evaluation_interval: 30s
tests:
- name: cpu utilisation and request rates
interval: 1m
input_series:
# Server a: 1 core, idle 15 s and busy 45 s of every minute.
- series: 'node_cpu_seconds_total{job="node", instance="a:9100", cpu="0", mode="idle"}'
values: '0+15x10'
- series: 'node_cpu_seconds_total{job="node", instance="a:9100", cpu="0", mode="user"}'
values: '0+45x10'
# Server b: 3 cores, each idle 45 s and busy 15 s of every minute.
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="0", mode="idle"}'
values: '0+45x10'
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="0", mode="user"}'
values: '0+15x10'
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="1", mode="idle"}'
values: '0+45x10'
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="1", mode="user"}'
values: '0+15x10'
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="2", mode="idle"}'
values: '0+45x10'
- series: 'node_cpu_seconds_total{job="node", instance="b:9100", cpu="2", mode="user"}'
values: '0+15x10'
# 60 + 30 requests a minute to the query API, 15 a minute to /metrics.
- series: 'prometheus_http_requests_total{job="prometheus", instance="localhost:9090", handler="/api/v1/query", code="200"}'
values: '0+60x10'
- series: 'prometheus_http_requests_total{job="prometheus", instance="localhost:9090", handler="/api/v1/query", code="400"}'
values: '0+30x10'
- series: 'prometheus_http_requests_total{job="prometheus", instance="localhost:9090", handler="/metrics", code="200"}'
values: '0+15x10'
promql_expr_test:
- expr: instance:node_cpu_utilisation:ratio_rate5m
eval_time: 10m
exp_samples:
- labels: 'instance:node_cpu_utilisation:ratio_rate5m{job="node", instance="a:9100"}'
value: 0.75
- labels: 'instance:node_cpu_utilisation:ratio_rate5m{job="node", instance="b:9100"}'
value: 0.25
# 4 cores in total, 2.5 of them idle: 1 - 2.5/4 = 0.375.
- expr: job:node_cpu_utilisation:ratio_rate5m
eval_time: 10m
exp_samples:
- labels: 'job:node_cpu_utilisation:ratio_rate5m{job="node"}'
value: 0.375
# Averaging the two ratios would wrongly give 0.5.
- expr: avg without (instance) (instance:node_cpu_utilisation:ratio_rate5m)
eval_time: 10m
exp_samples:
- labels: '{job="node"}'
value: 0.5
- expr: job_handler:prometheus_http_requests:rate5m
eval_time: 10m
exp_samples:
- labels: 'job_handler:prometheus_http_requests:rate5m{job="prometheus", handler="/api/v1/query"}'
value: 1.5
- labels: 'job_handler:prometheus_http_requests:rate5m{job="prometheus", handler="/metrics"}'
value: 0.25
YAML
promtool test rules ~/recording-rules-demo/recording-test.ymlServer a is busy 45 of every 60 seconds, so its utilisation is 0.75. Server b is busy 15 of every 60 seconds on each core, so 0.25. Across both, 2.5 of the 4 cores are idle, so the fleet is 0.375 busy. The third test is there to show the trap from the previous step: the plain average of 0.75 and 0.25 is 0.5, which overstates how busy the fleet is because the small server counts as much as the big one.
Check it worked
The output starts with Unit Testing: and the file name, and the last line is SUCCESS. To see what a failure looks like, change 0.375 to 0.4 in the test file and run the command again: promtool prints FAILED:, the expression, and the expected and actual results side by side. Change it back before you continue. Keep this file next to the rules, for example in Git, and run it whenever you edit them.
Step 4 · Load the rules into Prometheus
Prometheus loads rule files listed under rule_files in its configuration.
If you followed the Alertmanager tutorial, your prometheus.yml already has rule_files with /etc/prometheus/rules/*.yml, and also an alerting section. Skip the next command in that case: the new file is already covered by the pattern, and rewriting the configuration would remove the alerting section.
Otherwise, rewrite the configuration from the Prometheus tutorial with a rule_files section added. evaluation_interval is the default for groups that do not set their own interval:
sudo tee /etc/prometheus/prometheus.yml > /dev/null <<'YAML'
global:
scrape_interval: 15s
evaluation_interval: 1m
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ["127.0.0.1:9090"]
- job_name: node
static_configs:
- targets: ["127.0.0.1:9100"]
YAMLCheck the configuration and every rule file it points to, then reload. A reload re-reads the files without restarting Prometheus, and it only applies the change if every file is valid:
promtool check config /etc/prometheus/prometheus.ymlsudo systemctl reload prometheuspromtool check config prints SUCCESS: 1 rule files found (2 if you also have server.yml from the Alertmanager tutorial) and a SUCCESS line for each rule file. Now ask Prometheus which recording rules it has loaded. Give it a minute first, so both groups have run at least once:
curl -s 'http://127.0.0.1:9090/api/v1/rules?type=record' |
jq -r '.data.groups[] | .name as $g | .interval as $i | .rules[] | "\($g) every \($i)s \(.health) \(.name)"'Check it worked
You get four lines, three for node_cpu every 30s and one for prometheus_http every 60s, and each says ok. A rule that says err has a problem only visible with real data, such as hitting its limit; the lastError field in the same JSON says what. If the list is empty, check that the reload worked: prometheus_config_last_reload_successful should be 1.
Step 5 · Query the recorded series
Recorded series are ordinary series. Query them like any metric, and compare the cost with the raw query from the first step:
q() {
curl -s http://127.0.0.1:9090/api/v1/query \
--data-urlencode "query=$1" --data-urlencode 'stats=true' |
jq -c '{result: [.data.result[] | {labels: (.metric | del(.__name__)), value: .value[1]}], samples: .data.stats.samples.totalQueryableSamples}'
}
q 'job:node_cpu_utilisation:ratio_rate5m'
q 'instance:node_cpu_utilisation:ratio_rate5m'
q 'job_handler:prometheus_http_requests:rate5m{handler="/api/v1/query"}'Check it worked
The first line shows one result with the label job set to node and a value between 0 and 1, close to the value of the raw query from the first step. It will not match to the last digit: the recorded value can be up to 30 seconds old, and it divides by the sum of all CPU modes rather than by the number of cores. The samples count is 1, against the dozens or hundreds you wrote down earlier. The second line has one result per server with an instance label, and the third shows a small requests-per-second figure for the query API, which your own curl calls have been feeding.
Recorded series only exist from the moment the rule starts. A graph of job:node_cpu_utilisation:ratio_rate5m over the last week is empty before today; Prometheus does not fill in the past for you.
Step 6 · Point the Grafana panel at the recorded series
Now make the dashboard use the cheap series. Button names may differ slightly in your Grafana version. Open the Server overview dashboard, choose Edit, then open the CPU busy panel's menu and choose Edit. Replace the query with:
100 * job:node_cpu_utilisation:ratio_rate5m{job="node"}The old query used $__rate_interval, which lets Grafana widen the rate() window as you zoom out. The recorded series has its window fixed at 5 minutes, so that variable no longer applies. Two consequences:
- Zoomed right in, the line is smoother than before, because each point is a 5-minute average.
- There is no point asking for a point more often than the rule runs. Open Query options above the query and set Min interval to
30s, the group's interval, so Grafana never asks for finer steps than exist.
To chart each server separately, add a second query, 100 * instance:node_cpu_utilisation:ratio_rate5m, with the legend set to {{instance}}. Save the dashboard. If you keep the dashboard as a file in /etc/grafana/dashboards/, as in the Grafana tutorial, export it as JSON afterwards and replace the file, so the file and the browser agree.
The panel's query now returns faster, because Prometheus reads one stored series instead of computing rate() over every core. The gain grows with the number of servers and the number of people viewing the dashboard.
Check it worked
The CPU busy panel draws the same shape as before for the period since the rule started, and is empty before it. Open the panel menu's Inspect option and its Query tab: the request Grafana sends names job:node_cpu_utilisation:ratio_rate5m, not node_cpu_seconds_total.
Step 7 · Decide what not to record, and watch the cost
Each recording rule costs Prometheus work on every interval, whether or not anyone looks, and adds series to store for the whole retention period. Record a query when it is:
- on a dashboard that is open often, or on many dashboards,
- used by alerts, so that alert expressions stay short and readable,
- expensive: it reads many series, a long window, or both.
Do not record:
- a query someone runs a few times a month while investigating. Rules run every interval; rarely used queries cost more as rules than as ad hoc queries.
- a query whose filter changes per viewer, such as a dashboard variable for one server. Record the aggregation without the filter, as
instance:node_cpu_utilisation:ratio_rate5mdoes, and filter the recorded series in the panel. - a query that does not aggregate anything. Recording
rate()for every series one to one doubles the storage and saves little.
Prometheus reports how long each group takes and whether it falls behind:
for m in prometheus_rule_group_last_duration_seconds prometheus_rule_group_interval_seconds prometheus_rule_group_iterations_missed_total; do
echo "$m"
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode "query=${m}{rule_group=~\".*recording.yml;.*\"}" |
jq -r '.data.result[] | " \(.metric.rule_group | split(";")[1]) \(.value[1])"'
doneCheck it worked
For both node_cpu and prometheus_http you see a last duration (a small fraction of a second), the interval (30 and 60), and 0 missed iterations. If a group's duration ever approaches its interval, Prometheus starts skipping runs and the missed count climbs: split the group, lengthen the interval, or remove rules nobody uses.
Step 8 · Remove the demo
If you want to keep the rules, keep /etc/prometheus/rules/recording.yml and move the test file into version control with your configuration. To remove them instead, delete the rule file and the demo folder, then reload. Do this only after pointing the Grafana panel back at its original query, or the panel goes blank. Series already recorded stay in the database until the retention period expires.
sudo rm /etc/prometheus/rules/recording.yml
rm -r ~/recording-rules-demo
promtool check config /etc/prometheus/prometheus.ymlsudo systemctl reload prometheusYou can leave the rule_files line in prometheus.yml: a pattern that matches no files is valid.
Check it worked
promtool check config ends with SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax, and no longer lists recording.yml (any other rule file, such as the Alertmanager one, is still checked). After the reload, the /api/v1/rules?type=record query from earlier returns no groups.
Next steps
- Write the PromQL worth recording in the first place: write PromQL for request rates, errors and latency.
- Build alerts on top of recorded error ratios: alert on SLO burn rate with Prometheus.
- Route the alerts to people: send alerts with Prometheus Alertmanager.
- Add more panels that read recorded series: build your first Grafana dashboard.
Related tutorials
- Alert when a cron job or batch job silently stops runningYou will have a nightly backup job that pushes its last-success time and duration to Pushgateway 1.11, and tested Prometheus 3.16 alert rules that fire when the job is late, slow or has never reported, plus a heartbeat ping as a second, independent check.
- Write PromQL for request rates, errors and latencyYou will write the PromQL queries for a service's request rate, error ratio and p95 latency, plus week-on-week and missing-data checks, and prove every one with promtool unit tests over synthetic data.
- Instrument a Python app with Prometheus metricsYou will add a request counter, a latency histogram, an in-progress gauge and a version metric to a FastAPI app with prometheus-client 0.26, serve them on a private port, and have Prometheus 3.16 scrape and query them.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials