# Alerting with Alertmanager

Write alert rules in Prometheus, route them to the right people with Alertmanager, group and silence the noise, and follow one real alert from a dead server to a page and back.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 4. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/04-alerting-with-alertmanager

## What you will learn

- Write an alert rule with an expression, a for duration, labels and annotations
- Explain the inactive, pending and firing states and what for protects you from
- Route alerts by severity with an Alertmanager routing tree, and test the routes with amtool
- Use grouping, inhibition and silences to cut noise
- Tell a useful alert from a noisy one, and write alerts on symptoms and predictions

Dashboards only help when someone is looking. Alerting tells a person when something users care
about is broken, and stays quiet otherwise. **Prometheus** decides _whether_ something is wrong;
**Alertmanager** decides _who_ hears about it, how and how often. In this lesson you'll write rules,
build a routing tree, and follow one real alert from a dead server to a page and back.

> **Figure.** Left, in Prometheus: the rule DiskWillFillIn4Hours with predict_linear over 1 hour and for 15 minutes moves from inactive while false, to pending while true but not yet 15 minutes, to firing after 15 minutes. Right, in Alertmanager: 1 group by alertname and job so 40 disks become 1 message, 2 inhibit so TargetDown mutes that host's other alerts, 3 silence for planned work, 4 route severity page to on-call and ticket to a queue, 5 notify by webhook, Slack, email or PagerDuty, repeating every 4 hours.
>
> Prometheus never talks to Slack or a pager. It only says 'firing'. Alertmanager handles people.

## Alert rules

An **alert rule** is a PromQL expression that returns series when something is wrong. Each
returned series becomes one alert. Rules live in a rules file next to your recording rules:

```yaml
# rules.yml
groups:
  - name: node
    rules:
      - alert: TargetDown
        expr: up == 0 # any target Prometheus can't scrape
        for: 1m # must stay true this long before it fires
        labels:
          severity: page # used by Alertmanager to route it
        annotations:
          summary: '{{ $labels.job }} on {{ $labels.instance }} is down'
          runbook_url: https://runbooks.example.com/target-down

      - alert: DiskWillFillIn4Hours
        expr: predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}[1h], 4 * 3600) < 0
        for: 15m
        labels:
          severity: page
        annotations:
          summary: 'Disk {{ $labels.mountpoint }} on {{ $labels.instance }} will be full within 4 hours'

      - alert: HighMemoryUse
        expr: (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) > 0.9
        for: 10m
        labels:
          severity: ticket
        annotations:
          summary: 'Memory on {{ $labels.instance }} is over 90% used'
```

Each part has one job:

- **`expr`**: the condition. Any series it returns is "wrong right now".
- **`for`**: how long it must stay true. This is your main defence against noise: a 30-second
  spike never pages anyone.
