Designing Prometheus Alert Rules: PromQL and Alertmanager Routing
An alert rule takes five lines of YAML to write: an expression, a for, a couple of labels, and a sentence of description. Precisely because it is that cheap, most rule libraries grow in a "add one after each incident" rhythm — one more rule per postmortem, never removed. Six months later nobody can say when a given rule last fired, let alone whether the decision it made at that moment was correct.
The real acceptance criterion for a rule is not "it loads without errors" but proof in two directions: it fired when it should have, and it stayed quiet when it should have. The first direction can still be checked against incident records. The second leaves almost no trace — a non-firing alert produces no log line, no report, and no red number. A team therefore usually knows which rules have fired, and knows nothing about what it missed.
Making both directions testable requires one move: treat rules as code, with inputs, assertions, and a version history. The design work that happens after an alert fires — severity tiers, routing, inhibition — is covered in Alerting Design Basics; this article deals with the rule file itself.
1. Two Kinds of Rules: One for Performance, One for Firing
A Prometheus rule file can hold two different things. They share the same PromQL, live inside the same groups structure, and even fail validation in the same way, but their purposes are unrelated. Mixing them up is the first source of an unmaintainable rule library.
1.1 Recording rules are a performance tool, not an alerting tool
A recording rule precomputes a complex PromQL expression and writes the result back as a new metric. It pays off in three layers: it turns "recompute on every query" into "compute once per evaluation, read many times"; it keeps an expression that a dozen dashboards and alerts reference defined in exactly one place; and it gives that expression a name, so troubleshooting reads job:http_requests:rate5m instead of a nested pile of functions.
It produces no notification and should never be used as an alert. To decide whether a piece of logic deserves recording, ask one question: is this expression referenced from more than one place, or is a single evaluation genuinely expensive — a sum across many series, a multi-layer quantile calculation, a wide-window rate? If yes, record it. If it is used once and is cheap, write it inline in the alert expression; an extra recording layer only adds a second place to keep in sync.
Name recordings with the aggregation level and window built in, in the form "level:metric:operation-window", for example job:http_requests:rate5m for a per-job request rate. With that information in the name, a reader of the alert definition knows the granularity and the window without opening the recording file. For the basic wiring, see Prometheus and Grafana Basics.
1.2 Alerting rules only evaluate and emit
An alerting rule has exactly three jobs: decide whether a condition holds, maintain the pending and firing states, and hand labelled alerts to Alertmanager. It should not carry heavy computation, and it should not reshape data — that belongs to recording rules or to the collection side.
The boundary matters because the expression's output decides whether a human gets woken up. When an alert expression nests five levels of aggregation, a problem leaves you unable to tell whether the threshold is wrong or whether one intermediate aggregation erased a dimension that mattered. Split into "a recorded input plus one comparison", the possible causes collapse from five to two, and the reasoning cost for an on-call engineer at 3 a.m. drops by an order of magnitude.
By the same argument, business logic does not belong in an alert expression. Conditions like "exclude test accounts" or "skip the whitelist during a sale" should be attached as labels on the collection side, or filtered inside a recording rule. Pushed into the alert expression, they make it stranger with every edit, and none of those edits has any test coverage.
1.3 The recommended layering: heavy work in recordings, judgement in alerts
The layering that works in practice: the collection and export side adds labels, drops volume, and discards useless series; recording rules handle every aggregation and ratio; alerting rules contain only "recorded metric + comparison + for"; Alertmanager handles grouping, inhibition, and routing. Four layers, each with one job, each testable and revertible on its own.
An alert expression written this way is short enough to read at a glance: one recorded ratio metric, compared against 0.05, with a for and two labels. Short expressions buy testability as well as readability — a promtool unit test asserts on the result computed from synthetic series, and the shorter the expression, the easier it is to write the case correctly and the less likely the test itself is wrong.
The price is a dependency order between rule groups: recording rules must be evaluated before the alerts that consume them, and a recorded metric carries its own lag. That lag stacks on top of for and becomes part of the detection time. Miss the stacking and you get "every rule is written correctly, yet the incident still paged six minutes late".
2. The for Clause: A State Machine from Pending to Firing
An alert rule is not an instantaneous check but a state machine. When a condition holds in an evaluation cycle, the alert enters pending; only after it has held continuously for the duration given by for does it become firing and actually notify anyone. Once that is clear, choosing for stops being parameter tuning and becomes a decision about where the line sits between fast detection and low false-positive rate.
2.1 No for means treating one jitter as an outage
Without for, any instantaneous sampling anomaly becomes a notification: a GC pause spikes latency for one cycle, a retransmission makes up briefly zero, a scheduled job creates a momentary concurrency peak, a container restart refuses connections for a few seconds. All of these happen several times a day in a real system, and the overwhelming majority disappear by the next scrape.
The damage from such false positives is not their count but the reflex they train. After a few "it fired and then fixed itself" pages, the on-call engineer starts to wait before acting — and a genuine incident lands inside that wait. What false positives really consume is not handling time but the reflex of acting the moment the phone rings.
The reverse is not true either: a longer for is not automatically safer. Thirty minutes means a real outage is discovered at least thirty minutes late. Those thirty minutes of user impact are certain, and what they buy is a few fewer false positives — a trade that rarely pays, especially when the error budget is already tight.
2.2 for must be much larger than the scrape and evaluation intervals
The value of for is constrained by two lower-level cycles: the scrape interval decides how often a metric changes, and the evaluation interval decides how often the rule judges. When for sits in the same order of magnitude as those cycles, the state machine skews — the metric has not refreshed, yet the rule has already evaluated twice, both times reading the same stale value, and both count toward "continuously true".
A concrete shape: scrape 15s, evaluate 15s, for: 30s. A genuine blip only needs to be captured by one scrape to be read by two evaluation cycles, so for effectively degrades to "a single sample point" and is nearly indistinguishable from having no for at all. A workable ratio is to let for cover at least four to five scrape points; only then does "continuously true" mean sustained over a period rather than one instantaneous value read repeatedly.
There is a third cycle that is easy to forget: the metric's own window width. Every result of rate(x[5m]) is really an average over the past five minutes — inherently smooth and inherently lagging. A spike lasting forty seconds is diluted into a small bump inside a five-minute window and may never reach the threshold. The problem there is not for but the window, which has already erased the signal; no amount of for tuning will recover it.
2.3 Set the value by how reversible the action is, not by metric type
The common rule of thumb assigns for by metric type: 2 to 5 minutes for node liveness, 5 to 10 for error rates, 10 to 15 for resource exhaustion. That table is usable, but it cannot answer the real question of why one service should use 3 minutes for its error rate while another should use 12.
A better criterion is action reversibility. Where a rollback takes seconds, or degradation and scaling are automatic, report earlier with a shorter for: the cost of a false positive is opening a dashboard for a glance, while the cost of a miss is ten minutes of user-facing failure. Irreversible situations — corrupted writes, duplicate message consumption, accounting drift — deserve a shorter window or even an instantaneous condition, because the cost of late detection dwarfs a false positive. What those need to defend against is jitter only, and jitter is expressed more precisely as "N consecutive samples" than as a long for.
One corollary: the same rule can use different for values on different services, because the two services recover differently. Enforcing one global for is convenient and guaranteed to be wrong on your most important service.
3. Ratio Rules: Denominators, Low Traffic, and Multiple Windows
The most valuable alert class is the ratio: error rate, success rate, timeout share. Ratios look like the easiest thing to write — one division and you have a number — and are in fact the easiest place to write something that looks right and concludes wrong.
3.1 How a plain ratio breaks under low traffic
sum(rate(errors[5m])) / sum(rate(total[5m])) is the canonical form. It behaves well with healthy traffic and becomes discrete with little traffic: with twenty requests in five minutes, one failure is 5% and two are 10%. As long as the threshold sits near 5%, the rule flickers continuously through the state of "one request failed occasionally" while the system is entirely healthy.
This is not a threshold calibration problem; a ratio simply has no stable meaning at that sample size. Low-traffic scenarios have two exits: widen the window to buy samples, at the cost of slower detection, or switch the object to an absolute count — "more than ten 5xx in five minutes" is more stable there, because its variance is independent of request volume.
Deciding between them takes only two numbers: the normal request rate, and how much a single failure shifts the ratio inside the default window. If one failure pushes the ratio past the threshold, the ratio form is wrong for that service, no matter what threshold you pick.
3.2 Zero denominators and "too little traffic"
Low traffic has an extreme form: a zero denominator. With no requests arriving, the ratio does not evaluate to 0 — it evaluates to nothing. sum(rate(x[5m])) returns empty when there are no series, and the division follows it into emptiness. The alerting consequence is that the rule goes quiet rather than reporting zero.
That emptiness is dangerous because it looks exactly like "all good". When the entry point is cut off, when every instance is drained, when DNS resolution fails, when an expired certificate breaks the TLS handshake, request volume drops to zero and the error-rate alert falls silent — at precisely the moment it should be loudest. Every ratio alert therefore needs a companion rule: when request volume drops below a floor, a separate "no traffic" alert takes over instead of letting the ratio go quiet. This is the concrete landing point of the "traffic is the denominator of every other signal" argument in What to Monitor.
Denominator protection has a second layer: the numerator must be dimensionally aligned with the denominator first. If the numerator filters on status=~"5.." while the denominator aggregates over a different label set, the two series sets can disagree, and the ratio either exceeds 1 or silently undercounts traffic. Checking both sides with a per-dimension count before the rule ships is a cheap step — and one of the hardest to add afterwards.
3.3 Multi-window burn rates: one window forces a choice
Any single window with a single threshold forces a choice between two failures. A short window with a low threshold produces many false positives and still misses slow degradation, because a system degrading a little each day never leaves the threshold at any single moment. A long window with a high threshold detects late, and users absorb two hours of impact before the page arrives.
Multi-window, multi-burn-rate alerting redefines "abnormal" as "the error budget is being consumed fast" and requires a long and a short window to agree: the long window establishes that this is sustained degradation rather than a momentary dip, and the short window confirms the degradation is still ongoing rather than already recovered. Firing only when both hold suppresses both failure modes at once.
The prerequisite is an SLI and an error budget, meaning a success-rate definition with a trustworthy denominator, plus histogram or counter data to support window arithmetic. The cost is interpretive: someone reading "14.4x burn rate" needs a translation. That is why it belongs on a few critical journeys rather than everywhere. Window and tier configurations are covered in SLO and Error Budget Practice.
4. High Cardinality: Where Rules Explode
How many series a rule emits is decided by its aggregation dimensions, a fact almost nobody considers while writing it. The resulting problem is not "a bit slow" — it is the rule and the alerting path failing together.
4.1 The cost of by (user_id)
sum by (service) emits as many series as there are services; sum by (user_id) emits as many as there are users. The first is dozens, the second can be hundreds of thousands. Same expression shape, three orders of magnitude apart in cost.
The cost has three layers. First, computation: every evaluation cycle must evaluate, compare, and materialise alert instances for that many outputs; one rule can consume a large share of memory and CPU, and every other rule on that Prometheus slows down with it. Second, the alerting path: if the condition holds, Alertmanager receives hundreds of thousands of alert instances, deduplication, grouping, and routing all collapse, and nearly all of them describe the same event. Third, remediation: once such a rule has shipped and accumulated history, changing the dimension means rebuilding the whole series space.
One criterion decides whether a dimension may appear in by: does its value set have a firm upper bound that is small enough to enumerate? Service, environment, region, method, status code, and instances within a controlled fleet qualify; user ID, request ID, session ID, phone number, and URLs with path parameters do not.
4.2 Dynamic values belong in annotations, never in labels
The sibling mistake is putting dynamic values into alertname or labels. alertname participates in grouping and deduplication; once an instance IP is inside it, every machine becomes a "different alert", grouping does nothing, and inhibition rules stop matching.
The correct split: labels holds only the static information that needs to be addressed — severity, team, service, environment — values with small, stable domains that Alertmanager's routing tree can match exactly. annotations holds what a human reads — the current value, the affected instance list, a dashboard link, a runbook URL. Reverse that split and you get alerts that look richly detailed while routing is in chaos.
If the notification genuinely needs an instance list, build it in annotations from the series labels with a template, or simply link the receiver to the dashboard for detail. A notification body is not a data warehouse; the more it carries, the harder it is for someone to decide within ten seconds whether to act. For the organisational side of severity tiers, see the Monitoring and Alerting Guide.
5. Turning Rules into Regression Tests with promtool
This is the least-known part of the whole topic: Prometheus ships rule unit testing. It turns an alert rule from "a text shipped on intuition" into "a program with expected behaviour".
5.1 What a unit test feeds in and asserts
A promtool rule test feeds synthetic time series to a set of rules and asserts, at a given evaluation time and for a given alert name, what state that alert should be in — pending, firing, or absent — and which labels it should carry. The value is a repeatable verification path: previously the only way to validate a rule was to ship it and watch, one observation at a time; now the same check runs locally and in CI as often as you like.
Be clear about the ceiling. A unit test can only prove "given this series, the rule fires or stays quiet as expected"; it cannot prove the threshold is correct. Whether the threshold is right still depends on real user impact, and no tool replaces that judgement. The split is clean: unit tests guard against editing mistakes — someone changed for, moved a label, flipped the comparison, swapped an aggregation — which would make the rule silent when it must fire; threshold review guards against choosing wrong in the first place.
5.2 One runnable test and three cases you must have
A test file has three parts: the rule files under test, the evaluation interval, and a set of timelines with assertions. The example below asserts on a 5xx ratio alert — the values notation 0+9x12 means "start at 0, add 9 per sample, repeat 12 times":
rule_files:
- rules/api.yaml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'http_requests_total{job="api",status="500"}'
values: '0+9x12'
- series: 'http_requests_total{job="api",status="200"}'
values: '0+91x12'
alert_rule_test:
- eval_time: 3m
alertname: HighErrorRate
exp_alerts: []
- eval_time: 9m
alertname: HighErrorRate
exp_alerts:
- exp_labels:
severity: page
job: api
The same series is asserted to produce no alert at 3 minutes and to be firing at 9 minutes; the only difference between the two is for: 5m. That bracket is the entire semantics of for — it goes pending at minute 1 and only turns firing at minute 6. Any accidental edit to for turns one of the two assertions red.
Three case types worth pinning in CI: a slow climb that approaches the threshold and must eventually fire, which catches a for set so long that real degradation is missed; a spike that breaches the threshold for one sample and recovers, which must not fire and catches someone deleting for; and an empty-data case where the denominator stays at zero throughout, asserting that no 0-valued ratio alert is produced, which confirms the no-traffic rule really does take over.
5.3 When a unit test is mandatory
Not every rule deserves a test. The criterion is how expensive it is to get that rule wrong. Paging alerts, burn-rate rules tied to an SLO, and any rule whose labels inhibition and routing depend on must have one — their errors surface directly as misses or false pages, usually at the worst possible moment.
Display-only rules that never reach an alert channel can skip it. A rule library should keep a ratio: a small number of critical rules carry tests, and everything else is simple enough not to need them. Conversely, when a rule becomes so complex that you dare not touch it without a test, the better move is usually not to write the test but to split the rule into a recording plus a simple comparison. Moving complexity out of the alerting side beats armouring it.
6. Organising Rules: Files, Names, and Labels
How rule files are laid out decides the blast radius of every change. Below twenty rules it makes no visible difference; past a hundred it becomes the main cost.
6.1 One file per service, names with prefixes
Organise by service plus purpose: api-alerts.yaml, api-recordings.yaml, db-alerts.yaml. A change then touches a small diff, review sees exactly which rules moved, and a rollback is a single file.
The anti-pattern is one enormous alerts.yaml. The problem is not its size but ownership: every team appends to the same file, and nobody can say which rule belongs to whom, whether it can be deleted, or why it was last changed. Once rules live in their service's own files, "who maintains this rule" is answered by the directory structure instead of by a separate inventory nobody updates.
Prefix alert names with the service or subsystem, for example ApiHighErrorRate. That buys three things: scope is obvious inside Alertmanager, the alert cannot be mistaken for another team's problem in a shared channel, and it is searchable in incident records. The name is also the default grouping key, so alerts sharing a prefix group together naturally.
6.2 severity and team: static addressing information only
severity and team in labels are not display fields. They decide which receiver gets the alert, which channel is used at which hour, and how long an unacknowledged alert waits before escalating. Both must come from a fixed, small enumeration rather than free text — free text forces the routing tree to accumulate special cases until nobody dares to edit it.
team is chronically undervalued. An alert with no owning team can only go to a shared channel, and response time there depends on who happens to be looking. Labelling every rule with a team writes "who must handle this" at the rule level instead of leaving it for the recipient to infer.
Both fields carry one implicit requirement: stability. Changing severity from ticket to page means the alert now wakes people up, and that should be an explicit review rather than a casual one-line edit. For the broader discipline of noise control, see Alert Fatigue and On-call Practice.
7. Self-Check Table and Rollout Order
7.1 A rule self-check table
Run these seven rows every time a rule is added or changed. The table is not exhaustive; its job is to gather the judgements scattered through this article into a set of questions that check each other.
| Check | Criterion | What to do if it fails |
|---|---|---|
Has a for |
Duration covers at least four to five scrape points | Add for, set it by reversibility first |
Has a severity |
Value comes from a fixed enumeration and matches a channel | Add the label and wire the route |
| Has a runbook | annotations contains an actionable path |
Keep it out of the alert path until it does |
| Denominator protected | Low traffic and zero traffic each have a fallback | Add a no-traffic alert |
| No high-cardinality grouping | Every by dimension has a bounded value set |
Move high-cardinality dimensions out of labels |
| Has a unit test | Critical rules have both firing and non-firing cases | Add cases, or split into a recording rule |
| Computation moved down | Complex expressions live in recording rules | Split into a recording plus a comparison |
7.2 Rollout order
Week one, two low-risk moves: split existing rules into per-service files, and add severity and team to every rule. No expression changes, yet for the first time you can see how many rules you have and who owns each — the foundation for everything after.
Week two, fix the noisiest ones: add missing for clauses, add denominator protection to ratio rules, remove high-cardinality groupings. Decide which are noisiest from repeat counts in the alert history, not from memory; the one you remember is usually just the one that last woke you up.
Week three, build tests: write cases for the three most critical paging alerts, wire promtool test rules into CI, and require it for every subsequent change. The point is not coverage but making rule edits safe again.
The first quarter is for convergence: delete or downgrade rules that never drove an action, push complex expressions down into recordings, and align critical-path rules with your SLOs. A rule library's maturity is not measured in count but in two facts — every rule has someone who can explain why it exists, and the last time it fired it made the right call. For alerting on logs, see Log Aggregation and LogQL; for turning each miss and false page into a rule change, see the Incident Postmortem Template.
Source: Prometheus documentation (alerting rules, recording rules, and promtool unit testing). Compiled and interpreted by 16IDC.
Integration & Code Examples
Example 1: What a well-formed alert rule looks like
# rules/api.rules.yml
groups:
- name: api-availability
interval: 30s
rules:
# Record the ratio first instead of aggregating over high-cardinality labels
- record: job:http_requests_error_ratio5m
expr: |
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total[5m]))
- alert: ApiHighErrorRate
expr: job:http_requests_error_ratio5m > 0.05
for: 10m
labels:
severity: page
team: platform
annotations:
summary: "{{ $labels.job }} 5xx ratio above 5%"
description: "Current value {{ $value | humanizePercentage }} for 10 minutes."
runbook_url: "https://wiki.example.com/runbook/api-5xx"
for suppresses flapping, labels drive routing and deduplication, and annotations must link a runbook — without all three a rule is just a query.
Example 2: Turn rules into regression tests
# Syntax and semantic checks, run in CI every time
promtool check rules rules/api.rules.yml
# Behavioural regression: feed a series and assert when it fires and when it must not
cat > rules/api.rules.test.yml <<'YAML'
rule_files:
- api.rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'http_requests_total{job="api",status="500"}'
values: '0+5x12'
- series: 'http_requests_total{job="api",status="200"}'
values: '0+95x12'
alert_rule_test:
- eval_time: 5m
alertname: ApiHighErrorRate
exp_alerts: [] # still inside `for`, must not fire
- eval_time: 15m
alertname: ApiHighErrorRate
exp_alerts:
- exp_labels:
severity: page
team: platform
job: api
YAML
promtool test rules rules/api.rules.test.yml
With this layer, changing a threshold or splitting an expression no longer relies on "watching it for a night" — firing and not firing both become deterministic assertions.
Limitations
- By the same argument, business logic does not belong in an alert expression.
- Thirty minutes means a real outage is discovered at least thirty minutes late.
- That table is usable, but it cannot answer the real question of why one service should use 3 minutes for its error rate while another should use 12.
- With no requests arriving, the ratio does not evaluate to 0 — it evaluates to nothing.
- Denominator protection has a second layer: the numerator must be dimensionally aligned with the denominator first.
FAQ
How long should for be compared with the scrape interval?
Set the scrape and evaluation intervals first, then pick for. It should span four or five scrape points; with 15-second scrapes and evaluations a 30-second for covers exactly one sample, which is barely different from having none. A rate over a 5m window already smooths a 40-second spike away, and no for value brings it back.
Why did the alert never fire during the outage?
Verify first whether the rule ever reached firing. A promtool test on the same series asserts no alert at 3 minutes and a firing alert at 9 minutes; if production stays silent at that moment, check whether for was lengthened or by() dropped the dimension that mattered. A zero denominator also leaves a ratio silent.
Which parts belong to Alertmanager instead of rules?
Rules judge, Alertmanager delivers. A rule emits alert instances carrying two static keys, severity and team, while grouping, inhibition, silences and routing all live in Alertmanager. Encoding receivers or on-call rosters into rule labels pushes that state into 100 rule files and leaves no single place to audit routing.
Which rules shouldn't enter the paging channel?
Display-only rules shouldn't. Ones that merely feed a dashboard and never trigger an action dilute the signal for everything else in the library. Page-worthy candidates are emergency alerts, burn-rate rules tied to an SLO, and the handful whose labels an inhibition rule matches; in a library of 100 rules only a dozen earn the channel.
Related Providers
- Prometheus: align the version and rule file format when promtool must validate syntax and unit tests in CI.
- Grafana: annotate rule firings beside metric curves when alerts and the underlying series have to be read on one screen.
- Datadog: weigh rule migration effort when hosted alert routing replaces a self-run Prometheus and Alertmanager pair.
Community & Resources
-
Monitoring & Alerting: other coverage in this category.
Official docs and communities -
Prometheus alerting rules — Rule syntax,
for,labelsand template variables. -
Prometheus recording rules — The official way to push complexity into recorded metrics.
-
promtool command line — Full options for
check rulesandtest rules. -
Prometheus on GitHub — Source and changelog — the source of truth for rule behaviour changes.
Learning resources and tools
- Awesome Prometheus Alerts — A curated collection of ready-made alert expressions by component.
- Awesome Prometheus Alerts repo — A forkable rule catalogue that works well as a baseline.
- Prometheus first steps — The minimal loop from scraping to querying to alerting.
- Grafana documentation — Visualising alert outcomes and organising dashboards.
Original source: Prometheus Docs ↗