Sub topic 15
Writing alerting rules
This chapter assumes you have a working Prometheus server that scrapes node_exporter, and that you can write basic PromQL with selectors, rate, and aggregation. It also assumes you have seen the Alertmanager configuration file, though routing is covered in the next chapter. Here you write the rules that decide when an alert exists.
What an alerting rule does
An alerting rule is a PromQL expression that Prometheus evaluates on a schedule. The schedule is evaluation_interval in the global block, 15 seconds in our configuration. If the expression returns at least one series, each returned series becomes an active alert. Prometheus then sends those alerts to Alertmanager, which handles grouping, deduplication, and notification.
Prometheus does not send emails or chat messages. It only decides that a condition holds. Keeping that split in mind makes later debugging easier. If a rule never fires, the problem is in Prometheus. If it fires but nobody is notified, the problem is in Alertmanager or the receiver.
Rules live in files listed under rule_files in prometheus.yml. Our configuration uses rules/*.yml, resolved relative to the location of prometheus.yml.
Anatomy of a rule
Here is the rule file for this tutorial, saved as rules/node-alerts.yml.
groups:
- name: node-alerts
rules:
- alert: InstanceDown
expr: up{job="node"} == 0
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.instance }} is down"
- alert: DiskSpaceLow
expr: node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay"} < 0.10
for: 10m
labels:
severity: warning
annotations:
summary: "Less than 10% disk space free on {{ $labels.instance }} ({{ $labels.mountpoint }})"Each part has a job:
- groups: rules in a group are evaluated in order, at the same interval. Put related rules in one group.
- alert: the alert name. It becomes the
alertnamelabel, which Alertmanager uses for grouping. - expr: the condition. Any series it returns is an active alert, so write it as a filter. A comparison such as
== 0or< 0.10drops the series that do not match. - for: how long the condition must stay true before the alert fires.
- labels: extra labels added to the alert. Alertmanager routes on these, so
severityis the usual choice. - annotations: human-readable text such as a summary or a link to a runbook. Annotations do not affect routing.
Alert states
Without for, an alert fires on the first evaluation where the expression returns data. With for, the alert passes through a pending state first.
Pending alerts are visible on the Alerts page of the Prometheus web interface but are not sent to Alertmanager. Only firing alerts are sent. When a firing alert returns to inactive, Prometheus tells Alertmanager that it is resolved.
Choosing `for`
The for duration filters out brief spikes. A short value reacts quickly but produces false alarms. A long value is quiet but slow to report real problems. Some reasonable starting points:
| Condition | Typical `for` | Reason |
|---|---|---|
| Target down (`up == 0`) | 1m to 5m | A single failed scrape is common, for example during a restart. |
| Disk nearly full | 10m to 30m | Disks fill slowly, and a short spike from a temporary file is not worth a page. |
| High CPU | 10m to 15m | CPU is often high for short periods in normal operation. |
Because for is measured in evaluation cycles, the effective delay is rounded to a multiple of evaluation_interval. If the scrape fails and then recovers during the pending period, the timer resets.
Templating labels and values
Annotations and labels can use Go templates. Two variables matter most:
$labelsholds the labels of the series that triggered the alert, for example{{ $labels.instance }}.$valueholds the number the expression returned.
Because DiskSpaceLow compares a ratio against 0.10, $value is the remaining fraction. You can format it for readers:
annotations:
summary: "{{ $labels.instance }} has {{ $value | humanizePercentage }} free on {{ $labels.mountpoint }}"Template errors do not stop the rule from being loaded. They show up only when the alert is evaluated, so check the Alerts page after you add a template.
A trend-based alert
A fixed threshold warns you when the disk is already nearly full. A trend alert warns earlier. predict_linear fits a straight line to the samples in a range and projects it forward.
groups:
- name: node-alerts-predictive
rules:
- alert: DiskWillFillIn24Hours
expr: predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}[6h], 24 * 3600) < 0
for: 30m
labels:
severity: warning
annotations:
summary: "{{ $labels.mountpoint }} on {{ $labels.instance }} is predicted to fill within 24 hours"The range [6h] is the history used for the fit, and 24 * 3600 is how many seconds ahead to predict. Short ranges make the prediction jumpy, so the for of 30 minutes matters here.
Failure modes
The target vanishes instead of going down. up == 0 only matches a series that exists. If you remove a target from prometheus.yml, or service discovery stops listing it, its up series disappears and InstanceDown never fires. To catch a whole job going missing, add a rule using absent:
- alert: NodeJobMissing
expr: absent(up{job="node"})
for: 5m
labels:
severity: critical
annotations:
summary: "No targets are reporting for job node"Flapping. An alert near its threshold can switch between firing and resolved repeatedly, and each switch can trigger a notification. Raise for, or use two thresholds. Recent Prometheus versions also support keep_firing_for, which holds an alert in the firing state for a set time after the condition clears.
Too many labels. Aggregating with by or without removes labels. Labels such as mountpoint appear in your annotation only if the expression keeps them. If {{ $labels.mountpoint }} renders as an empty string, the expression dropped that label.
Alerting on causes instead of symptoms. High CPU may be harmless. Pages should go to conditions that need action, such as a down host or a disk that will fill. Send lower-urgency conditions to a ticket queue or a dashboard instead.
Validating and loading rules
Check a rule file before Prometheus sees it:
promtool check rules rules/node-alerts.ymlpromtool reports YAML mistakes and PromQL syntax errors. It does not tell you whether a metric exists. To load changes without a restart, send SIGHUP to the Prometheus process, or call the reload endpoint if you started Prometheus with --web.enable-lifecycle:
sudo systemctl reload prometheusThis works only if your unit file defines ExecReload to send SIGHUP. If it does not, restart the service instead. Then open the Alerts page, usually http://localhost:9090/alerts, and confirm each rule shows as inactive, pending, or firing. A rule that is missing from the page was not loaded, so check rule_files and the Prometheus log.
To test a rule, run its expr alone in the query page first. Remove the comparison and the result should show the value you expect. Then add the comparison back and confirm the output matches the hosts you would expect to alert.
Exercise
Your team removed server2.example.com:9100 from the node job last week, and now InstanceDown never alerts for it. You also want a warning if server1 is about to run out of disk within 12 hours. What do you need, and why did the original rule stay silent?
Show answer
up{job="node"} == 0 only matches series that exist. Once the target left the scrape config its up series disappeared, so there was nothing for the comparison to return. This is correct behaviour, but it means a removed or undiscovered target is invisible to that rule. Use absent(up{job="node", instance="server2.example.com:9100"}) for a specific host, or absent(up{job="node"}) for the whole job. For the disk warning, add a rule such as predict_linear(node_filesystem_avail_bytes{instance="server1.example.com:9100", fstype!~"tmpfs|overlay"}[6h], 12 * 3600) < 0 with for: 30m and a severity: warning label.