28.7. Collecting Metrics and Delivering Alerts

Prometheus pulls metrics from HTTP endpoints at a fixed interval, stores them as time series, evaluates rules, and sends firing alerts to Alertmanager. Alertmanager groups, silences, inhibits, and routes notifications. The split is deliberate: Prometheus decides whether a condition is true, and Alertmanager decides who should be told and how often.

28.7.1. Configuring Prometheus Targets, Scrape Access, and Retention

A minimal Prometheus configuration scrapes itself, both node exporters, and the blackbox exporter. The blackbox job uses relabeling to pass the probe target as a URL parameter and to send the actual request to the exporter. The configuration lives in /etc/prometheus/prometheus.yml on perf1:

global:
  scrape_interval: 5s
  evaluation_interval: 5s
  external_labels:
    monitor: handbook

alerting:
  alertmanagers:
    - static_configs:
        - targets: ['127.0.0.1:9093']

rule_files:
  - /etc/prometheus/rules/*.yml

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ['127.0.0.1:9090']

  - job_name: node
    static_configs:
      - targets: ['192.168.228.10:9100', '192.168.228.20:9100']

  - job_name: blackbox
    metrics_path: /probe
    params:
      module: [http_2xx]
    static_configs:
      - targets: ['http://192.168.228.20/']
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: 127.0.0.1:9115

The five-second interval is appropriate for a lab; production systems often use 15 or 30 seconds for host metrics and a shorter interval only for symptoms that need it. A shorter interval costs storage and query load, and it does not make a ten-minute problem more visible. Prometheus retention is a service argument; on Debian it is set in /etc/default/prometheus:

ARGS="--storage.tsdb.retention.time=30d"

Restart Prometheus after changing the argument; the restart is silent. The running value is visible through the HTTP API:

$ curl -s localhost:9090/api/v1/status/flags | jq -r '.data["storage.tsdb.retention.time"]'
30d

Prometheus's local storage is not a backup. Retention defines how far back a query can look; it does not protect the data from disk failure. Export or snapshot important series if they must outlive the server, and back up the configuration and rule files with the rest of /etc.

Scrape access is part of the security boundary. A node exporter that listens on every interface exposes host metrics to any network that can reach it. On perf2, restrict the exporter to the lab address by setting its argument file, /etc/default/prometheus-node-exporter, to:

ARGS="--web.listen-address=192.168.228.20:9100"

Apply the change on perf2, in the root shell; the restart is silent:

# systemctl restart prometheus-node-exporter

Test from perf1, in john's shell, on the lab address:

$ curl -s -o /dev/null -w '%{http_code}\n' http://192.168.228.20:9100/metrics
200

perf2's management address on eth0 is 192.168.121.248 in this lab. The exporter no longer listens there, so the same request against that address fails:

$ curl -s --max-time 2 -o /dev/null -w '%{http_code}\n' http://192.168.121.248:9100/metrics
000

The exit status is nonzero and the status code is 000; curl could not connect. That is the intended result. When the exercise is finished, return perf2's exporter to its default listener by setting ARGS="" in the same file and restarting the service; Prometheus scrapes the lab address, which works either way. Restore the general listener permanently only if a firewall or another access control protects it. A firewall rule is covered in Chapter 18; binding to one address is simpler when the monitoring network is known and the host has a stable address.

Prometheus and Alertmanager do not provide user authentication by themselves. Expose them only on a management network, or put an authenticating reverse proxy in front of them; the same applies to the blackbox exporter's probe endpoint. Metric data can reveal hostnames, mount points, and service topology, so treat the scrape network as an administrative network.

28.7.2. Recording Rules and Alerts for Availability, Capacity, and Missing Backups

Rules live in files loaded by rule_files. The listing begins /etc/prometheus/rules/lab.yml; the availability and capacity groups later in this subsection are appended to the same top-level groups: list. A recording rule precomputes an expression so dashboards and alerts do not repeat it:

groups:
  - name: recording
    rules:
      - record: instance:node_cpu_utilization:rate1m
        expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)
      - record: instance:node_filesystem_usage:ratio
        expr: 1 - node_filesystem_avail_bytes / node_filesystem_size_bytes

The CPU recording rule converts idle counters into a percentage; the filesystem rule keeps the used fraction. The availability and capacity alerts are ordinary PromQL expressions with for durations:

  - name: availability
    rules:
      - alert: InstanceDown
        expr: up{job="node"} == 0
        for: 10s
        labels:
          severity: critical
        annotations:
          summary: "Node exporter on {{ $labels.instance }} is unreachable"
      - alert: ProbeFailing
        expr: probe_success{job="blackbox"} == 0
        for: 10s
        labels:
          severity: warning
        annotations:
          summary: "HTTP probe for {{ $labels.instance }} is failing"
      - alert: MonitoringDataMissing
        expr: absent(up{job="node"})
        for: 20s
        labels:
          severity: critical
        annotations:
          summary: "No node-exporter series are being scraped"
  - name: capacity
    rules:
      - alert: HighFilesystemUsage
        expr: (1 - node_filesystem_avail_bytes{fstype="ext4",mountpoint="/srv/capacity"} / node_filesystem_size_bytes{fstype="ext4",mountpoint="/srv/capacity"}) > 0.90
        for: 10s
        labels:
          severity: warning
        annotations:
          summary: "Filesystem {{ $labels.mountpoint }} on {{ $labels.instance }} is over 90% used"
      - alert: BackupMissing
        expr: time() - backup_last_success_timestamp_seconds > 3600
        for: 10s
        labels:
          severity: warning
        annotations:
          summary: "The last successful backup is more than one hour old"

Save the file as /etc/prometheus/rules/lab.yml and validate it before reloading. The validation commands are:

Command Description
promtool check config FILE Validate the Prometheus configuration and its rule files.
promtool check rules FILE Validate alert and recording expressions.
promtool test rules FILE Evaluate rules against synthetic series.
amtool check-config FILE Validate the Alertmanager configuration.

promtool checks syntax and rule expressions without touching the running server:

$ sudo promtool check config /etc/prometheus/prometheus.yml
Checking /etc/prometheus/prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax

Checking /etc/prometheus/rules/lab.yml
  SUCCESS: 7 rules found
$ sudo promtool check rules /etc/prometheus/rules/lab.yml
Checking /etc/prometheus/rules/lab.yml
  SUCCESS: 7 rules found

Reload the running server with sudo systemctl reload prometheus; the reload is silent. The target list and health show that all scrapes are succeeding:

$ curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | [.labels.job,.scrapeUrl,.health] | @tsv'
blackbox    http://127.0.0.1:9115/probe?module=http_2xx&target=http%3A%2F%2F192.168.228.20%2F   up
node    http://192.168.228.10:9100/metrics  up
node    http://192.168.228.20:9100/metrics  up
prometheus  http://127.0.0.1:9090/metrics   up

The recording rule is queryable like any other series:

$ curl -s localhost:9090/api/v1/query --data-urlencode 'query=instance:node_cpu_utilization:rate1m' | jq -r '.data.result[] | [.metric.instance,.value[1]] | @tsv'
192.168.228.20:9100 13.63636363636364
192.168.228.10:9100 9.733920194171162

The values are percentages. The rule name encodes the aggregation and window, so a dashboard does not have to guess them.

With the rules loaded, exercise the capacity rule without touching a production filesystem. Create a small loop-mounted ext4 image on the disposable test disk. In the root shell on perf1, each of the following commands is silent. Create the 150 MiB image file on the test disk:

# truncate -s 150M /mnt/perfdisk/capacity.img

Format it, with -q suppressing the summary that Section 28.4.4 showed:

# mkfs.ext4 -F -q /mnt/perfdisk/capacity.img

Create the mountpoint and mount the image; mounting by loop device lets the filesystem be removed like a file afterwards:

# mkdir -p /srv/capacity
# mount -o loop /mnt/perfdisk/capacity.img /srv/capacity

Fill it past the 90 percent threshold:

# dd if=/dev/zero of=/srv/capacity/fill bs=1M count=130 status=none

The mountpoint is under /srv, not /mnt, because the Debian node-exporter package excludes /mnt and /media from the filesystem collector. df shows the result:

$ df -h /srv/capacity
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop0      136M  131M     0 100% /srv/capacity

After the next evaluation, the rule fires:

$ curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | [.labels.alertname,.labels.mountpoint,.state] | @tsv'
HighFilesystemUsage /srv/capacity   firing

Leave the loop mount in place for now: the silence, inhibition, and delivery exercises in the next two subsections use this still-firing alert as their example. It is removed at the end of Section 28.7.5.

The backup metric is supplied by the textfile collector. A script that completes a backup writes a Unix timestamp to /var/lib/prometheus/node-exporter/backup.prom:

backup_last_success_timestamp_seconds 1795466309

Node exporter reads the file on the next scrape. The alert expression compares the timestamp with the current time, so it fires when the file is stale and resolves when a new timestamp is written. This is a common pattern for cron jobs, backup scripts, and certificate renewals that have no native exporter.

absent() needs special care: when a job is removed from the configuration, Prometheus keeps the last sample for the lookback delta (five minutes by default) before the series becomes stale. A backup-missing or target-missing alert should use a for duration long enough to cover that staleness, or a recording rule should explicitly mark the job as missing. The rule unit test in Section 28.7.4 verifies the expression without waiting five minutes.

28.7.3. Alertmanager Routing, Grouping, Silences, and Inhibition

Alertmanager receives firing alerts and decides how to deliver them. A minimal configuration sends every alert to one webhook, groups by alert name and severity, and inhibits capacity warnings while the same instance is down:

global:
  resolve_timeout: 1m

route:
  receiver: webhook
  group_by: [alertname, severity]
  group_wait: 2s
  group_interval: 5s
  repeat_interval: 30s

inhibit_rules:
  - source_matchers:
      - alertname="InstanceDown"
    target_matchers:
      - alertname=~"HighFilesystemUsage|ProbeFailing"
    equal: [instance]

receivers:
  - name: webhook
    webhook_configs:
      - url: http://127.0.0.1:9099/alerts
        send_resolved: true

group_wait is how long Alertmanager waits for more alerts in a new group; group_interval is the minimum time between updates to an existing group; and repeat_interval is how long a still-firing alert waits before being sent again. The values here are short for a lab. In production they are chosen so that a flapping service does not page repeatedly and a sustained problem is still re-sent.

Validate the file with amtool before reloading:

$ sudo amtool check-config /etc/prometheus/alertmanager.yml
Checking '/etc/prometheus/alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 1 inhibit rules
 - 1 receivers
 - 0 templates

Save the file as /etc/prometheus/alertmanager.yml and reload Alertmanager with sudo systemctl reload prometheus-alertmanager; the reload is silent. The example receiver is a local Python HTTP server on 127.0.0.1:9099 that appends each POST body to notifications.jsonl:

#!/usr/bin/env python3
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LOG = "/home/john/debian-handbook/monitoring/notifications.jsonl"


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode("utf-8", "replace")
        with open(LOG, "a", encoding="utf-8") as handle:
            handle.write(json.dumps({"received": time.time(), "body": json.loads(body)}) + "\n")
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok")

    def log_message(self, fmt, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", 9099), Handler).serve_forever()

Start it as a transient service so that it survives the shell and can be stopped by unit name:

$ sudo systemd-run --unit=alert-receiver --uid=john --collect python3 /home/john/debian-handbook/monitoring/receiver.py
Running as unit: alert-receiver.service; invocation ID: ba14cce0c4a347b1b222fd4cf0dba4b8

Stop it with sudo systemctl stop alert-receiver. The receiver appends each POST body to notifications.jsonl. Grouping is visible in that file. Inject two synthetic alerts with the same alertname and severity but different instance labels, so that the grouping rule has something to group; --end bounds their lifetime so the exercise cleans up after itself. In the root shell on perf1, each command is silent:

# amtool --alertmanager.url=http://127.0.0.1:9093 alert add alertname=GroupTest severity=warning instance=group-a --end=$(date -u -d '+2 minutes' +%Y-%m-%dT%H:%M:%SZ)
# amtool --alertmanager.url=http://127.0.0.1:9093 alert add alertname=GroupTest severity=warning instance=group-b --end=$(date -u -d '+2 minutes' +%Y-%m-%dT%H:%M:%SZ)

Alertmanager's group_wait collects the pair, and one notification contains both:

$ sudo cat /home/john/debian-handbook/monitoring/notifications.jsonl | jq -r 'select(.body.alerts[0].labels.alertname=="GroupTest") | .body.alerts | length' | tail -1
2

The receiver is a stand-in for email, chat, or a paging service; the Alertmanager configuration is what changes when the destination changes. The amtool commands used here are:

Command Description
--alertmanager.url=URL Select the Alertmanager API endpoint.
alert add LABEL=VALUE ... Inject a test alert.
silence add ... Create a time-bound silence.
silence query List silences and their IDs.
silence expire ID End a silence immediately.

A silence suppresses notifications for matching alerts without resolving them in Prometheus:

$ sudo amtool --alertmanager.url=http://127.0.0.1:9093 silence add alertname=HighFilesystemUsage --duration=2m --comment='capacity maintenance' --author=john
5eea96ed-d3e6-4771-9767-6211024abb12

The alert still exists; the Alertmanager API records the silence:

$ curl -s localhost:9093/api/v2/alerts | jq -r '.[] | select(.labels.alertname=="HighFilesystemUsage") | [.labels.instance, (.status.silencedBy|length)] | @tsv'
192.168.228.10:9100 1

Inhibition is different: a firing source alert suppresses a target alert while both match. The inhibit rule in the configuration above needs a firing InstanceDown alert for the same instance as the target; its severity label is not part of the match, but the injected alert carries the same labels the real rule produces. Inject one with a short end time, so it disappears on its own; the command is silent:

# amtool --alertmanager.url=http://127.0.0.1:9093 alert add alertname=InstanceDown severity=critical instance=192.168.228.10:9100 --end=$(date -u -d '+20 seconds' +%Y-%m-%dT%H:%M:%SZ)

While it exists, the capacity alert is reported as inhibited:

$ curl -s localhost:9093/api/v2/alerts | jq -r '.[] | select(.labels.alertname=="HighFilesystemUsage" and .labels.instance=="192.168.228.10:9100") | (.status.inhibitedBy|length)'
1

Silences are time-bound operational actions; inhibition is a standing rule derived from alert relationships. Use inhibition for cases such as "do not send a disk-full warning when the whole host is unreachable" and use silences for maintenance that a person has scheduled.

28.7.4. External Service Probes and Detecting Missing Monitoring Data

The blackbox exporter turns a URL, TCP port, or other endpoint into a metric. The HTTP probe against perf2's nginx is configured in the scrape job as probe_success. To give the probe a failure to observe, stop nginx on perf2, in the root shell; the command is silent:

# systemctl stop nginx

From perf1, in john's shell, the next scrape records the failure:

$ curl -s 'localhost:9090/api/v1/query?query=probe_success' | jq -r '.data.result[] | [.metric.instance,.value[1]] | @tsv'
http://192.168.228.20/  0

The ProbeFailing alert fires after ten seconds. Start nginx again on perf2, also silently:

# systemctl start nginx

The probe recovers on the following scrape:

$ curl -s 'localhost:9090/api/v1/query?query=probe_success' | jq -r '.data.result[] | .value[1]'
1

This is an external check: it exercises the network path and the HTTP stack, not just the target's process table. A probe that only checks "process is running" can miss a listener that accepts connections but never answers.

Missing monitoring data is a third failure mode. MonitoringDataMissing uses absent(up{job="node"}) to fire when the job label disappears entirely. Prometheus retains stale samples for its five-minute lookback, so a live transition takes at least that long to observe. promtool can evaluate the rule against synthetic series without waiting. Write the test file /etc/prometheus/rules-test.yml:

rule_files:
  - /etc/prometheus/rules/lab.yml
evaluation_interval: 1m

tests:
  - interval: 1m
    input_series:
      - series: 'up{job="node",instance="192.168.228.10:9100"}'
        values: '1 1 1 1 1 1 1 1 1 1 1 1'
    alert_rule_test:
      - eval_time: 10m
        alertname: MonitoringDataMissing
        exp_alerts: []

  - interval: 1m
    alert_rule_test:
      - eval_time: 2m
        alertname: MonitoringDataMissing
        exp_alerts:
          - exp_labels:
              job: node
              severity: critical
            exp_annotations:
              summary: "No node-exporter series are being scraped"
$ sudo promtool test rules /etc/prometheus/rules-test.yml
Unit Testing:  /etc/prometheus/rules-test.yml
  SUCCESS

The first test proves that the alert is absent while a series exists; the second proves that it fires when no series exists. The job="node" label is synthesized by absent() from the equality matcher, which is why the expected labels include it. A production rule should also cover the case where only one instance disappears while the job still has other series; that is what InstanceDown does, while MonitoringDataMissing covers the loss of the whole job or the monitoring path itself.

28.7.5. Testing Alert Delivery, Recovery Notifications, and Notification-Service Failure

An alerting system is not tested until a notification reaches the destination and a recovery reaches it too. The local receiver writes every delivery to notifications.jsonl; the backup alert is a convenient controlled trigger. Write a timestamp two hours in the past. The file lives in the exporter's textfile directory, so this is a root operation; the command is silent. In the root shell on perf1:

# printf 'backup_last_success_timestamp_seconds %s\n' "$(( $(date +%s) - 7200 ))" > /var/lib/prometheus/node-exporter/backup.prom

After the next scrape and the for duration, Prometheus reports the alert:

$ curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | [.labels.alertname,.state] | @tsv'
BackupMissing   firing

The receiver log records the firing notification. Write a fresh timestamp to resolve it; as before, the redirection writes the file and produces no terminal output. In the root shell on perf1:

# printf 'backup_last_success_timestamp_seconds %s\n' "$(date +%s)" > /var/lib/prometheus/node-exporter/backup.prom

After the next evaluation and the resolve timeout, the log contains a resolved notification:

$ sudo cat /home/john/debian-handbook/monitoring/notifications.jsonl | jq -r '.body.status' | tail -3
firing
resolved

Recovery notifications require send_resolved: true in the receiver configuration. Without it, the alert disappears from the dashboard and nobody learns that the condition cleared. Test both directions for every alert that matters.

Expire the silence before testing delivery again. The ID is the one printed by the silence command; yours will differ. The command is silent when it succeeds:

$ sudo amtool --alertmanager.url=http://127.0.0.1:9093 silence expire 5eea96ed-d3e6-4771-9767-6211024abb12

The notification service itself can fail. Stop the receiver and let a firing alert repeat. In the root shell on perf1:

# systemctl stop alert-receiver

Alertmanager logs the failure and retries with backoff:

$ sudo journalctl -u prometheus-alertmanager --since '2 min ago' --no-pager | grep -E 'Notify attempt failed|connection refused' | tail -4
Nov 24 02:42:45 perf1 prometheus-alertmanager[53924]: time=2026-11-24T02:42:45.504Z level=ERROR source=dispatch.go:360 msg="Notify for alerts failed" component=dispatcher num_alerts=1 err="webhook/webhook[0]: notify retry canceled after 8 attempts: Post \"<redacted>\": dial tcp 127.0.0.1:9099: connect: connection refused"
Nov 24 02:42:45 perf1 prometheus-alertmanager[53924]: time=2026-11-24T02:42:45.505Z level=WARN source=notify.go:865 msg="Notify attempt failed, will retry later" component=dispatcher receiver=webhook integration=webhook[0] aggrGroup="{}:{alertname=\"HighFilesystemUsage\", severity=\"warning\"}" attempts=1 err="Post \"<redacted>\": dial tcp 127.0.0.1:9099: connect: connection refused"
Nov 24 02:42:50 perf1 prometheus-alertmanager[53924]: time=2026-11-24T02:42:50.054Z level=ERROR source=dispatch.go:360 msg="Notify for alerts failed" component=dispatcher num_alerts=2 err="webhook/webhook[0]: notify retry canceled after 8 attempts: Post \"<redacted>\": dial tcp 127.0.0.1:9099: connect: connection refused"
Nov 24 02:42:50 perf1 prometheus-alertmanager[53924]: time=2026-11-24T02:42:50.055Z level=WARN source=notify.go:865 msg="Notify attempt failed, will retry later" component=dispatcher receiver=webhook integration=webhook[0] aggrGroup="{}:{alertname=\"GroupTest\", severity=\"warning\"}" attempts=1 err="Post \"<redacted>\": dial tcp 127.0.0.1:9099: connect: connection refused"

The WARN lines are individual failed attempts that Alertmanager will retry with backoff; the ERROR line records a notification whose retry budget of eight attempts was exhausted. The alert is not lost in either case; it stays pending and is sent again at the next repeat interval. Start the receiver again with the same systemd-run command from Section 28.7.3 and wait for the next retry or repeat interval. New notifications appear in the log:

$ sudo cat /home/john/debian-handbook/monitoring/notifications.jsonl | jq -r '.body.alerts[].labels.alertname' | tail -8
GroupTest
GroupTest
InstanceDown
InstanceDown
HighFilesystemUsage
HighFilesystemUsage
GroupTest
GroupTest

The exact set depends on which alerts were firing during the outage. The important assertions are that a firing alert was delivered after recovery and that the Alertmanager log shows connection failures rather than silent drops. A production test should also cover the notification service returning an HTTP error, an authentication failure, and a slow response; the webhook receiver can be made to return 500 for a bounded test, and the Alertmanager retry behavior is the same category of failure.

A monitoring stack that has never lost a notification is a stack that has not been tested. Test the target down, the probe down, the capacity threshold, the silence, the inhibition, the delivery, the recovery, and the failure of the delivery path itself. Keep the resulting rule files and receiver scripts under configuration management, and record the commands and observations alongside the incident timeline so the next test starts from a known state.

Finish by removing the capacity loop mount kept from Section 28.7.2. In the root shell on perf1, unmount the image; the command is silent:

# umount /srv/capacity

Remove the backing file from the disposable test disk:

# rm /mnt/perfdisk/capacity.img

That command is also silent. The HighFilesystemUsage alert resolves as the filesystem disappears from the next scrape, and with every exercise closed out, the monitoring stack keeps running against the two hosts as it was configured to do.