- **`labels`**: added to the alert. `severity` is the convention routing uses.
- **`annotations`**: text for the human: a summary using the alert's own labels, and a
  `runbook_url` that says what to do (you'll write runbooks in the SLOs lesson).

Point Prometheus at Alertmanager in `prometheus.yml`, and check the rules:

```yaml
# prometheus.yml (added)
alerting:
  alertmanagers:
    - static_configs:
        - targets: ['alertmanager:9093']
```

```sh
$ docker exec prometheus promtool check rules /etc/prometheus/rules.yml
Checking /etc/prometheus/rules.yml
  SUCCESS: 4 rules found
```

(The fourth rule is the recording rule from lesson 2.)

### Inactive, pending, firing

An alert rule is always in one of three states:

1. **Inactive**: the expression returns nothing. All good.
2. **Pending**: it returns something, but not for the full `for` duration yet. Nothing is sent.
3. **Firing**: it has been true for the whole `for`. Prometheus sends it to Alertmanager, and keeps
   re-sending it while it fires.

If the condition clears while pending, the alert goes back to inactive and nobody is told. That's
exactly what `for` is for.

## Follow one real alert

Here is a real run on the lab machine (times in UTC). Rule: `TargetDown`, `for: 1m`. Alertmanager
settings: `group_wait: 30s`, `group_interval: 5m`.

| Time     | What happened                                                       |
| -------- | ------------------------------------------------------------------- |
| 07:00:42 | `docker stop node-exporter`                                         |
| 07:00:49 | Next scrape fails: `up` becomes 0, alert goes **pending**           |
| 07:01:49 | Still down after 1 minute: alert **fires**                          |
| 07:02:19 | After `group_wait` (30 s), Alertmanager sends the page              |
| 07:03:24 | `docker start node-exporter`                                        |
| 07:03:34 | Next scrape succeeds: alert **resolved**                            |
| 07:07:20 | Alertmanager sends "resolved", at the group's next `group_interval` |

> **Figure.** The Prometheus Alerts page showing the rule group node from /etc/prometheus/rules.yml with Firing 1 and Inactive 2. TargetDown is marked firing, DiskWillFillIn4Hours and HighMemoryUse are inactive.
>
> Prometheus → Alerts at 07:02: TargetDown firing, the other two rules inactive.

Two things worth noticing. First, the page arrived **97 seconds** after the server died: 7 s to the
next scrape, 60 s of `for`, 30 s of `group_wait`. Every alert has this built-in delay, and you
choose it. Second, "resolved" took almost **4 minutes** to arrive after recovery, because
Alertmanager only sends updates for a group every `group_interval`. That's normal, not a bug.

The receiver was a small webhook that printed what it got. This is the real payload, shortened:

```json
POST /page {
  "receiver": "on-call",
  "status": "firing",
  "alerts": [
    {
      "status": "firing",
      "labels": {
        "alertname": "TargetDown",
        "env": "lab",
        "instance": "node-exporter:9100",
        "job": "node",
        "severity": "page"
      },
      "annotations": {
        "runbook_url": "https://runbooks.example.com/target-down",
        "summary": "node on node-exporter:9100 is down"
      },
      "startsAt": "2026-11-03T07:01:49.374Z",
      ...
    }
  ],
  "notification_reason": "first notification",
  "groupLabels": { "alertname": "TargetDown", "job": "node" },
  ...
}
```

The summary template turned into plain English (`node on node-exporter:9100 is down`), the
`severity: page` label chose the `on-call` receiver, and `groupLabels` shows how it was grouped.
Slack, PagerDuty and email receivers get the same data, formatted for them.

## Alertmanager

**Alertmanager** is a separate program (port 9093) that receives alerts from one or more
Prometheus servers and turns them into notifications. Its config has three parts: a **route** tree,
**receivers**, and **inhibit_rules**.

```yaml
# alertmanager.yml
route:
  receiver: default # anything no child route matches
  group_by: ['alertname', 'job']
  group_wait: 30s # wait this long to batch the first alerts of a new group
  group_interval: 5m # then send updates for that group at most this often
  repeat_interval: 4h # re-send a still-firing alert this often
  routes:
    - matchers: ['severity="page"']
      receiver: on-call
    - matchers: ['severity="ticket"']
      receiver: team-tickets

receivers:
  - name: default
  - name: on-call
    webhook_configs:
      - url: http://webhook-sink:8080/page
  - name: team-tickets
    webhook_configs:
      - url: http://webhook-sink:8080/ticket

inhibit_rules:
  - source_matchers: ['alertname="TargetDown"']
    target_matchers: ['severity="ticket"']
    equal: ['instance']
```

In real life `on-call` would use `pagerduty_configs` or `opsgenie_configs`, and `team-tickets`
`slack_configs` or `email_configs`. The structure stays the same.

`amtool` ships in the Alertmanager image. Use it to check the file before you reload:

```sh
$ docker exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml
Checking '/etc/alertmanager/alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 1 inhibit rules
 - 3 receivers
 - 0 templates
```

## Routing, grouping and silences

### The routing tree

Alerts enter at the top route and walk down. The first child whose `matchers` fit the alert's
labels handles it; if none match, the parent's receiver does. Print the tree, then test where a
given set of labels would go:

```sh
$ amtool config routes --config.file=/etc/alertmanager/alertmanager.yml
Routing tree:
.
└── default-route  receiver: default
    ├── {severity="page"}  receiver: on-call
    └── {severity="ticket"}  receiver: team-tickets

$ amtool config routes test --config.file=/etc/alertmanager/alertmanager.yml severity=page alertname=TargetDown
on-call
$ amtool config routes test --config.file=/etc/alertmanager/alertmanager.yml severity=ticket alertname=HighMemoryUse
team-tickets
$ amtool config routes test --config.file=/etc/alertmanager/alertmanager.yml alertname=Watchdog
default
```

Run `routes test` in CI on every change to `alertmanager.yml`. A typo in a matcher silently sends
pages to the default receiver, and you find out during the next outage. Add `continue: true` to a
route when an alert should also carry on to later siblings (for example, page on-call _and_ post
to the team channel).

### Grouping

`group_by: ['alertname', 'job']` means: alerts with the same alert name and job travel together.
If 40 node_exporters go down because a network switch died, on-call gets **one** message listing
40 instances, not 40 pages. `group_wait` gives the group 30 seconds to collect its members before
the first message.

### Inhibition

An **inhibition rule** mutes some alerts while another is firing. The rule above says: while
`TargetDown` fires for an instance, mute every `severity="ticket"` alert with the same `instance`.
If a server is unreachable, nobody needs a separate ticket about its memory.

### Silences

A **silence** mutes matching alerts for a fixed time, typically for planned work. You create it in
the Alertmanager UI or with amtool, and it needs an author and a comment, so the next person knows
why:

```sh
$ amtool silence add --alertmanager.url=http://localhost:9093 \
    alertname=TargetDown instance=node-exporter:9100 \
    --duration=2h --author=rajeev --comment="Planned reboot of node-exporter host"
cf666dc6-711b-47c1-a657-f6409aa0ff78
$ amtool silence query --alertmanager.url=http://localhost:9093
ID                                    Matchers                                              Ends At                  Created By  Comment
cf666dc6-711b-47c1-a657-f6409aa0ff78  alertname="TargetDown" instance="node-exporter:9100"  2026-11-03 09:03:01 UTC  rajeev      Planned reboot of node-exporter host
$ amtool alert query --alertmanager.url=http://localhost:9093
Alertname  Starts At  Summary  State
$ amtool alert query -s --alertmanager.url=http://localhost:9093
Alertname   Starts At                Summary                             State
TargetDown  2026-11-03 07:01:49 UTC  node on node-exporter:9100 is down  suppressed
```

The plain query hides silenced alerts; `-s` shows them as `suppressed`. The alert still exists in
Prometheus, and if the silence expires while it's still firing, notifications start again. Always
set an end time: a forgotten "silence forever" is how real outages go unnoticed.

> **Figure.** The Alertmanager web UI Alerts tab. The alert is grouped under the receiver on-call with group labels alertname TargetDown and job node, 1 alert, started 2026-11-03T07:01:49.374Z, with labels env lab, instance node-exporter:9100 and severity page, and buttons for Info, Source, Silence and Link.
>
> Alertmanager's own UI: the alert under the on-call receiver, grouped by alertname and job. The Silence button creates a silence pre-filled with its labels.

## Writing alerts people trust

Every page should mean: **users are affected, and a human needs to act now**. Anything else is a
ticket or a dashboard. A few rules that keep it that way:

1. **Alert on symptoms, not causes.** Users feel errors and slowness, not CPU. "Checkout error rate
   above 2% for 10 minutes" is a page. "CPU above 80%" is a dashboard: a busy server that serves
   fast is fine.
2. **Alert on predictions for things that fill up.** `predict_linear(...) < 0` gives you hours of
   warning, at any disk size. "Disk above 90%" fires too late on a small disk and far too early on a
   10 TB one.
3. **Use `for` generously.** 5 to 15 minutes for most symptoms. If you'd fix it the same way 5
   minutes later, it doesn't need to fire on the first sample.
4. **Two severities are enough to start.** `page` (wake someone) and `ticket` (handle in working
   hours). Each should map to one receiver.
5. **Every alert has a runbook link and an owner.** If nobody can say what to do when it fires,
   delete it or make it a ticket.
6. **Review alerts monthly.** Anything that fired and nobody acted on is noise. Fix it or remove it.

One more rule many teams add: a **Watchdog** alert with `expr: vector(1)` that always fires. It goes
to a "dead man's switch" service that pages you if the Watchdog _stops_ arriving. That's how you
find out the alerting pipeline itself is broken.

> **Missing data is not good news.** If a target disappears completely, `up == 0` won't help: there's no series left to compare. For critical jobs, add `absent(up{job="checkout"})` as well, which fires when the series is missing altogether.

> **In production.** Run Alertmanager as a cluster of 2 or 3 (they share silences and deduplicate), point every Prometheus at all of them, and send pages to a real paging tool (PagerDuty, Opsgenie, Grafana OnCall) that handles escalation and acknowledgement. Keep rules and alertmanager.yml in Git and run `promtool check rules` and `amtool check-config` in CI.

## Mission: Break a server and time the alert

With Prometheus, Alertmanager and the rules from this lesson running, stop node_exporter and write down when the alert went pending, when it fired and when the notification arrived. Then silence it, restart node_exporter and record when the resolved notification came. Explain each delay from the settings.

- You need: TargetDown rule with for: 1m; group_wait 30s; group_interval 5m
- You'll have: ~/alert-timeline.txt

```sh
$ date -u +%T; docker stop node-exporter
$ curl -s localhost:9090/api/v1/alerts | grep -o '"state":"[a-z]*"'   # repeat until "firing"
$ amtool alert query --alertmanager.url=http://localhost:9093
$ date -u +%T; docker start node-exporter
```

On the lab machine the page came 97 seconds after the stop (7 s to the next scrape, 60 s of `for`,
30 s of `group_wait`) and the resolved message about 4 minutes after recovery (the next
`group_interval`). Your times will differ by a few seconds. If nothing fires, check that
Prometheus found Alertmanager with `curl -s localhost:9090/api/v1/alertmanagers`, and look at the
Alerts page for rule errors.

## Try it

- Run `promtool check rules rules.yml` on the rules file from this lesson.
- Run `amtool config routes` and draw the tree it prints on paper.
- Stop node_exporter, watch TargetDown go pending then firing on the Alerts page, and note the times.
- Add a 2 hour silence with `amtool silence add` and confirm the alert shows as suppressed.
- Start node_exporter again and wait for the resolved notification.
- Do the mini mission and keep `~/alert-timeline.txt`.

## Quiz

1. An alert rule has `for: 15m`. The expression is true for 10 minutes, then false. What happens?
   - The alert fires after 10 minutes
   - **It stays pending, then returns to inactive; nobody is notified** (answer)
   - It fires and resolves immediately
   Why: The alert becomes pending when the expression turns true and only fires if it stays true for the whole for duration. Short blips never wake anyone up.

2. Which component sends the message to Slack or a pager?
   - Prometheus
   - **Alertmanager** (answer)
   - node_exporter
   Why: Prometheus evaluates rules and sends firing alerts to Alertmanager. Alertmanager groups, silences, routes and delivers them to receivers.

3. 40 disks on 40 servers cross the same threshold at once. What stops you getting 40 messages?
   - Silences
   - **Grouping by labels such as alertname** (answer)
   - Recording rules
   Why: group_by collects alerts that share those label values into one notification. A silence would hide them completely, which isn't what you want here.

4. A server is down. You don't want separate alerts for its high memory, its disk and its CPU too. What do you use?
   - **An inhibition rule that mutes other alerts on the same instance while TargetDown fires** (answer)
   - A longer repeat_interval
   - A second Prometheus
   Why: Inhibition mutes target alerts while a source alert is firing, matched on labels such as instance. The one alert that matters gets through.

5. Which alert is the most useful to page someone at night for?
   - CPU above 80% for 1 minute
   - **Error rate above 2% for 10 minutes on the checkout service** (answer)
   - Any log line containing "warning"
   Why: Page on symptoms users feel, sustained long enough to be real. High CPU alone may be normal and harmless; a warning log line is not an incident.

## Resources

- [Alerting rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) (Prometheus)
- [Alertmanager overview](https://prometheus.io/docs/alerting/latest/alertmanager/) (Prometheus)
- [Alertmanager configuration (route, receivers, inhibit_rules)](https://prometheus.io/docs/alerting/latest/configuration/) (Prometheus)
- [Alerting best practices](https://prometheus.io/docs/practices/alerting/) (Prometheus)
- [Practical alerting from time-series data](https://sre.google/sre-book/practical-alerting/) (Google SRE book)
- [Awesome Prometheus alerts (rule collection)](https://samber.github.io/awesome-prometheus-alerts/) (Community)
