Course contents · Lesson 7 of 21

Prometheus Recording and Alerting Rules, Hands-On

Prometheus and Alertmanager · Lesson 7 of 21 · 11 min Hands-on

Your PromQL from the last lesson can tell you how slow shop-demo is, but only while someone watches the Graph tab. Nobody watches it at 3 a.m., and a dashboard that recomputes the same p95 on every refresh repeats heavy work. This lesson shows how Prometheus alerting rules watch a condition for you, how recording rules store a heavy query's answer, and how to load both into the lab.

Rules: standing orders on a timer

A rule is a PromQL expression that Prometheus runs by itself, on a schedule. As What Is Prometheus? showed, rules are built into the Prometheus server. They live in rule files: YAML files that prometheus.yml lists under rule_files.

Inside a file, rules sit in named groups. Every evaluation_interval, 15 seconds in the lab and 1 minute by default, Prometheus runs each group's rules one after another at the same timestamp; each run is an evaluation. There are two kinds of rule, recording and alerting.

Recording rules: compute once, read many times

A recording rule runs a query at every evaluation and stores the answer as a new time series, under a name you choose. Dashboards, queries and alerts can then read that small stored series instead of recomputing the original. The lab's prometheus/rules.yml starts with this group, shown without its comments:

groups:
  - name: shop-demo-recording
    rules:
      - record: job:http_requests:rate5m
        expr: sum by (job) (rate(http_requests_total[5m]))
      - record: job_le:http_request_duration_seconds_bucket:rate5m
        expr: sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))

record is the new series' name and expr the query. The names follow the level:metric:operations convention from the Prometheus recording rules guide: the labels kept, the metric name (minus _total once rate() is applied), then what was done. Colons are reserved for recording rules, so a colon tells readers the series was computed, not scraped.

The second rule does the heavy half of the p95 query from the last lesson: the rate of every bucket series, summed by job and le. A dashboard then asks for histogram_quantile(0.95, job_le:http_request_duration_seconds_bucket:rate5m), which reads 11 stored series instead of about 66 raw ones.

Before and after, with approximate lab sizes. Before: a dashboard panel runs histogram_quantile(0.95, sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))) on every refresh, reading about 66 series times 20 samples, 1,320 samples per answer, repeated for every panel and viewer. After: a recording rule runs every 15 seconds and stores 11 series, one per le bucket; the panel runs histogram_quantile(0.95, job_le:http_request_duration_seconds_bucket:rate5m) and reads 11 samples. A note says it is the same p95, at most 15 seconds older, and the new series starts when the rule does.
The rule does the expensive part once per evaluation, so every viewer reads a handful of stored samples instead.

On a real system, the left side can span thousands of series. Two limits apply: a recorded series has no history before the rule's first evaluation, and it can be up to one evaluation interval older than the raw data.

Alerting rules: expr, for, labels and annotations

An alerting rule turns a condition into alerts. Its expr returns series only while something is wrong, and each series it returns becomes one alert. Here is the lab's second group:

  - name: shop-demo-alerts
    rules:
      - alert: ShopDemoDown
        expr: up{job="shop-demo"} == 0
        for: 1m
        labels:
          severity: page
        annotations:
          summary: "shop-demo is down"
          description: "Prometheus could not scrape {{ $labels.instance }} for more than 1 minute."

As lesson 3 showed, up is 0 when the last scrape failed. == 0 filters: the expression returns the series while scrapes fail and nothing while the app answers. alert names the alert, and Prometheus adds that name as the alertname label.

for is how long the condition must keep holding before the alert fires, so one failed scrape does not wake anyone. labels are added to the alert's labels, which identify it; Alertmanager will route on them, for example severity="page". annotations are text for the person who receives it, such as a summary or a runbook link. {{ $labels.instance }} is a template, filled in with the alert's own label value.

Each alert moves through states. While the expression returns nothing, the rule is inactive. The first evaluation that finds a series makes the alert pending and starts the for timer. If the condition still holds at an evaluation 1 minute later, the alert is firing. If it clears first, the pending alert is dropped, and the timer starts again from zero next time.

