Recording & alerting rules
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A rule is a named PromQL expression, evaluated on evaluation_interval and grouped into rule
groups inside YAML files referenced from the rule_files entry of prometheus.yml. Prometheus supports two
kinds: recording rules, which save an expression’s result as a new time series, and alerting
rules, which turn an expression’s result into a firing or resolved alert. This page covers the
evaluation cycle that drives both, the naming convention and use cases for recording rules, the
for/labels/annotations fields and templating syntax for alerting rules, and validating both
with promtool. A first alerting rule already appeared in
Getting Started; this page covers writing rules well,
not just writing one.
Every example below belongs to one running scenario: an orders-api service that exposes
http_requests_total{method, status} and is scraped as job="orders-api". The same rule file is fed
to promtool, loaded into a real Prometheus server, and routed through a real Alertmanager in
Alertmanager, so the outputs shown are what those tools
printed.
How rules are evaluated
Rules are not triggered by queries or by scrapes; a rule manager walks every rule group on that
group’s own timer, runs each expr as an instant query against the local TSDB, and writes the
outcome back:
http_requests_total"] --> TSDB[("Local TSDB")] TSDB --> RG["Rule group tick
every interval"] RG --> REC["Recording rule
expr result"] RG --> ALR["Alerting rule
expr result"] REC -->|"appended as new series"| TSDB ALR -->|"ALERTS and ALERTS_FOR_STATE series"| TSDB ALR -->|"firing alerts over HTTP"| AM["Alertmanager"] TSDB --> DASH["Dashboards and ad hoc queries"]
Two consequences matter in practice. First, a recording rule’s output is stored exactly like a scraped
series, timestamped at the evaluation instant, so a recorded series is always at least one evaluation
interval behind the raw data it summarises. Second, an alerting rule also writes to the TSDB: every
pending or firing alert instance is exposed as an ALERTS series (with an extra alertstate label)
plus an ALERTS_FOR_STATE series that lets the server restore the for countdown after a restart.
Rule groups
Both rule types live in the same file structure: one or more named groups, each holding an ordered
list of rules evaluated sequentially on that group’s own interval (defaulting to the global
evaluation_interval if unset). Rules within a group can see the results of earlier rules in the
same evaluation cycle, which is what lets an alerting rule reference a recording rule defined above
it in the same group.
groups:
- name: orders-api.rules
interval: 30s # optional: overrides evaluation_interval for this group only
limit: 0 # optional: maximum series a rule may produce (0 means unlimited)
query_offset: 0s # optional: evaluate as of "now minus offset" to tolerate late samples
rules:
- record: ... # a recording rule
- alert: ... # an alerting rule
# https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/
Rules in different groups run concurrently and independently, which is why a rule that depends on another’s output must sit in the same group, after it. Split unrelated rules into separate groups instead of one large one, so a slow group’s evaluation time does not delay unrelated rules.
|
|
Recording rules
A recording rule precomputes an expression and stores it as a new metric, on every evaluation, just like a regular scrape would:
groups:
- name: orders-api.rules
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
# https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/
job:http_requests:rate5m is itself queryable, exactly like any scraped metric — job:http_requests:rate5m{job="orders-api"} returns the precomputed value instantly instead of
re-running the sum(rate(...)) aggregation on every query. See
Recording rules for the
full rule-group syntax, including record, expr, and the optional labels a recording rule may
attach to every series it produces.
The level:metric:operations naming convention
Recording rule names should follow level:metric:operations, so a glance at the name tells you what
aggregation level it is at and what was done to reach it, without reading the expression:
-
level— the aggregation labels remaining after the rule runs (job,instance,job_instance, or a colon-free base metric name for no aggregation). -
metric— the original metric name, with its_total/unit suffix generally kept. -
operations— the PromQL operations applied, outermost first, separated by underscores (for examplerate5mfor a five-minuterate(), orirateforirate()).
groups:
- name: orders-api.rules
rules:
# level: job -- aggregated down to just the job label
# metric: http_requests_total
# operations: rate applied over a 5m window, then summed
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
# level: job_status -- job and status both survive the aggregation
- record: job_status:http_requests:rate5m
expr: sum by (job, status) (rate(http_requests_total[5m]))
# level: instance -- no aggregation, just a renamed rate() over one series per instance
- record: instance:node_cpu:rate5m
expr: rate(node_cpu_seconds_total{mode!="idle"}[5m])
Two practical rules keep the convention honest. Aggregate with sum by (...) (naming the labels to
keep) rather than without, so the level in the name stays accurate when someone adds a label to the
source metric. And when a rule divides one aggregate by another, name the result as a ratio of the
operations, for example job:http_requests_errors:ratio_rate5m, which is the rule used for alerting
in the rest of this page. See
the
naming convention in Recording rules for the authoritative definition of each segment.
|
The convention is advisory. |
Use cases
Recording rules exist to trade evaluation cost, paid once per evaluation_interval, against query
cost, paid on every dashboard load or every downstream rule evaluation:
-
Dashboards queried often. A Grafana panel re-runs its query every time someone opens the dashboard or it auto-refreshes; if the underlying expression is an expensive
sum(rate(...))over high-cardinality series, precomputing it once as a recording rule turns every panel load into a cheap lookup instead of a repeated aggregation. See Grafana: Dashboards & Visualization for wiring recorded series into panels. -
Expressions reused by other rules. When several alerting rules threshold-check the same aggregation (error rate by job, saturation by instance), computing it once as a recording rule and referencing it from every alert avoids repeating — and re-evaluating — the same subquery multiple times per cycle.
-
Long-window or high-cardinality aggregations. A
rate()over a long range, or asum bythat collapses a very high-cardinality label, can be slow enough at query time to time out an ad-hoc request; the same computation as a recording rule pays that cost once on the server’s own schedule instead of once per caller. -
Federation and remote write. Pre-aggregated series are what a global server federates or what you keep when raw series are dropped before
remote_write; see Storage, Federation & Remote Write.
Recording rules do not reduce raw sample storage or cardinality on their own — the source series are still scraped and retained — they only avoid re-deriving an aggregate from them repeatedly. They also cost something: every rule adds series to the TSDB, so record what is queried repeatedly, not every intermediate expression. Reducing retained cardinality itself is covered in Storage, Federation & Remote Write.
Alerting rules
An alerting rule evaluates a boolean-producing expression on every cycle; whenever the expression
returns any series, an alert instance is created per returned series and moves through inactive →
pending → firing (or back to inactive once the expression stops matching). The orders-api rules
used in the rest of this page record the error ratio once and alert on it:
# rules/orders_api_rules.yml
groups:
- name: orders-api.rules
interval: 15s
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
- record: job_status:http_requests:rate5m
expr: sum by (job, status) (rate(http_requests_total[5m]))
- record: job:http_requests_errors:ratio_rate5m
expr: |
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total[5m]))
- name: orders-api.alerts
interval: 15s
rules:
- alert: OrdersApiHighErrorRate
expr: job:http_requests_errors:ratio_rate5m{job="orders-api"} > 0.05
for: 1m
labels:
severity: page
team: orders
annotations:
summary: "{{ $labels.job }} error rate above 5%"
description: >-
{{ $labels.job }} has a {{ $value | humanizePercentage }} error rate over the
last 5 minutes (threshold 5%).
- alert: OrdersApiDown
expr: up{job="orders-api"} == 0
for: 30s
labels:
severity: critical
team: orders
annotations:
summary: "{{ $labels.instance }} is down"
# https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/
The ratio is computed as one recording rule rather than inline in the alert, which is exactly the
"reused by other rules" case above: dashboards, a second alert and a Grafana-managed rule can all
share the same job:http_requests_errors:ratio_rate5m series. The short for values here keep the
lab fast; production values are discussed next.
The alert life cycle
In the running example the error rate was pushed above 5% and the alert was observed through the HTTP
API (/api/v1/alerts), first pending, then firing after the one-minute for plus the time it took
the five-minute ratio to cross the threshold:
{
"labels": {
"alertname": "OrdersApiHighErrorRate",
"job": "orders-api",
"severity": "page",
"team": "orders"
},
"annotations": {
"description": "orders-api has a 13.44% error rate over the last 5 minutes (threshold 5%).",
"summary": "orders-api error rate above 5%"
},
"state": "firing",
"activeAt": "2026-11-10T13:37:09.787130049Z",
"value": "1.3440647060111408e-01"
}
Note that activeAt is when the alert became pending, not when it started firing, and that
value is the raw float that {{ $value }} formats. The same alert is visible as a time series, which
is how dashboards and meta-alerts consume it:
ALERTS{alertname="OrdersApiHighErrorRate", alertstate="firing"}
ALERTS{alertname="OrdersApiHighErrorRate", alertstate="firing", job="orders-api", severity="page", team="orders"} 1
for: avoiding flapping
for: 10m requires the expression to keep matching a given series continuously across every
evaluation for that whole duration before the alert leaves pending and becomes firing; a single
evaluation where the condition briefly stops holding resets that series back to inactive. This is
what keeps a noisy metric that crosses a threshold for one scrape from paging anyone — without for
(or with it set to 0s), the alert fires the instant the expression matches, which is appropriate
only for conditions that must never wait, such as up == 0 on a critical target. Longer for
durations trade faster detection for fewer transient false pages; Status > Alerts in the expression
browser shows each alert’s current state and how long it has been pending. See
Alerting rules for the
full pending/firing/inactive state machine.
A useful sizing rule is that for should span several evaluation intervals and be at least as long
as the transient you want to ignore: a deploy that restarts pods for two minutes should not page, so
for: 5m is a more honest choice than for: 1m for latency or error-ratio alerts on a service that
deploys during working hours.
The counterpart is keep_firing_for, which keeps an alert firing for a further duration after its
expression stops matching:
- alert: OrdersApiHighErrorRate
expr: job:http_requests_errors:ratio_rate5m{job="orders-api"} > 0.05
for: 5m
keep_firing_for: 10m # stay firing 10 more minutes after the ratio drops below 5%
Where for delays the start, keep_firing_for delays the end, which damps an alert whose expression
oscillates around its threshold and would otherwise generate a stream of resolved/firing
notifications.
labels: routing metadata
labels on an alerting rule are attached to every alert instance it produces, merged with the labels
already on the series the expression returned. They exist to be matched on downstream, not to be read
by a human — severity, team, and similar dimensions are what
Alertmanager's routing tree and inhibition rules match
against to decide who gets paged and through which receiver. A labels value can itself use the
{{ }} templating described below, though this is far less common than templating annotations.
Two cautions follow from how alerts are identified. An alert instance is identified by its full label
set, so a label whose value changes (a templated label containing $value, for example) creates a new
alert on every change and resets its for timer. Keep label values stable, and put anything that varies
into an annotation.
annotations: human-readable text
annotations, by contrast, carry the free-text a human actually reads — conventionally summary (a
one-line description) and description (more detail) — and are never used for Alertmanager routing.
Because annotation values are templated per alert instance, they can embed the value and labels that
triggered that specific instance rather than a generic message. Other conventional annotations are
runbook_url, linking to the page that explains how to react, and dashboard, linking to the Grafana
dashboard that shows the same series.
Templating: {{ $value }} and {{ $labels.foo }}
Annotation (and label) values are Go templates evaluated once per alert instance, with these variables in scope:
| Variable | Meaning |
|---|---|
|
The numeric result of |
|
A map of that series’s label set ( |
|
The server’s |
|
The server’s own external URL, for building links back to Prometheus. |
Template functions like humanize, humanizePercentage, humanizeDuration, humanize1024 and
printf format $value for a human instead of dumping a raw float:
annotations:
summary: "High memory usage on {{ $labels.instance }}"
description: >-
{{ $labels.instance }} is using {{ $value | humanizePercentage }} of available memory
(job {{ $labels.job }}).
runbook_url: "https://runbooks.example.com/memory/{{ $labels.job }}"
With the lab alert above, the description template rendered as orders-api has a 13.44% error rate
over the last 5 minutes (threshold 5%)., as in the JSON output earlier. A template can also query
Prometheus with the query function, for example to attach a second number to a notification (a unit test with this template rendered rate 2; again 2 req/s.):
annotations:
description: >-
rate {{ $value | humanize }};
again {{ with printf "job:http_requests:rate5m{job='%s'}" $labels.job | query }}{{ . | first | value | humanize }}{{ end }} req/s.
See
Template reference
for the complete set of available functions and variables, including $labels access via bracket
notation ({{ index $labels "label.with.dots" }}) for label names that are not valid Go identifiers.
A template error does not stop the rule from evaluating; it is logged and the annotation comes out
empty or partial, so always confirm rendered text in the Alerts page or the /api/v1/alerts output.
Patterns worth knowing
-
Absence. A target that disappears produces no series, and a threshold on a missing series never matches.
up == 0catches a failed scrape, whileabsent(up{job="orders-api"})catches the case where the whole job has vanished from service discovery. -
Ratios, not counts. Alert on
errors / total(the recorded ratio above), not on the absolute number of errors, so the threshold keeps its meaning as traffic grows. -
Symptoms before causes. Page on user-visible symptoms (error ratio, latency) and keep cause-level alerts (disk, queue depth) at warning severity; Alertmanager’s inhibition can then suppress the warnings while the page is firing.
-
One owner per alert. Every alert needs a
teamlabel and arunbook_url; an alert nobody owns is noise.
Testing rules with promtool
promtool, bundled alongside the prometheus binary, validates rule files two ways: a static syntax
check, and a full unit test against synthetic input series.
promtool check rules
Checks a rules file parses, every expr is valid PromQL, and flags duplicate rules, without
evaluating anything against real data:
promtool check rules rules/orders_api_rules.yml
Checking rules/orders_api_rules.yml
SUCCESS: 5 rules found
A broken expression is reported with its group, rule number and position, and the command exits with a non-zero status, which is what makes it usable as a CI gate:
Checking /x/r.yml
FAILED:
/x/r.yml: 16:15: group "demo", rule 4, "Broken": could not parse expression: 1:34: parse error: unclosed left parenthesis
Defining the same recorded series twice is caught by the default --lint=duplicate-rules check
(--lint=none turns it off and --lint-fatal makes lint findings fail the command).
promtool test rules
Runs one or more rule files against a synthetic time series you define, at simulated points in time,
and asserts the recorded series and firing alerts that should exist at each point — catching a wrong
threshold, a missing for, or an inverted comparison before the rule ever reaches production. The test
file for the orders-api rules feeds a steady 6% error ratio, then a steady 4%:
# tests/orders_api_rules_test.yml
rule_files:
- ../rules/orders_api_rules.yml
evaluation_interval: 1m
tests:
- name: sustained 6 percent errors fires after the for window
interval: 1m
input_series:
- series: 'http_requests_total{job="orders-api", status="500"}'
values: "0+6x30" # +6 requests per minute of 500s, 30 steps
- series: 'http_requests_total{job="orders-api", status="200"}'
values: "0+94x30" # +94 requests per minute of 200s over the same window
promql_expr_test:
- expr: job:http_requests:rate5m{job="orders-api"}
eval_time: 10m
exp_samples:
- labels: 'job:http_requests:rate5m{job="orders-api"}'
value: 1.6666666666666667
alert_rule_test:
# One minute in, the ratio series is too young to have crossed the threshold for 1m.
- eval_time: 1m
alertname: OrdersApiHighErrorRate
exp_alerts: []
# After the ratio has stayed at 6% for longer than the for duration, it must be firing.
- eval_time: 15m
alertname: OrdersApiHighErrorRate
exp_alerts:
- exp_labels:
job: orders-api
severity: page
team: orders
exp_annotations:
summary: "orders-api error rate above 5%"
description: "orders-api has a 6% error rate over the last 5 minutes (threshold 5%)."
- name: 4 percent errors stays below the threshold
interval: 1m
input_series:
- series: 'http_requests_total{job="orders-api", status="500"}'
values: "0+4x30"
- series: 'http_requests_total{job="orders-api", status="200"}'
values: "0+96x30"
alert_rule_test:
- eval_time: 20m
alertname: OrdersApiHighErrorRate
exp_alerts: []
# https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/
cd tests && promtool test rules orders_api_rules_test.yml
SUCCESS
A test that disagrees with the rules fails loudly and shows both sides. Changing the expected
summary to say 10% produced:
FAILED:
name: sustained 6 percent errors fires after the for window,
alertname: OrdersApiHighErrorRate, time: 15m,
exp:[
0:
Labels:{alertname="OrdersApiHighErrorRate", job="orders-api", severity="page", team="orders"}
Annotations:{description="orders-api has a 6% error rate over the last 5 minutes (threshold 5%).", summary="orders-api error rate above 10%"}
],
got:[
0:
Labels:{alertname="OrdersApiHighErrorRate", job="orders-api", severity="page", team="orders"}
Annotations:{description="orders-api has a 6% error rate over the last 5 minutes (threshold 5%).", summary="orders-api error rate above 5%"}
]
input_series.values uses the compact series-value syntax of promtool (0+6x30 means: start at 0, add 6
at each of the next 30 steps of interval; _ is a missing sample and stale a staleness marker); a
recording rule is asserted via promql_expr_test, comparing the recorded series' value at a given
eval_time against an exp_samples list. Because rule_files paths are resolved relative to the test
file, keep tests next to the rules (or in a tests/ directory one level below, as above). See
Unit testing rules
for the full test-file schema, including multiple input_series blocks per group, exp_alerts with
several instances and testing several rule files together. Run both checks in CI before a rules file
is deployed — check rules catches syntax errors immediately, test rules catches logic errors that
only show up once real data flows through the expression.
Continue with Alertmanager for what happens to a firing alert once Prometheus has produced it — grouping, routing, silencing, and delivery to a receiver — or back up to PromQL: Functions for the aggregation and rate functions that recording-rule expressions like the ones above are built from.