State diagram for ShopDemoDown with for 1m, checked every 15 seconds: inactive, condition false; up == 0 leads to pending, true with the timer running; after 1m passed, firing, true for 1m or more; when up is 1, resolved, false again, and back to inactive. A dashed arrow from pending back to inactive: up is 1 again within 1m, no alert. Below, an approximate timeline after docker stop shop-demo: stop at 0 s, a scrape fails and up is 0 at about 15 s, pending at the first evaluation at about 30 s, and firing 60 s after pending, at about 90 s. Pending alerts are never sent; firing ones go to Alertmanager.
The for timer starts at pending, not when the app stopped, so firing comes later than for alone suggests.

When a firing alert's condition clears, the alert is resolved and the rule is inactive again. A rule without for skips pending and fires at the first evaluation that finds a series.

Load the rules into the lab

The lab in course-labs/open-source-observability-stack/02-prometheus-alertmanager ships with prometheus/rules.yml, but Prometheus ignores it until prometheus.yml lists it. Loading it uses the check-and-reload steps from lesson 4.

Step 1: check the rule file

promtool's check rules command parses a rule file, checks every expression and template, and counts the rules, without touching the running server:

docker compose exec prometheus promtool check rules /etc/prometheus/rules.yml

A valid file prints the two lines below. A mistake, such as expression: instead of expr: or a wrong indent, prints FAILED: and the problem instead.

Checking /etc/prometheus/rules.yml
 SUCCESS: 3 rules found

Step 2: list the file, check and reload

Open prometheus/prometheus.yml and add these two lines between the global block and scrape_configs, starting at the left margin. A relative path is read from the folder that holds prometheus.yml:

rule_files:
  - rules.yml

Run promtool check config as in lesson 4. It now prints SUCCESS: 1 rule files found before its usual line, then checks rules.yml too. Reload with curl -X POST localhost:9090/-/reload, which prints nothing on success; if it answers failed to reload config:, Prometheus keeps its old configuration and rules.

Step 3: see the rules run

Within 15 seconds, Status, then Rule health (http://localhost:9090/rules) lists both groups, each rule with the health ok. On the Query page, job:http_requests:rate5m returns one series, job:http_requests:rate5m{job="shop-demo"}, near 5 requests per second: the long query's answer, already computed.

Watch the alert, and what happens next

The Alerts page (http://localhost:9090/alerts) lists alerting rules by group. A rule with a pending or firing alert shows a badge such as pending (1); click the rule to see each alert's labels and State. Prometheus also stores every pending or firing alert as a series named ALERTS, with an alertstate label, so you can query alert history.

Firing is where Prometheus's own job ends. It sends firing alerts to the Alertmanagers listed under alerting in prometheus.yml, resends them about once a minute while they fire, and tells Alertmanager when they resolve. The flowchart shows one full round.

Flowchart. rules.yml, listed in rule_files, leads to: run the expr every 15 seconds, the evaluation_interval. A record rule goes to: store a series, the rule's result. An alert rule goes to the question: any series returned? No: inactive, nothing to send. Yes: the question true for 1m or more? No: pending, timer keeps running. Yes: firing, the alert is active, which goes to Alertmanager, connected in lesson 8. Inactive and pending loop back to the run step: next round, 15 seconds later. A note says firing is rechecked too, and false again means resolved.
Only the firing branch leaves Prometheus: pending alerts wait inside it, and are never sent.

Alertmanager already runs in the lab, but prometheus.yml has no alerting block yet, so ShopDemoDown stays inside Prometheus. The next lesson adds it; Alertmanager then decides who is told, how often, and what to hold back.

Check yourself

One scrape of shop-demo fails, and the next one works. Does ShopDemoDown, with for: 1m, fire?

No. The evaluation after the failed scrape makes the alert pending, but once a scrape works the expression returns nothing, so the pending alert is dropped long before 1 minute passes. Ignoring blips like this is what for is for.

A teammate deletes the for line to be told sooner. What changes, and what does it cost?

The alert skips pending and fires at the first evaluation that sees up at 0, about a minute sooner. The cost is a page for every single failed scrape, such as a short network blip, which teaches people to ignore pages.

You add the job_le:…:rate5m recording rule today. Why does a 7-day graph of it show only today, while the long query shows 7 days?

A recording rule writes results only from its first evaluation onward; it does not fill in the past. The long query computes from the raw samples, which go back as far as Prometheus has kept them.