Prometheus & Grafana Hour 2: Alerting and Production Readiness

On the ~/promlab Docker Compose environment from Lesson 1, add everything needed to “wake the right person when something breaks, and only once”: recording rules, alerting rules, Alertmanager routing/grouping/inhibition/silences, notification channels, Grafana Alerting, dashboard design and storage planning
Prometheus v3.16.0Alertmanager v0.35.0Grafana 13.3.1promtool · amtoolVerified against the official docs and source code · 2026-11-15
Overall learning goals
  • Use recording rules to pre-compute the expensive PromQL that dashboards and alerts use repeatedly into new series, following the official naming conventions level:metric:operations (for example job:myapp_http_errors:ratio_rate5m).
  • Write maintainable alerting rules: expr,for,keep_firing_for, labels (severity,service), annotations (summary,description,runbook_url), and use promtool test rules for unit tests.
  • Explain the full lifecycle: inactive → pending → firing → (sent to Alertmanager) deduplication → grouping → inhibition / silences / time windows → notification → resolved, and be able to explain group_wait,group_interval,repeat_interval how they affect notification timing.
  • Configure Alertmanager routing trees, inhibition rules, silences and time intervals, use amtool to validate configuration, test routing and manage silences.
  • Connect notification channels: webhook (a local receiver, so the lab needs no external accounts at all), email (local Mailpit), Microsoft Teams (msteamsv2_configs), Slack, PagerDuty, and manage secrets properly.
  • Understand the Grafana Alerting model (alerting rules, contact points, notification policies, silences, time intervals) and the division of responsibilities between Prometheus and Alertmanager; be able to manage Grafana alerts with file provisioning.
  • Design USE / RED / the four golden signals layered dashboards; plan using the official formulas for retention and disk; finally, use a production-readiness review checklist to review the entire monitoring stack.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (~/promlab)
0Before classWarm-up and bridgeCheck the Lesson 1 Compose environment; add Alertmanager, the local webhook receiver and Mailpit“Alerting readiness” self-assessmentcompose.alerting.yaml Overlay file
100–06Recording rules: precomputation and naming conventionsRule groups, sequential evaluation, naming conventions,limit,query_offset, when to use / when not to use“Query cost” comparator + name buildermyapp RED recording rules + promtool check rules
206–13Alerting rules: for, labels and annotationsfor,keep_firing_for, templates,ALERTS series, symptoms vs causes, unit testsCore animation: full alert lifecycle (rule evaluation → Alertmanager → notification → resolved)myapp alerts + promtool test rules + stop myapp and watch pending/firing
313–21Alertmanager: routing, grouping, inhibition and silencesrouting tree and continue, group_by and the three timers, inhibit_rules, silence, time_intervals, high-availability clusterrouting tree simulator (enter labels to see the matched path, inhibition and silences)amtool config routes test, stop Redis to watch inhibition, add a silence
421–28Notification channelswebhook payload format, email, Teams (Workflows), Slack, PagerDuty Events v2, templates, secret files, retries and failure metricsNotification payload previewerLocal webhook + Mailpit receive firing / resolved
528–35Grafana Alerting and unified alertingGrafana-managed rules vs data-source-managed rules, contact points, notification policies, No Data / Error, Recovering, provisioningGrafana alert state machineFile provisioning of one Grafana rule + webhook contact point
635–42Dashboard design: USE / RED / the four golden signalslayered dashboards, panel choice, units and thresholds, recording-rule-driven panels, alert and runbook linksDashboard method generator (good vs bad version comparison)Provision the “myapp service overview” dashboard
742–50Storage, retention and capacity planningTSDB blocks, WAL, compaction, retention (time / size / percentage), capacity formula, memory estimation, Alertmanager dataCapacity calculatorMeasure ingestion rate, set retention in the config file,promtool tsdb analyze
850–60Production-readiness review and common mistakesReview checklist, Watchdog, monitoring the monitoring system, alert fatigue, typical mistakesReadiness scorecard + interactive troubleshooting treeFault injection and repair
—After classCheat sheet · Capstone labBuild the myapp alerts and dashboards from scratchFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLabs
Recording rules and naming conventions✓✓···✓✓✓promtool check rulesM1 lab
Alerting rules and templates·✓✓✓✓··✓/api/v1/alerts,ALERTSM2 lab
Rule unit tests✓✓·····✓promtool test rulesM2, capstone lab
Alert lifecycle and timers·✓✓✓✓··✓group_wait/interval,repeat_intervalM2, M3
Routing, inhibition, silences, time intervals··✓✓✓··✓amtool config routes test,amtool silenceM3 lab
Notification channels and secrets···✓✓··✓webhook_configs,*_fileM4 lab
Grafana Alerting····✓✓·✓/api/v1/provisioning/...M5 lab
Dashboard design (USE/RED/golden signals)✓····✓·✓dashboard provisioningM6 lab
Retention and capacity planning······✓✓promtool tsdb analyze,storage.tsdb.retentionM7 lab
Monitoring the monitor itself (meta-monitoring)·✓✓✓··✓✓Watchdog,alertmanager_notifications_failed_totalM8, capstone lab

What this lesson does not cover (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Prometheus architecture, metric types, scraping, PromQL basics, Grafana data sources and your first dashboardAlready covered in Lesson 1; used directly in this lessonLesson 1
Rule groups for Azure Monitor managed Prometheus, Azure Managed Grafana alertsBelongs to the cloud platform topicsLesson 3 (Azure)
Rules and Alertmanager definitions for Amazon Managed Service for PrometheusBelongs to the cloud platform topicsLesson 4 (AWS)
PrometheusRule / AlertmanagerConfig CRDs, rules bundled with kube-prometheus-stackRequires the Prometheus OperatorLesson 5
SLOs and multi-window multi-burn-rate alerting, Thanos/Mimir long-term storage and global viewArchitecture topics; they need the rule basics from this lessonLesson 6
Cardinality explosion, TSDB internals (head/WAL/compaction), deep troubleshootingThis lesson only covers an introduction to capacity planningLesson 7 · Lesson 8 (50 problems)
Kubernetes autoscaling (HPA/metrics-server)Unrelated to alertingKubernetes course

How to use these course materials

10 pages per module
Theory · diagrams · animation · commands · labs · production cases · troubleshooting · quizzes · voice · video. Read “Theory” and “Animation” first, then do the “Labs”. All labs build cumulatively on the same ~/promlab directory; the module order is the order in which the files are created.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress; it is saved in this browser (cleared on refresh if the browser blocks local storage).
Chinese voice
The “Voice” page reads the narration script aloud with the browser’s built-in Web Speech API (en-US); if no Chinese voice pack is installed, the script can still be read or passed to a TTS tool.
Version notes This lesson uses as its baseline Prometheus v3.16.0 (2026-11-04),Alertmanager v0.35.0 (2026-11-09),Grafana 13.3.1 (2026-11-10). Recent changes relevant to alerting that need attention: from Alertmanager v0.34.2 onward no longer sends CORS headers by default (browser cross-origin calls to /api/v2 require --web.cors.origin); in v0.35.0, /ui/ a new Mantine UI is provided,--enable-feature=auto-gomemlimit and the default changes to --auto-gomemlimit; the Prometheus 3.16 docs recommend setting TSDB retention in the configuration file storage.tsdb.retention, whereas the command-line --storage.tsdb.retention.* flag is marked deprecated (still usable). Grafana 12.x users: the alerting concepts (rules, contact points, notification policies, Recovering state) are the same as in this lesson; UI locations may differ slightly.
Cost and security Everything in this lesson runs locally in Docker on this machine,so it incurs no cloud cost, and no Slack/Teams/PagerDuty accounts are needed: notifications go to a local webhook receiver (Python standard library) and a local Mailpit. Required permission: a local user who can run Docker. Security risks: the Grafana admin password in the lab and the non-TLS ports are for local use only; real webhook URLs and PagerDuty routing keys must always be treated as secrets (Module 4). Clean-up after class is covered in the last step of the capstone lab.

Module 0 · Warm-up and bridge (Lesson 1 environment)

Confirm that the Lesson 1 ~/promlab still works, then add Alertmanager, the local webhook receiver and Mailpit using a Compose overlay file
Before class ≈ 10 minutesDocker Compose v2
Prerequisites
  • CompletedLesson 1: directory ~/promlab, Compose project promlab (compose.yaml), services prometheus (9090),alertmanager (9093),grafana (3000),node-exporter (9100),myapp (5000),redis,redis-exporter (9121), with ports bound only to 127.0.0.1. prometheus/prometheus.yml already contains alerting (pointing to alertmanager:9093),rule_files: ["rules/*.yml"] and job prometheus,alertmanager,grafana,node,myapp,redis; alertmanager/alertmanager.yml is a minimal configuration with only "null" receivers; the Grafana data source uid is prometheus, the dashboard provider reads /etc/grafana/dashboards (host grafana/dashboards/, already has myapp-red.json).
  • myapp comes from the Docker lesson (Flask + gunicorn + Redis, port 5000); Lesson 1 already added /healthz,/metrics, as well as the endpoints that create latency and errors /slow,/error (returns 500) routes, with unified metric names: myapp_http_requests_total{method,route,status} (counter),myapp_http_request_duration_seconds (histogram),myapp_redis_up (gauge).
  • Tools: Docker Engine + Compose v2,curl,jq. promtool and amtool do not need to be installed separately; they are included in the Prometheus and Alertmanager images respectively.

Step 1: check the Lesson 1 environment

cd ~/promlab
ls
docker compose ps --format 'table {{.Service}}\t{{.State}}\t{{.Ports}}'
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | "\(.labels.job)\t\(.health)"'
alertmanager  compose.yaml  grafana  myapp  prometheus
SERVICE          STATE     PORTS
alertmanager     running   127.0.0.1:9093->9093/tcp
grafana          running   127.0.0.1:3000->3000/tcp
myapp            running   127.0.0.1:5000->5000/tcp
node-exporter    running   127.0.0.1:9100->9100/tcp
prometheus       running   127.0.0.1:9090->9090/tcp
redis            running   6379/tcp
redis-exporter   running   127.0.0.1:9121->9121/tcp
prometheus	up
alertmanager	up
grafana	up
node	up
myapp	up
redis	up
Follow the Lesson 1 conventions The job names in this lesson’s rules come directly from Lesson 1’s myapp,redis,prometheus; in Lesson 1, static labels were added to the myapp and redis targets env="lab" (myapp also has service="myapp"), and Prometheus’s external_labels is set to lab="promlab" (this is attached to alerts sent to Alertmanager). The Grafana admin account is admin, and the password is ${GF_ADMIN_PASSWORD:-promlab-admin}.

Step 2: create this lesson’s directory and a local webhook receiver

The lab needs no external accounts: Alertmanager and Grafana both POST notifications to a receiver written with the Python standard library, which prints each notification as a single line and saves the latest full JSON to /tmp/last.json.

cd ~/promlab
mkdir -p prometheus/rules prometheus/tests alertmanager/templates webhook grafana/provisioning/alerting
cat > webhook/receiver.py <<'EOF'
import json, datetime
from http.server import BaseHTTPRequestHandler, HTTPServer

class H(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        try:
            d = json.loads(body)
        except ValueError:
            d = {"raw": body.decode(errors="replace")}
        alerts = d.get("alerts", [])
        names = ",".join(sorted({a.get("labels", {}).get("alertname", "?") for a in alerts}))
        now = datetime.datetime.now().strftime("%H:%M:%S")
        print(f"{now} POST {self.path} receiver={d.get('receiver')} status={d.get('status')} "
              f"alerts={len(alerts)} [{names}] groupLabels={json.dumps(d.get('groupLabels', {}), ensure_ascii=False)}",
              flush=True)
        with open("/tmp/last.json", "w") as f:
            json.dump(d, f, indent=2, ensure_ascii=False)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok")

    def log_message(self, *args):
        pass

HTTPServer(("", 5001), H).serve_forever()
EOF

Step 3: Compose overlay file (without changing Lesson 1’s compose.yaml)

Compose supports merging multiple files: fields of services with the same name are merged or overridden. The Lesson 1 compose.yaml already includes alertmanager service (config directory ./alertmanager mounted read-only, data volume am-data), and Prometheus also already mounts the whole ./prometheus mounted at /etc/prometheus (so rules/ and the rule files newly created in this lesson tests/ are automatically visible). This lesson only edits compose.alerting.yaml in add the webhook receiver and Mailpit, and override the alertmanager command (adding an external URL and turning off cluster gossip), using .env in COMPOSE_FILE so that docker compose reads both files by default.

services:
  alertmanager:                                         # only overrides command; image, ports and volumes are inherited from Lesson 1
    command:
      - --config.file=/etc/alertmanager/alertmanager.yml
      - --storage.path=/alertmanager
      - --web.external-url=http://localhost:9093        # link used in notifications
      - --cluster.listen-address=                       # single instance: disable cluster gossip

  webhook:                                              # local notification receiver
    image: python:3.13-slim
    command: ["python", "-u", "/app/receiver.py"]
    volumes:
      - ./webhook:/app:ro
    ports:
      - "127.0.0.1:5001:5001"
    restart: unless-stopped

  mailpit:                                              # local SMTP + web UI (Module 4)
    image: axllent/mailpit:v1.33.1
    ports:
      - "127.0.0.1:8025:8025"
    restart: unless-stopped
cd ~/promlab
grep -q '^COMPOSE_FILE=' .env 2>/dev/null || echo 'COMPOSE_FILE=compose.yaml:compose.alerting.yaml' >> .env
cat .env

Step 4: replace Lesson 1’s "null" configuration with the webhook receiver

The Lesson 1 alertmanager.yml sends all alerts to a "null" receiver that sends no notifications. First,replace it entirely with a minimal “send everything to the webhook” configuration; Module 3 will expand it into the full routing tree. Nothing needs to change on the Prometheus side: the Lesson 1 prometheus.yml already has alerting,rule_files: ["rules/*.yml"] (relative path, i.e. /etc/prometheus/rules/*.yml), and alertmanager scrape job.

route:
  receiver: default-webhook
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 30s
  repeat_interval: 1h

receivers:
  - name: default-webhook
    webhook_configs:
      - url: http://webhook:5001/default
cd ~/promlab
docker compose up -d                            # creates webhook and mailpit, and rebuilds alertmanager with the new command
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml
docker compose exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml
curl -s localhost:9090/api/v1/alertmanagers | jq '.data.activeAlertmanagers'
Checking /etc/prometheus/prometheus.yml
  SUCCESS: 0 rule files found
 SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax

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

[
  {
    "url": "http://alertmanager:9093/api/v2/alerts"
  }
]

Prometheus 3 only uses Alertmanager API v2 (v1 was removed in Alertmanager 0.27), so the discovered URL ends with /api/v2/alerts . After this lesson, use docker compose kill -s SIGHUP prometheus to reload (Lesson 1 also enabled --web.enable-lifecycle, so curl -XPOST localhost:9090/-/reload works too).

Step 5: send a test alert to verify the pipeline end to end

curl -s -XPOST localhost:9093/api/v2/alerts -H 'Content-Type: application/json' -d '[
  {"labels":{"alertname":"SetupSmokeTest","severity":"info"},
   "annotations":{"summary":"Lesson 2 environment connectivity test"}}]'
sleep 15
docker compose logs --no-log-prefix webhook | tail -n 3
09:12:41 POST /default receiver=default-webhook status=firing alerts=1 [SetupSmokeTest] groupLabels={"alertname": "SetupSmokeTest"}

Wait about 10 seconds (group_wait) before a notification appears. A manually POSTed alert has no endsAt, so Alertmanager treats it as resolved after resolve_timeout (default 5m).

Warm-up: answer from memory (30 seconds)

Lesson 1: why must the counter operation come first rate() and then sum(), not the reverse?

rate() Counter resets (the counter restarting from 0 after a process restart) must be detected on each raw series; summing first mixes multiple series together, so one instance’s reset would be mistaken for an overall drop and distort the result. The recording rules in this lesson strictly follow “rate first, then sum”.

histogram_quantile() Which label must be kept when aggregating?

le. Correct form: histogram_quantile(0.95, sum by (job, le) (rate(myapp_http_request_duration_seconds_bucket[5m]))).

Does Prometheus send notifications itself?

No. Prometheus only evaluates rules to determine alerts and pushes active alerts to Alertmanager; deduplication, grouping, inhibition, silences and notifications are all handled by Alertmanager.

“Alerting readiness” 10-item self-assessment

Tick the items your current environment has already achieved (saved in this browser). Tick them again after completing the capstone lab.

Environment self-check list

Module 1 · Recording rules: precomputation and naming conventions

00:00 – 06:00 · Turn the expensive queries that dashboards and alerts run repeatedly into new series that Prometheus writes periodically
6 minlevel:metric:operations★★★★☆
Learning objectives
  • Explain the execution model of recording rules: rule file → rule group → at interval a regular interval, within the group sequential evaluation, with the same evaluation timestamp → results written back to the TSDB.
  • Name recording rules following the official level:metric:operations convention, knowing when to drop _total and when to add ratio.
  • Write RED recording rules for myapp (request rate, error ratio, p95 latency) using promtool check rules promtool to validate them, and know what limit,query_offset,rule_group_iterations_missed_total mean.
Prerequisites: From Lesson 1: the rate(),sum by,histogram_quantile(). Importance:★★★★☆

What: a recording rule = a PromQL expression run on a schedule + storing the result as a new series

A recording rule is written in a rule file and executed at a fixed interval by the Prometheus rule manager runs it at a fixed interval. Each run writes the expr result (an instant vector) back to the local TSDB under the record name you specify. Afterwards, dashboards and alerts only need to query this new series, instead of running rate + sum over the raw series every time.

groups:                       # a file can contain multiple groups
  - name: myapp-recording     # group names must be unique within the file
    interval: 15s             # defaults to global.evaluation_interval
    rules:
      - record: job:myapp_http_requests:rate5m
        expr: sum by (job) (rate(myapp_http_requests_total[5m]))

Why: why precomputation is needed

  • Dashboard speed: a panel with a 7-day range refreshing every 30 seconds has to read the samples of every raw series across the whole time range each time; a recording rule turns “read N series” into “read 1 series”.
  • Alerting consistency: alerting expressions reference the recording rule, and dashboards reference the same series, so on-call staff see on the graph exactly the number that triggered the alert.
  • Dimensionality reduction for federation / remote write / long-term storage: send only the aggregated series to the global view (Lesson 6), rather than all raw series.
  • Layering complex expressions: ratios, quantiles and SLO burn rates can be composed from an earlier layer of recording rules, so each expression is shorter and easier to test.

How: execution model (from the official Recording rules documentation)

  1. Rules within a rule group run in order, and use the same evaluation timestamp; so later rules can reference the results that earlier rules in the same group have just written in this round. Different groups run concurrently, with no ordering guarantee.
  2. The name of a recording rule must be a valid metric name; the name of an alerting rule must be a valid label value.
  3. If a group has not finished when the next round arrives, the next round is skipped, leaving gaps in the recorded series, and rule_group_iterations_missed_total increases.
  4. Group-level limit: when the number of series produced by a recording rule (or the number of alerts produced by an alerting rule) exceeds the limit, that rule’s entire result for this round is discarded and recorded as an evaluation error. This is the fuse that prevents cardinality explosions.
  5. Group-level query_offset (global default rule_query_offset): shifts the evaluation time back into the past, so that late-arriving data (for example samples from remote write) has arrived before it is computed.
  6. Group-level labels: adds or overrides labels on each rule result in the group; a rule’s own labels takes precedence.

Naming convention: level:metric:operations

PartMeaningExample
levelAfter aggregation labels kept (aggregation level); multiple labels are joined with underscoresjob,job_route,instance
metricthe original metric name; when applying rate/irate to a counter,is removed, _totalmyapp_http_requests
operationsthe operations applied, newest first; sum usually omitted (summing after rate is the default action); ratios are written ratiorate5m,ratio_rate5m,p95_5m

With this convention, you can tell from the name alone: job:myapp_http_errors:ratio_rate5m is “5-minute error ratio aggregated by job”, with no need to open the rule file.

When: when to use / not use

SuitableNot suitable
Aggregations used repeatedly by several dashboard panels / alerts; heavy rate + sum over large numbers of raw series; quantiles and ratios; intermediate layers for SLO calculationsAd hoc queries run only occasionally during troubleshooting; cases where the number of series after aggregation is almost the same as the raw series count (no dimensionality reduction); exploratory queries that need slicing along arbitrary dimensions

Comparison with similar technologies

Prometheus recording rulesGrafana query caching / panel transformsGrafana-managed recording rulesRemote (Mimir/Thanos ruler)
Where results are storedWritten back to the local TSDB, as real seriesNot persisted; only affects this renderingWritten to a specified Prometheus-compatible data sourceWritten to remote storage
Can be referenced by alertsYesNoYesYes
Historical dataOnly exists from the time it is enabled (can be promtool tsdb create-blocks-from rules backfilled)—Only starts from when enabledSame as left
Common misconceptions① “recording rules back-fill historical data”: no, a new rule only produces data from the moment it is loaded. ② “you can also write a recording rule as “first sum then rate ”: rate(sum(...)) is not valid in PromQL at all (rate needs a range vector), and using a subquery to get around this loses counter-reset handling; always do rate rate first, and only then sum sum. ③ “ratio = average of two ratios”: averaging ratios is mathematically wrong; aggregate the numerator and denominator separately, then divide. ④ “the bigger the rule group the better”: rules in a group run in sequence, so a large group lengthens each round and causes skips; split groups by dependency.

Where recording rules sit inside Prometheus

rules/*.ymlLoaded at startup / on SIGHUPone goroutine per grouptriggered on a schedule by interval rule group myapp-recording (t = evaluation time) ① job_route_status:…:rate5m ② job:…requests:rate5m (reads ①) ③ job:…errors:ratio_rate5m (reads ①②) PromQL enginePromQL engineevaluates at time treads the raw series TSDBhead block+ WALreturns an instant vector new series = recordConsumersGrafana panel: job:myapp_http_errors:ratio_rate5malerting rule: … > 0.05 federation / remote_write: send only aggregated seriesFuselimit: entire result is dropped when exceededtimeout: the next round is skipped
query_offset: wait for late data

Figure 1-1: within a group, rules are evaluated in order with the same timestamp; later rules can use the results of earlier rules in this round

Layered recording rules: from raw series to alertsmyapp_http_requests_total{instance × method × route × status}…_duration_seconds_bucket{instance × route × le} Raw series (360 in the example)job_route_status:myapp_http_requests:rate5mjob_le:…_bucket:rate5m Layer 1 (tens of series)job:…requests:rate5mjob:…errors:ratio_rate5mjob:…duration_seconds:p95_5m Layer 2 (one per job)> 0.05 for 2mAlerts / panelsRED panels
SLO (Lesson 6)

Animation

Interactive: how many series does one query read?

Number of panels + alerts using this query

Generate rule

Commands

Core commands and interfacesCommand / interfacePurpose
promtool check rules FILE...DescriptionSyntax and semantic checks
promtool check config prometheus.ymlLint is enabled by default (duplicate rules, etc.); a lint problem exits with code 3. It can also read from stdin.Check the main configuration rule_files also checks
promtool query instant URL 'expr'the rules it referencesRun an instant query from the command line
docker compose kill -s SIGHUP prometheusVerify that the rule expression itself returns the expected resultReload configuration and rules POST /-/reload equivalent to --web.enable-lifecycle (the latter requires
GET /api/v1/rules?type=record)View loaded recording rules, health status and last duration health fields lastError,evaluationTime
prometheus_rule_group_last_duration_seconds,last evaluation duration per group prometheus_rule_group_interval_seconds compared with
prometheus_rule_group_iterations_missed_totalskipped roundsgreater than 0 means the group is too slow
promtool tsdb create-blocks-from rulesBackfill history for a new recording ruleGenerates blocks, then moves them into the data directory; for reference only
cd ~/promlab
docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp-recording.yml
curl -s 'localhost:9090/api/v1/rules?type=record' | jq -r '.data.groups[] | .name as $g | .rules[] | "\($g)\t\(.name)\t\(.health)\t\(.evaluationTime)"'
Checking /etc/prometheus/rules/myapp-recording.yml
  SUCCESS: 6 rules found

myapp-recording	job_route_status:myapp_http_requests:rate5m	ok	0.000612
myapp-recording	job:myapp_http_requests:rate5m	ok	0.000201
…

How to verify:health is ok,lastError is empty. Common mistakes: forgetting to reload after changing rules; promtool checking the host path instead of the path inside the container. Production use: run on every rule file in CI promtool check rules and promtool test rules (Module 2).

Lab 1: write RED recording rules for myapp (about 5 minutes)

First generate some traffic (open a new terminal and keep it running until the end of this lesson; requesting a path that does not exist returns 404, so status has two values):
while true; do
  curl -s -o /dev/null localhost:5000/
  curl -s -o /dev/null localhost:5000/healthz
  curl -s -o /dev/null localhost:5000/nope
  sleep 0.3
done
Write the recording rule file:
groups:
  - name: myapp-recording
    interval: 15s
    rules:
      # Layer 1: keep route and status for drill-down panels
      - record: job_route_status:myapp_http_requests:rate5m
        expr: sum by (job, route, status) (rate(myapp_http_requests_total[5m]))

      # Layer 2: one per job (references the result of the previous rule in the same group in this round)
      - record: job:myapp_http_requests:rate5m
        expr: sum by (job) (job_route_status:myapp_http_requests:rate5m)

      - record: job:myapp_http_errors:rate5m
        expr: sum by (job) (job_route_status:myapp_http_requests:rate5m{status=~"5.."})

      # If there are no 5xx responses, the numerator does not exist; use “or denominator * 0” to fill in 0, so the ratio is 0 rather than “no data”
      - record: job:myapp_http_errors:ratio_rate5m
        expr: |
          (job:myapp_http_errors:rate5m or job:myapp_http_requests:rate5m * 0)
          /
          job:myapp_http_requests:rate5m

      # Latency: aggregate buckets by (job, le) first, then compute the quantile
      - record: job_le:myapp_http_request_duration_seconds_bucket:rate5m
        expr: sum by (job, le) (rate(myapp_http_request_duration_seconds_bucket[5m]))

      - record: job:myapp_http_request_duration_seconds:p95_5m
        expr: histogram_quantile(0.95, job_le:myapp_http_request_duration_seconds_bucket:rate5m)
Check and load:
cd ~/promlab
docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp-recording.yml
docker compose kill -s SIGHUP prometheus
Checking /etc/prometheus/rules/myapp-recording.yml
  SUCCESS: 6 rules found
Compare the raw query with the recording rule (wait 1 minute for the recording rule to accumulate samples):
q(){ curl -s localhost:9090/api/v1/query --data-urlencode "query=$1" | jq -r '.data.result[] | "\(.metric | del(.__name__) | tostring)  \(.value[1])"'; }
q 'sum by (job) (rate(myapp_http_requests_total[5m]))'
q 'job:myapp_http_requests:rate5m'
q 'job:myapp_http_errors:ratio_rate5m'
q 'job:myapp_http_request_duration_seconds:p95_5m'
q 'count({__name__=~"myapp_http_request.*"})'
{"job":"myapp"}  9.83
{"job":"myapp"}  9.83
{"job":"myapp"}  0
{"job":"myapp"}  0.0048
{}  52

The first two values should be essentially the same (the recording rule lags the raw query by at most one evaluation cycle). The error ratio is 0 because 404 is not a 5xx; this is exactly why the team must agree on a single definition of “error”. If the Lesson 1 traffic script (about 5% of requests hit /error) is also running, the ratio will be close to 0.05. The last line is the total number of raw myapp series (including routes such as /, /healthz, /slow and /error).

View rule group health and duration: open http://localhost:9090/rules, or:
q 'prometheus_rule_group_last_duration_seconds{rule_group=~".*myapp-recording"}'
q 'prometheus_rule_group_iterations_missed_total{rule_group=~".*myapp-recording"}'
{"instance":"localhost:9090","job":"prometheus","rule_group":"/etc/prometheus/rules/myapp-recording.yml;myapp-recording"}  0.0017
{"instance":"localhost:9090","job":"prometheus","rule_group":"/etc/prometheus/rules/myapp-recording.yml;myapp-recording"}  0

rule_group The format of the label is file path;group name. The self-scrape job from Lesson 1 is prometheus, and its target is localhost:9090.

Case 1: the overview dashboard takes 40 seconds to open

Problem: a service overview with 30 panels, each running histogram_quantile(sum by (le, route) (rate(..._bucket[5m]))) over 20,000 raw series, with a 7-day time range. Approach: turn layer 1 (bucket rates aggregated by route and le) into recording rules, and point the panels at the recording rules. Configuration: the same two-layer structure as this lab. Results and limits: load time dropped to under 2 seconds; but the recording rules only have data from when they were deployed, so when historical comparison is needed, use promtool tsdb create-blocks-from rules a backfill, or accept a period of “old and new running side by side”.

Case 2: recording rule data “sometimes has gaps”

Problem: the SLO panel shows intermittent gaps. Approach: check prometheus_rule_group_iterations_missed_total and prometheus_rule_group_last_duration_seconds, which showed that one group of 80 rules takes 70 seconds per round, while its interval is 60 seconds. Configuration: split into 4 groups by dependency (groups run concurrently), put the expensive rules in their own group, and raise its interval to 2m. Limits: after splitting, cross-group references read the “previous round” result, which introduces a one-cycle lag.

Case 3: one recording rule produced 500,000 series

Problem: someone wrote sum without (instance) (rate(http_requests_total[5m])), and the raw metric carried user_id labels; the recording rule did not reduce dimensionality and instead duplicated high-cardinality data. Approach: Set limit: 1000, so that when the limit is exceeded the entire rule result is dropped and /rules an error is shown on the page; at the same time change without to explicit by (job, route). Limits:limit is a fuse, not a rate limiter; once it trips, this rule has no data at all, so it must be paired with an alert (Module 8’s PrometheusRuleEvaluationFailures).

Common errors and fixes

"job:myapp_http_requests:rate5m" is not a valid metric name? / invalid recording rule name

Cause:record must be a valid metric name. Colons are allowed (and are reserved for recording rules), but spaces, hyphens and the like are not.

docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp-recording.yml

Fix: use only letters, digits, underscores and colons. Prevention: run promtool in CI.

Recording rule query returns empty: job:myapp_http_errors:ratio_rate5m has no data

Cause: the numerator job:myapp_http_errors:rate5m does not exist at all when there are no 5xx responses,/ so there are no matching series on either side and the result is empty.

q 'job:myapp_http_errors:rate5m'          # empty
q 'job:myapp_http_requests:rate5m'        # has values

Fix: use (numerator or denominator * 0) / denominator; or have the application pre-initialise the 5xx counter (prometheus_client calling it on the labelled counter in .labels(...) exports it with 0).

/rules page shows err: many-to-many matching not allowed

Cause: the label sets of the two vectors do not match (for example the numerator keeps route but the denominator does not), giving a one-to-many / many-to-many match.

Fix: bring both sides sum by (job) to the same level; when different levels are needed, use on(job) group_left (Lesson 1, Module 5).

rule group … evaluation took longer than interval / iterations missed
q 'prometheus_rule_group_last_duration_seconds > on(rule_group) prometheus_rule_group_interval_seconds'

Fix: split the groups, increase the interval, add more specific selectors to expensive expressions, or add another recording-rule layer underneath. --rules.max-concurrent-evals (default 4) only affects concurrency among independent rules; it cannot replace splitting groups.

Rule file was changed, but Prometheus still has the old one

Cause: not reloaded; or the reload failed (when the configuration has errors, Prometheus keeps running with the old configuration).

docker compose kill -s SIGHUP prometheus
docker compose logs prometheus --since 1m | grep -iE 'reload|error'
curl -s localhost:9090/api/v1/query --data-urlencode 'query=prometheus_config_last_reload_successful' | jq -r '.data.result[0].value[1]'

The last line should be 1. Prevention: create an alert for prometheus_config_last_reload_successful == 0 .

Command-line tasks
1. List all rules whose health is not ok, together with their error messages.
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[].rules[] | select(.health != "ok") | "\(.name): \(.lastError)"'
2. Use promtool on the command line to check the current value of a recording rule expression.
docker compose exec prometheus promtool query instant http://localhost:9090 'job:myapp_http_requests:rate5m'
Scenario analysis
A colleague proposes writing one recording rule per route (30 routes → 30 rules) so that “queries run faster”. How would you review this?

Not needed. One sum by (job, route) (...) already outputs 30 series, one per route; at query time, just select with {route="/x"} . Thirty rules would make the rule group longer and raise maintenance cost, and adding a new route would mean changing the rules. The granularity of a recording rule should be decided by “which labels to keep”, not by “the label values”.

Verified teaching videos

▶
Recording Rules in Prometheus with Examples | Best Practices for Prometheus Recording Rules — DevOps Hint
English · recording rule examples and naming best practices, matching the “Theory” page of this module
▶
Recording Rules in Prometheus | Prometheus Recording Rules | Prometheus Tutorial for Beginners — DevOps Hint
English · introductory demo: rule files, loading, viewing in the UI
▶
Understanding Counter Rates and Increases in PromQL | Reset Handling, Extrapolation, Edge Cases — Prometheus Monitoring with Julius | PromLabs
English · counter resets and extrapolation behind “rate first, then sum”

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Scene: a dashboard loading spinner, with an animation of the 360 raw series being read one by one behind it.
Narration: every dashboard refresh re-runs rate and sum across all the raw series.
Shot 2 · 20–45s
Scene: the rule group clock ticks every 15 seconds; three rules light up in turn, and the result is written into the TSDB as a new series.
Narration: a recording rule computes the result in advance and stores it; within the group, rules run in order with the same timestamp.
Shot 3 · 45–70s
Scene: the name job:myapp_http_errors:ratio_rate5m is split into three parts, labelled “aggregation level / metric / operation”.
Narration: the naming convention is level colon metric colon operations, so the name tells you what it computes.
Shot 4 · 70–90s
Scene: the numerator is missing, so the ratio is empty; after adding or denominator * 0, the curve returns to 0.
Narration: compute the ratio by aggregating numerator and denominator separately before dividing, and handle the case where the numerator does not exist.
or pass the quiz with a score of ≥ 70%

Module 2 · Alerting rules: for, labels and annotations

06:00 – 13:00 · Alerting rules decide “when is it an incident”; labels decide “who gets it”; annotations tell the recipient “what to do”
7 minCore animation: alert lifecyclepromtool test rules★★★★★
Learning objectives
  • Write complete alerting rules: alert,expr,for,keep_firing_for,labels,annotations, and use $labels,$value,humanizePercentage and other templates.
  • Accurately describe the Prometheus-side state machine inactive → pending → firing → resolved, and how Prometheus pushes alerts to Alertmanager (how often, with what endsAt).
  • Distinguish “symptom alerts” from “cause alerts”, design severity severity levels, and use promtool test rules to write unit tests for alerts.
Prerequisites: Recording rules from Module 1. Importance:★★★★★

What: an alerting rule is PromQL where “a non-empty result means an alert”

Alerting rules and recording rules are written in the same kind of rule group. On each evaluation round,expr the returned every series returned becomes one active alert instance (distinguished by its label set); an empty result means no alert. So the threshold must be written into the expression itself: job:myapp_http_errors:ratio_rate5m > 0.05 returns a series only when the ratio exceeds 5%.

groups:
  - name: myapp-alerts
    interval: 15s
    labels:
      env: lab                       # group-level label: added to each rule result in the group
    rules:
      - alert: MyappHighErrorRate
        expr: |
          job:myapp_http_errors:ratio_rate5m > 0.05
          and job:myapp_http_requests:rate5m > 0.1      # no alert when traffic is too low
        for: 2m                      # must hold for 2 minutes before firing
        keep_firing_for: 1m          # keep firing for another minute after the condition clears, to prevent flapping
        labels:
          severity: warning
          service: myapp
        annotations:
          summary: "myapp 5xx ratio too high ({{ $labels.job }})"
          description: "5xx ratio over the past 5 minutes is {{ $value | humanizePercentage }}, threshold 5%."
          runbook_url: "https://runbooks.example.com/myapp/high-error-rate"

Why: why have for, labels and annotations

  • for: avoids alerting on momentary spikes. When the expression first returns a series, the alert enters pending; if it keeps returning on every subsequent round and accumulates for the for duration, it becomes firing. As soon as one round in between returns nothing, pending is cleared and the timer starts over.
  • keep_firing_for: once the condition clears, keep an already-firing alert firing for a while, avoiding “recovery → re-trigger” flapping and “false recovery” caused by brief gaps in the data.
  • Labels: Alertmanager only looks at labels for routing, grouping, inhibition and silences (Module 3). severity,service,team are the most common basis for routing. Label values can be templated, but do not put $value into labels— a changing value creates new alert instances.
  • Annotations: information for humans; not used for routing: summary (one-line summary),description (details and current value),runbook_url (runbook),dashboard (dashboard link).

How: the Prometheus-side state machine and sending mechanism

StateConditionWhere visible
inactivethe expression does not return this label set/alerts green on the page
pendinghas returned, but the duration is < forALERTS{alertstate="pending"} = 1; does not send to Alertmanager
firingduration ≥ for (or for: 0 the first round ofALERTS{alertstate="firing"} = 1; sent to Alertmanager
resolvedafter firing, the expression no longer returns (and keep_firing_for has elapsed)Prometheus keeps sending alerts marked with endsAt the “resolved” state (official source: resolved instances are kept for 15 minutes)
  • After each evaluation round, firing alerts and newly resolved alerts are (re)sent. The resend interval is at least --rules.alert.resend-delay (default 1m). Each firing alert sent carries endsAt = now + 4 × max(resend-delay, group interval): if Prometheus crashes and stops renewing, Alertmanager will treat the alert as resolved once endsAt that time is reached.
  • Prometheus stores the for progress of the pending timer in the ALERTS_FOR_STATE series, so it can be restored after a restart (--rules.alert.for-outage-tolerance default 1h,--rules.alert.for-grace-period default 10m).
  • Before sending, Prometheus adds external_labels, and applies alert_relabel_configs.

When: what kind of alerts to write

TypeExampleRecommendation
Symptom (user-visible)error ratio, latency, availability (SLO)Preferred; may page (call on-call)
Cause (internal component)Redis unavailable, disk about to fill, certificate about to expireUsually warning / ticket; must be actionable; use inhibition to avoid duplicating symptom alerts
Monitoring itselftarget down, rule failure, notification failure, WatchdogMust exist; otherwise “no alerts” cannot be told apart from “all is well” and “monitoring is broken” (Module 8)

Comparison with similar technologies

Prometheus alerting rulesGrafana-managed alerts (Module 5)Cloud vendor metric alerts
Where evaluation happensPrometheus rule managerGrafana scheduler (queries the data source)Cloud service
LanguagePromQLany data source query + expressions (Reduce/Math/Threshold)Vendor-specific
Stateinactive/pending/firingNormal/Pending/Alerting/Recovering/NoData/Errorvaries
Version controlYAML files + promtool unit testsprovisioning files / Terraform / APIIaC
Common misconceptions① “pending alerts are sent to Alertmanager”: no, only firing alerts are sent. ② “for: 5m means the first evaluation happens only after 5 minutes”: evaluation still follows the group interval; for only determines how long the condition must hold continuously before becoming firing. ③ “the alert threshold is written in Alertmanager”: Alertmanager does not look at metric values, only at labels. ④ “absent() can monitor all targets”: absent(up{job="myapp"}) only returns 1 when all matching series are absent; to detect a single instance disappearing, use up == 0 or compare against an expected list. ⑤ “putting {{ $value }} into summary shows the current value”: it is the value at the moment of evaluation, so the value in a notification may be out of date; the dashboard is authoritative.

Full path of an alert from rule to notification

Prometheus (rule manager, one round every 15s) inactive pending firing resolved (keeps sending for 15 minutes) expr non-empty≥ for POST /api/v2/alerts Alertmanager deduplicationby fingerprint routing + groupinggroup_by group_waitinitial wait inhibitioninhibit_rules silencesilences time intervalmute/active notification log deduplication → send (retry on failure) → group_interval / repeat_interval receiverwebhook · email · TeamsSlack · PagerDuty Key timing parameters (lab values / defaults) rule group interval: 15s / global.evaluation_interval (default 1m) for: 2m / 0s keep_firing_for: 1m / 0s --rules.alert.resend-delay: default 1m group_wait 10s / 30s · group_interval 30s / 5m · repeat_interval 1h / 4h
Figure 2-1: Prometheus is responsible for “deciding”, Alertmanager for “notifying”; pending never leaves Prometheus

Where alert labels come from

labels from the expr resultjob="myapp"(labels kept after aggregation) rule labelsseverity="warning"service="myapp" group labels / external_labelsenv="lab"+ alertname (automatic) alert instance label setalertname=MyappHighErrorRatejob=myapp env=labseverity=warning service=myapp→ fingerprint (unique identifier)
Figure 2-2: the label set uniquely identifies one alert instance; annotations do not take part in the fingerprint

Core animation: the full lifecycle of one alert

Scenario: the 5xx ratio of myapp starts rising in round 3 and falls back after about 2.5 minutes. The rule group evaluates every 15 seconds (one cell = one round), with a 5% threshold. Step through it and watch the Prometheus state, the Alertmanager grouping timers and the notifications received by the receiver. You can switch for,keep_firing_for, and also “maintenance silence” and “upstream RedisDown alert (inhibition source)”. The timing is simulated using this lesson’s lab parameters (group_wait 10s, group_interval 30s).

inactivependingfiringresolvednotification sent
Rule evaluationratio=— Stateinactive Send to AM— Grouping— Inhibition— Silence— Notification— Receiver— t = 0s PrometheusAlertmanagerwebhook
Click “Play” or “Step”.

Core commands and interfaces

Command / interfacePurposeNotes
promtool check rulesCheck alerting rule syntax and templatesSyntax errors in annotation templates are also caught
promtool test rules TEST.ymlUnit tests for alerts and expressions--run REGEX run only some test groups; --junit FILE output a JUnit report; since 3.16 it prints the test file names
GET /api/v1/alertsCurrent pending / firing alertsfields state,activeAt,value
GET /api/v1/rules?type=alertalerting rules and their instancesincluding duration (for),keepFiringFor
ALERTS{alertname="…"}synthetic series of alert statelabels alertstate=pending/firing, value 1
ALERTS_FOR_STATEfor progress (value is the activeAt timestamp)used to restore state after a restart
prometheus_notifications_sent_total / …_dropped_total / …_errors_totalstatistics on sending to Alertmanagergrowing dropped/errors counters indicate a problem on the Prometheus → AM link
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | "\(.labels.alertname)\t\(.state)\t\(.activeAt)\t\(.value)"'
curl -s 'localhost:9090/api/v1/rules?type=alert' | jq -r '.data.groups[].rules[] | "\(.name)\tfor=\(.duration)s\tstate=\(.state)\thealth=\(.health)"'
MyappDown	pending	2026-11-15T14:02:30.112Z	0
MyappDown	for=60s	state=pending	health=ok
MyappTargetMissing	for=120s	state=inactive	health=ok
MyappHighErrorRate	for=120s	state=inactive	health=ok
…

Lab 2: myapp alerting rules + unit tests + real triggering (about 7 minutes)

Write the alerting rules (referencing the Module 1 recording rules):
groups:
  - name: myapp-alerts
    interval: 15s
    labels:
      env: lab
    rules:
      - alert: MyappDown
        expr: up{job="myapp"} == 0
        for: 1m
        labels:
          severity: critical
          service: myapp
        annotations:
          summary: "myapp instance {{ $labels.instance }} cannot be scraped"
          description: "Prometheus has been unable to scrape /metrics from {{ $labels.instance }} for 1 minute."
          runbook_url: "https://runbooks.example.com/myapp/down"

      - alert: MyappTargetMissing
        expr: absent(up{job="myapp"})
        for: 2m
        labels:
          severity: critical
          service: myapp
        annotations:
          summary: "No targets with job=myapp found in Prometheus"
          description: "Check whether service discovery / scrape configuration was accidentally deleted."

      - alert: MyappHighErrorRate
        expr: |
          job:myapp_http_errors:ratio_rate5m > 0.05
          and job:myapp_http_requests:rate5m > 0.1
        for: 2m
        keep_firing_for: 1m
        labels:
          severity: warning
          service: myapp
        annotations:
          summary: "myapp 5xx ratio too high ({{ $labels.job }})"
          description: "5xx ratio over the past 5 minutes is {{ $value | humanizePercentage }}, threshold 5%."
          runbook_url: "https://runbooks.example.com/myapp/high-error-rate"

      - alert: MyappHighErrorRate
        expr: |
          job:myapp_http_errors:ratio_rate5m > 0.20
          and job:myapp_http_requests:rate5m > 0.1
        for: 2m
        keep_firing_for: 1m
        labels:
          severity: critical
          service: myapp
        annotations:
          summary: "myapp 5xx ratio critically high ({{ $labels.job }})"
          description: "5xx ratio over the past 5 minutes is {{ $value | humanizePercentage }}, threshold 20%."
          runbook_url: "https://runbooks.example.com/myapp/high-error-rate"

      - alert: MyappHighLatencyP95
        expr: job:myapp_http_request_duration_seconds:p95_5m > 0.5
        for: 5m
        labels:
          severity: warning
          service: myapp
        annotations:
          summary: "myapp p95 latency above 500ms"
          description: "Current p95 is {{ $value | humanizeDuration }}."

      - alert: MyappRedisUnavailable
        expr: max by (job, instance) (myapp_redis_up) == 0
        for: 1m
        labels:
          severity: warning
          service: myapp
        annotations:
          summary: "myapp reports Redis unavailable ({{ $labels.instance }})"
          description: "myapp_redis_up has been 0 for 1 minute; counting functionality is degraded."

      - alert: RedisDown
        expr: redis_up{job="redis"} == 0
        for: 1m
        labels:
          severity: critical
          service: redis
        annotations:
          summary: "Redis unavailable (exporter cannot connect)"
          description: "redis_exporter {{ $labels.instance }} reports redis_up=0."

Same-name alert MyappHighErrorRate appears twice (warning 5% / critical 20%); Module 3 will use an inhibition rule so that warning is no longer notified separately while critical is present. RedisDown depends on the redis_exporter redis_up metric.

Write unit tests: use synthetic data to verify that “at a 30% error rate, warning and critical fire together” and that “MyappDown fires after myapp has been stopped for 1 minute”.
rule_files:
  - ../rules/myapp-recording.yml
  - ../rules/myapp-alerts.yml

evaluation_interval: 15s

tests:
  - name: error-ratio-30pct
    interval: 15s
    input_series:
      # every 15s adds 21 200s and 9 500s → 2 req/s, 30% error ratio
      - series: 'myapp_http_requests_total{job="myapp",instance="myapp:5000",method="GET",route="/",status="200"}'
        values: '0+21x80'
      - series: 'myapp_http_requests_total{job="myapp",instance="myapp:5000",method="GET",route="/",status="500"}'
        values: '0+9x80'
    alert_rule_test:
      - eval_time: 1m            # condition is met, but for: 2m has not elapsed → still pending, not counted as firing
        alertname: MyappHighErrorRate
        exp_alerts: []
      - eval_time: 10m
        alertname: MyappHighErrorRate
        exp_alerts:
          - exp_labels: {severity: warning, service: myapp, env: lab, job: myapp}
            exp_annotations:
              summary: "myapp 5xx ratio too high (myapp)"
              description: "5xx ratio over the past 5 minutes is 30%, threshold 5%."
              runbook_url: "https://runbooks.example.com/myapp/high-error-rate"
          - exp_labels: {severity: critical, service: myapp, env: lab, job: myapp}
            exp_annotations:
              summary: "myapp 5xx ratio critically high (myapp)"
              description: "5xx ratio over the past 5 minutes is 30%, threshold 20%."
              runbook_url: "https://runbooks.example.com/myapp/high-error-rate"
    promql_expr_test:
      - expr: round(job:myapp_http_errors:ratio_rate5m, 0.01)   # avoids floating-point rounding error
        eval_time: 10m
        exp_samples:
          - labels: '{job="myapp"}'
            value: 0.3

  - name: myapp-down
    interval: 15s
    input_series:
      - series: 'up{job="myapp",instance="myapp:5000"}'
        values: '1 1 1 0x20'       # scrape fails from the 45s mark
    alert_rule_test:
      - eval_time: 1m
        alertname: MyappDown
        exp_alerts: []             # only 15s in, still pending
      - eval_time: 2m
        alertname: MyappDown
        exp_alerts:
          - exp_labels: {severity: critical, service: myapp, env: lab, job: myapp, instance: "myapp:5000"}
            exp_annotations:
              summary: "myapp instance myapp:5000 cannot be scraped"
              description: "Prometheus has been unable to scrape /metrics from myapp:5000 for 1 minute."
              runbook_url: "https://runbooks.example.com/myapp/down"
Run tests and checks:
cd ~/promlab
docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp-alerts.yml
docker compose exec -w /etc/prometheus/tests prometheus promtool test rules myapp-alerts_test.yml
Checking /etc/prometheus/rules/myapp-alerts.yml
  SUCCESS: 7 rules found

Unit Testing:  myapp-alerts_test.yml
  SUCCESS

Relative paths in rule_files are resolved relative to the directory containing the test file, so use -w to enter the tests directory. humanizePercentage Values are formatted with %.4g (see source template/template.go), so 0.30000000000000004 also displays as “30%”; for numeric comparisons use round() round() or a top-level fuzzy_compare: true tolerance to avoid floating-point rounding errors. When a test fails, the output prints the labels and annotations actually produced.

Load and trigger for real: stop myapp and observe pending → firing → notification.
docker compose kill -s SIGHUP prometheus
docker compose stop myapp
for i in $(seq 1 8); do
  sleep 15
  curl -s localhost:9090/api/v1/alerts | jq -r --arg t "$(date +%T)" '.data.alerts[] | select(.labels.alertname=="MyappDown") | "\($t) \(.state)"'
done
docker compose logs --no-log-prefix webhook | tail -n 2
14:02:31 pending
14:02:46 pending
14:03:01 pending
14:03:16 pending
14:03:31 firing
14:03:46 firing
…
14:03:42 POST /default receiver=default-webhook status=firing alerts=1 [MyappDown] groupLabels={"alertname": "MyappDown"}

The moment pending first appears depends on when the scrape failure is detected (scrape interval 15s) plus the rule evaluation time; from firing until the webhook receives the notification there is also a delay of group_wait (10s).

Recover and observe resolved:
docker compose start myapp
sleep 60
docker compose logs --no-log-prefix webhook | tail -n 1
curl -s localhost:9090/api/v1/query --data-urlencode 'query=ALERTS{alertname="MyappDown"}' | jq '.data.result | length'
14:05:12 POST /default receiver=default-webhook status=resolved alerts=1 [MyappDown] groupLabels={"alertname": "MyappDown"}
0

The webhook defaults to send_resolved: true, so a resolved notification is received; it is sent at the next group_interval (30s) boundary. After the alert resolves, ALERTS the series is marked stale and queries return empty.

(Optional) using the Lesson 1 /error route to trigger the error-rate alert for real: in addition to the traffic generator, send about 2 req/s to the route that returns 500 /error, after about 3 minutes the warning (> 5%) and critical (> 20%) alerts enter firing, one after the other:
timeout 300 bash -c 'while true; do curl -s -o /dev/null localhost:5000/error; sleep 0.5; done' &
sleep 200
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | select(.labels.alertname=="MyappHighErrorRate") | "\(.labels.severity)\t\(.state)\t\(.value)"'
warning	firing	2.0e-01
critical	firing	2.0e-01

Actual ratio = 2 ÷ (traffic generator rate + 2). If only warning enters firing, total traffic is high and the ratio has not exceeded 20%. After stopping injection for 5 minutes (the rate window slides out), the alert recovers.

Case 1: woken at 3 a.m. by “CPU 85%”, yet users noticed nothing

Problem: Many cause-type alerts (CPU, memory, single Pod restarts) were all set to page, causing on-call fatigue while real incidents were overlooked. Approach: Re-tiered on a “symptoms first” basis: only user-impacting error ratio / latency / availability is severity=critical (page); cause-type alerts were downgraded to warning (business-hours tickets). Configuration: the lab’s MyappHighErrorRate + Alertmanager routing (Module 3). Limits: Symptom alerts fire somewhat later, so they must be combined with dashboards and cause alerts during troubleshooting.

Case 2: alerts that frequently “resolve and re-fire”

Problem: The error ratio hovered around the threshold, producing 20 firing/resolved pairs in one hour. Approach: Add keep_firing_for: 5m, change the ratio window from 1m to 5m, and split the threshold into warning and critical tiers. Limits:keep_firing_for this also delays notifications for genuine recoveries; do not base SLO calculations on ALERTS series.

Case 3: after a Prometheus restart, all alerts “wait for for” again

Problem: When upgrading Prometheus,for: 1h the capacity alerts for it had their timers reset. Approach: Confirm that the data directory is persisted (ALERTS_FOR_STATE stored in the TSDB), and the downtime is less than --rules.alert.for-outage-tolerance (default 1h). Limits: On recovery, Prometheus guarantees it waits at least another for-grace-period (default 10m) before moving to firing.

Common errors and fixes

Alert stays pending and never fires

Cause: the condition for is unmet for one round during the period (flapping), so pending is reset and the count restarts; or for the for duration is longer than the outage.

curl -s localhost:9090/api/v1/query_range --data-urlencode 'query=ALERTS{alertname="MyappHighErrorRate"}' \
  --data-urlencode "start=$(date -d '-30 min' +%s)" --data-urlencode "end=$(date +%s)" --data-urlencode 'step=15' | jq '.data.result[].values | length'

Fix: plot the expr itself in the Graph view to see whether it flaps around the threshold; lengthen the ratio window, lower for, or use keep_firing_for (only effective for alerts already firing).

Prometheus shows firing, but Alertmanager / the receiver does not receive it
curl -s localhost:9090/api/v1/alertmanagers | jq '.data'
curl -s localhost:9090/api/v1/query --data-urlencode 'query=rate(prometheus_notifications_errors_total[5m]) or rate(prometheus_notifications_dropped_total[5m])' | jq '.data.result'
docker compose logs prometheus --since 10m | grep -i notif

Causes and fixes:activeAlertmanagers is empty → check alerting.alertmanagers; errors growing → network / address / TLS; Alertmanager received it but did not notify → check routing, inhibition and silences in Module 3.

template: __alert_MyappHighErrorRate:1: function "humanizepercentage" not defined

Cause: Template function names are case-sensitive; the correct name is humanizePercentage. promtool check rules will catch this kind of error.

Fix: correct the function name; commonly used functions: humanize,humanize1024,humanizeDuration,humanizePercentage,humanizeTimestamp,printf.

The same alert is received many times, with a different value each time

Cause: putting {{ $value }} into labels, so every change in value creates a new label set (a new alert instance).

Fix: keep the value only in annotations.

promtool test rules: expected alerts … got … (labels mismatch)

Cause:exp_labels must include all of the alert’s all labels (except __name__ and alertname), including group-level labels and labels kept from the expr result; annotations must also match exactly.

Fix: read the “got” part of the failure output and add the missing labels; for ratio-type values, use fuzzy_compare: true.

Command-line tasks
1. Run only the test group named myapp-down in the test file, and output a JUnit report.
docker compose exec -w /etc/prometheus/tests prometheus promtool test rules --run 'myapp-down' --junit /tmp/junit.xml myapp-alerts_test.yml
2. Query the total time (in minutes) each alert spent in firing over the past hour.
sum by (alertname) (count_over_time(ALERTS{alertstate="firing"}[1h])) * 15 / 60

Estimate using a 15-second evaluation interval (each sample represents 15 seconds).

Scenario analysis
myapp has 3 instances, one of which is down. absent(up{job="myapp"}) Will it alert? What should be used?

No. absent It only returns a result when all matching series are absent; the downed instance still has up=0 series. For single-instance failures, use up{job="myapp"} == 0; use the job-level one only when the whole job disappears from service discovery absent. To go further, alert on a ratio: sum(up{job="myapp"}) / count(up{job="myapp"}) < 0.7, to avoid paging on single-instance flapping.

Verified teaching videos

▶
Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output) — DevOps Simplified
English · pending / firing states and promtool unit tests, corresponding one-to-one with this module’s labs
▶
Alerting Rules in Prometheus | Prometheus Tutorial for Beginners | Prometheus Alertmanager Tutorial — DevOps Hint
English · introduction to alerting rule files and Alertmanager
▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
English · one of the Prometheus authors covers common mistakes, including alerting pitfalls

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Scene: the error-ratio curve crosses the 5% red line; the rule block turns from green to yellow (pending), and the timer starts.
Narration: the expression first returns a result; the alert enters pending, and the for timer starts.
Shot 2 · 20–45s
Scene: the timer reaches 2 minutes, the block turns red (firing), and an envelope flies to Alertmanager.
Narration: the alert only fires after the for duration has been met continuously; only firing alerts are sent to Alertmanager.
Shot 3 · 45–75s
Scene: Alertmanager’s grouping box collects the envelopes; once the group_wait hourglass runs out, the notification is delivered to the receiver.
Narration: Alertmanager first waits to group, then checks inhibition and silences, and finally sends the notification.
Shot 4 · 75–100s
Scene: the curve falls; after the keep_firing_for timer, the block turns green, and the resolved notification is sent at the next group_interval.
Narration: once the condition clears, the alert becomes resolved, and the receiver gets the recovery notification.
or score ≥ 70% on the quiz

Module 3 · Alertmanager: routing, grouping, inhibition and silences

13:00 – 21:00 · One incident produces 50 alerts, but the on-call person should receive only 1 useful notification
8 minAlertmanager v0.35.0amtool★★★★★
Learning objectives
  • Read and write a routing tree: matching rules (matchers), depth-first,continue, parameter inheritance (receiver,group_by, three timers).
  • Explain precisely group_by,group_wait,group_interval,repeat_interval how they decide “when to send, how many to send, and how often to resend”.
  • Configure inhibition rules (source_matchers / target_matchers / equal), silences (UI / amtool / API) and time intervals (mute_time_intervals / active_time_intervals), and know the differences among the three.
  • Use amtool check-config,amtool config routes test,amtool silence to manage configuration, and understand how the Alertmanager high-availability cluster works.
Prerequisites: Alert labels from Module 2. Importance:★★★★★

What: Alertmanager does five things

FunctionBasisEffect
Deduplicationthe fingerprint of the alert label setwhen several Prometheus servers (an HA pair) send the same alert, it counts as one
Routingrouting tree + label matchingdecides which receiver gets it, and which grouping and timing parameters apply
Groupinggroup_byalerts in the same group are merged into one notification
Inhibitioninhibit_rules (config file)when one alert is present, other alerts are automatically muted
Silences / time intervalssilence (created at runtime),time_intervals (config file)do not notify within a specified time period

How the routing tree matches

  • Every alert enters from the root route (the root route matches all alerts and cannot have matchers), and then depth-first traversal of the child routes.
  • If all matchers of a child route are satisfied, it is a “match”; Alertmanager continues looking for more specific routes among its children, and if none are more specific, it stops at the current node.
  • By default, it stops at the first matching sibling node; when continue: true is set, after a match it still tries the following sibling nodes, so one alert can be sent to several receivers.
  • Child routes that do not specify receiver,group_by,group_wait,group_interval,repeat_interval are inherited from the parent node; mute_time_intervals / active_time_intervals is not inherited.
  • matcher syntax: alertname="X",severity=~"critical|warning",team!="db",env!~"dev.*". The old match/match_re form is deprecated; new configuration should use matchers uniformly.

Three timers (official defaults)

ParameterDefaultMeaningThis lab
group_wait30sOne new group after it appears, how long to wait before sending the first notification (so that alerts firing together end up in the same notification). Alerts resolved during the waiting period do not trigger a notification10s
group_interval5mafter the group sends its first notification, it is checked at this interval: if a new alert joins or an alert resolves, an updated notification is sent. It is also the timeout context for the notification request30s
repeat_interval4hhow long to wait before repeating the notification when the group contents have not changed. It is evaluated at each group_interval check, so it should be an integer multiple of group_interval (otherwise rounded up); do not exceed --data.retention (default 120h)1h

group_by determines the grouping key: ['alertname'] merges all same-name alerts from all instances into one; ['...'] is a special value meaning “group by all labels” (equivalent to no grouping).

Differences among inhibition, silences and time intervals

Inhibition inhibit_rulesSilence silenceTime interval time_intervals
Where definedConfig fileAt runtime (UI / amtool / API); stored in the Alertmanager data directory and synchronised across the clusterConfig file; referenced on routes
Trigger conditionan alert matching the source exists firing alert, and equal have the same label valuesalert labels match the silence’s matchers and it is within its validity periodcurrent time falls within the interval (if no location is given, UTC is used)
Typical usesuppress downstream symptoms when an upstream failure occurs; suppress warning when a critical with the same name existsplanned maintenance, known issues being handleddo not notify for warnings outside working hours; page only during on-call hours
Whether the alert remains visiblevisible, marked as inhibitedvisible, marked as silencedvisible; the route sends no notification

Two details of inhibition (official docs): a missing label is equivalent to an empty value, so equal if a label in the equal list is missing on both sides, inhibition still applies; an alert that matches both the source side and the target side is not inhibited by an alert that matches both sides the same way (including itself), but it is best to keep source and target non-overlapping.

High availability: Alertmanager cluster

Multiple Alertmanagers synchronise via gossip (default port 9094,--cluster.peer), synchronising silences and the notification log; Prometheus must send alerts to every instance (do not put it behind a load balancer). Each instance evaluates and prepares notifications, waits a different amount of time depending on its position in the cluster before sending, and uses the notification log to avoid duplicates. This lab runs a single instance, using --cluster.listen-address= to disable the cluster.

Common misconceptions① “repeat_interval: 5m will get a reminder every 5 minutes”: it is also limited by group_interval constraints, and is only evaluated at group_interval check points. ② “silences delete alerts”: no; the alert still exists and can still be queried, it just does not notify. ③ “an inhibition rule can match an alert that is already silenced as its source”: the source must be a firing alert; a silenced alert is still firing, so can act as an inhibition source. ④ “changing alertmanager.yml takes effect automatically”: it requires POST /-/reload or SIGHUP; if the config has errors, the old config is kept.

Routing tree for this lesson

route (root) → default-webhookgroup_by: [alertname, env, service]10s / 30s / 1h ① Watchdogalertname="Watchdog"→ heartbeatrepeat 1m ② audit (continue)severity=~"critical|warning"→ audit-logcontinue: true ③ severityseverity="critical"→ oncall-criticalgroup_wait 5s ④ myapp warningservice="myapp"severity="warning"→ team-myapp ⑤ batchservice="batch"→ team-batchmute: offhours Example: MyappHighErrorRate{severity="critical",service="myapp"} ① no match → ② match, send to audit-log, continue ③ match → send to oncall-critical, stop (no continue) Result: audit-log + oncall-critical: two receivers An alert that matches no child route → root route default-webhook Inhibition rules RedisDown (firing) ⟶ suppresses MyappRedisUnavailable, equal: [env] severity=critical ⟶ suppresses severity=warning equal: [alertname, env, service] (only notify the more severe one of same-name alerts)
Figure 3-1: depth-first, stop at the first match,continue: true to let matching continue

Grouping timer timeline (same group)

0s10s40s70s100s1h10s Alert A arrivesnew group B arrives (6s) Notification #1: A+B(group_wait 10s) C arrives (25s) Notification #2: A+B+C(group_interval) no change, not sent no change, not sent repeat_interval reached: resend
Figure 3-2: group_wait collects the first batch of alerts; afterwards each group_interval sends only when something has changed; when nothing has changed, repeat_interval controls resending

Interactive: routing tree simulator

Select or edit an alert’s labels, click “Route”, and see its matching path in this lesson’s routing tree, the final receiver, the grouping key, and whether it will be inhibited or silenced. The simulator implements =,!=,=~,!~ four matcher types (regular expressions are automatically wrapped with ^…$ anchors, consistent with Alertmanager).

Choose a preset or enter labels.

amtool and API

CommandPurposeNotes
amtool check-config FILEValidate configuration and templatesoutputs the number of receivers, inhibition rules and templates
amtool config routes [show] --config.file=FDisplay routing as a treealso available as --alertmanager.url reads the running configuration
amtool config routes test --config.file=F k=v ...Given labels, output the matching receiver--tree show the path; --verify.receivers=a,b exit code 1 when it does not match (suitable for CI)
amtool alert query [matchers]Query current alerts-o extended show all labels; -s include silences; -i include inhibition
amtool alert add k=v ... --annotation=summary=...Manually send a test alertequivalent to POST /api/v2/alerts
amtool silence add matchers -d 1h -c "reason" -a authorcreate a silencereturns the silence ID
amtool silence query [-q] / silence expire IDQuery / expire a silence early-q outputs only IDs, for bulk expiry
amtool template render --template.glob=... --template.text=...Render notification templates offlineUsed in Module 4
POST /-/reloadReload configurationAlertmanager always provides this endpoint
GET /api/v2/alerts,/api/v2/alerts/groups,/api/v2/silences,/api/v2/statusREST APIv0.34.2 onward, CORS headers are not sent by default
AM="docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093"
$AM config routes
$AM alert query -o extended
$AM silence query
Routing tree:
└── default-route  receiver: default-webhook
    ├── {alertname="Watchdog"}  receiver: heartbeat
    ├── {severity=~"critical|warning"}  continue: true  receiver: audit-log
    ├── {severity="critical"}  receiver: oncall-critical
    ├── {service="myapp",severity="warning"}  receiver: team-myapp
    └── {service="batch"}  receiver: team-batch
Alertname  Starts At  Summary  State
ID  Matchers  Ends At  Created By  Comment

The output columns and format depend on the actual version. amtool It can also be written into ~/.config/amtool/config.yml (alertmanager.url: http://localhost:9093,require-comment: true), saving you from passing it on every call.

Lab 3: routing tree, inhibition and silences (about 8 minutes)

Replace the Alertmanager configuration (all receivers point to the local webhook, distinguished by different paths):
global:
  resolve_timeout: 5m

route:
  receiver: default-webhook
  group_by: ['alertname', 'env', 'service']
  group_wait: 10s
  group_interval: 30s
  repeat_interval: 1h
  routes:
    - receiver: heartbeat
      matchers: ['alertname="Watchdog"']
      group_wait: 0s
      group_interval: 1m
      repeat_interval: 1m
    - receiver: audit-log
      matchers: ['severity=~"critical|warning"']
      continue: true
    - receiver: oncall-critical
      matchers: ['severity="critical"']
      group_wait: 5s
    - receiver: team-myapp
      matchers: ['service="myapp"', 'severity="warning"']
    - receiver: team-batch
      matchers: ['service="batch"']
      mute_time_intervals: ['offhours']

inhibit_rules:
  - name: redis-down-mutes-myapp-redis-symptom
    source_matchers: ['alertname="RedisDown"']
    target_matchers: ['alertname="MyappRedisUnavailable"']
    equal: ['env']
  - name: critical-mutes-same-warning
    source_matchers: ['severity="critical"']
    target_matchers: ['severity="warning"']
    equal: ['alertname', 'env', 'service']

time_intervals:
  - name: offhours
    time_intervals:
      - weekdays: ['saturday', 'sunday']
        location: 'UTC'
      - weekdays: ['monday:friday']
        times:
          - {start_time: '00:00', end_time: '13:00'}
          - {start_time: '23:00', end_time: '24:00'}
        location: 'UTC'

receivers:
  - name: default-webhook
    webhook_configs: [{url: 'http://webhook:5001/default'}]
  - name: heartbeat
    webhook_configs: [{url: 'http://webhook:5001/heartbeat'}]
  - name: audit-log
    webhook_configs: [{url: 'http://webhook:5001/audit'}]
  - name: oncall-critical
    webhook_configs: [{url: 'http://webhook:5001/critical'}]
  - name: team-myapp
    webhook_configs: [{url: 'http://webhook:5001/myapp-warning'}]
  - name: team-batch
    webhook_configs: [{url: 'http://webhook:5001/batch'}]

Time intervals use UTC: the official Alertmanager image is based on busybox,which may not ship a time zone database, so writing America/Toronto names like this may cause configuration loading to fail (see “Troubleshooting”). The offhours example above is equivalent to 6 p.m. to 8 a.m. in Toronto (UTC−5).

Validate, test routing, reload:
cd ~/promlab
AMX="docker compose exec alertmanager amtool"
$AMX check-config /etc/alertmanager/alertmanager.yml
$AMX config routes test --config.file=/etc/alertmanager/alertmanager.yml --tree alertname=MyappHighErrorRate severity=critical service=myapp env=lab
$AMX config routes test --config.file=/etc/alertmanager/alertmanager.yml alertname=MyappRedisUnavailable severity=warning service=myapp env=lab
$AMX config routes test --config.file=/etc/alertmanager/alertmanager.yml --verify.receivers=default-webhook alertname=Foo
curl -s -XPOST localhost:9093/-/reload && echo reloaded
Checking '/etc/alertmanager/alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 2 inhibit rules
 - 6 receivers
 - 0 templates

Matching routes:
.
├── default-route
│   ├── {severity=~"critical|warning"}  continue: true  receiver: audit-log
│   └── {severity="critical"}  receiver: oncall-critical

audit-log,oncall-critical
audit-log,team-myapp
default-webhook
reloaded

--tree The rendering format of the tree may differ slightly between versions; the key is the receiver list on the last line.

Observe inhibition: stop Redis; the two cause alerts will fire together, but MyappRedisUnavailable is RedisDown inhibited.
docker compose stop redis
sleep 100
AM="docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093"
$AM alert query -i -o extended | grep -E 'RedisDown|MyappRedisUnavailable'
curl -s localhost:9093/api/v2/alerts | jq -r '.[] | "\(.labels.alertname)\t\(.status.state)\tinhibitedBy=\(.status.inhibitedBy)"'
docker compose logs --no-log-prefix webhook --since 3m | grep -E 'Redis'
RedisDown              active      inhibitedBy=[]
MyappRedisUnavailable  suppressed  inhibitedBy=["3f2a…"]
14:21:07 POST /audit receiver=audit-log status=firing alerts=1 [RedisDown] groupLabels={"alertname": "RedisDown", "env": "lab", "service": "redis"}
14:21:07 POST /critical receiver=oncall-critical status=firing alerts=1 [RedisDown] groupLabels={…}

The webhook only receives RedisDown (audit + critical, two copies), with no MyappRedisUnavailable. Note: the Lesson 1 myapp_redis_up indicates “whether the most recent Redis access succeeded”; it is refreshed on requests and scrapes, so the traffic generator must keep running.

Maintenance silence: suppose you need to maintain Redis for 30 minutes; first silence RedisDown, then check whether notifications stop:
SID=$($AM silence add alertname=RedisDown env=lab -d 30m -c "Redis planned maintenance (lab 3)" -a lab-user)
echo "silence id: $SID"
$AM silence query
$AM alert query -s | grep RedisDown
silence id: 6c1d4a2e-5b8f-4e0a-9d61-2f7b0c3e9a11
ID                                    Matchers                           Ends At                  Created By  Comment
6c1d4a2e-5b8f-4e0a-9d61-2f7b0c3e9a11  alertname="RedisDown" env="lab"  2026-11-15 14:53:12 UTC  lab-user    Redis planned maintenance (lab 3)
RedisDown  2026-11-15 14:19:52 UTC  Redis unavailable (exporter cannot connect)  suppressed

The silenced RedisDown still can act as an inhibition source, so MyappRedisUnavailable remains inhibited. Silencing an upstream alert does not make downstream symptoms “pop up”.

Recovery and clean-up:
docker compose start redis
$AM silence expire "$SID"
sleep 90
docker compose logs --no-log-prefix webhook --since 2m | grep resolved
14:24:37 POST /audit receiver=audit-log status=resolved alerts=1 [RedisDown] …
14:24:37 POST /critical receiver=oncall-critical status=resolved alerts=1 [RedisDown] …

Case 1: 400 notifications from a single network fault

Problem: The root route group_by: ['...'] (grouped by all labels); a network blip in one availability zone made 400 instances report InstanceDown, one notification per instance. Approach: Change it to group_by: ['alertname', 'cluster', 'service'], and add an inhibition rule ZoneNetworkDown → suppress the same zone of InstanceDown. Limits: grouping too coarsely causes unrelated alerts to crowd into one notification,group_by so the grouping must include at least the labels that identify who is responsible.

Case 2: a “forever” silence caused missed alerts

Problem: Someone created alertname=~".+", a 30-day silence for maintenance, forgot to delete it, and real incidents went unnoticed during that time. Approach: configure amtool require-comment: true; silences must include a ticket number; create alerts for alertmanager_silences{state="active"} the number of silences and for overly long silences; during maintenance, match by instance exact match. Limits: Alertmanager has no built-in policy to forbid overly broad silences, so process controls are needed.

Case 3: wrong time zone, on-call paged over the weekend

Problem:time_intervals Did not specify location, so it was calculated in UTC and the North American team was paged on Friday night. After adding location: America/Toronto , Alertmanager failed to start. Approach: The container has no zoneinfo; mount the host’s /usr/share/zoneinfo read-only into the container (or set ZONEINFO to point to a zip), then use named time zones so daylight saving time is handled automatically. Limits: After the change, use amtool check-config in the same image to verify.

Common errors and fixes

err="unknown time zone America/Toronto" / failed to load configuration

Cause: Go’s time.LoadLocation needs a time zone database, which the busybox base image may not include.

docker compose logs alertmanager --since 5m | grep -i -E 'zone|error'

Fix: mount /usr/share/zoneinfo:/usr/share/zoneinfo:ro, or switch to UTC/Local.

The alert is visible in the Alertmanager UI, but there are no notifications at all
curl -s localhost:9093/api/v2/alerts | jq -r '.[] | "\(.labels.alertname)\t\(.status.state)\t\(.status.silencedBy)\t\(.status.inhibitedBy)\t\(.receivers|map(.name))"'
docker compose exec alertmanager amtool config routes test --config.file=/etc/alertmanager/alertmanager.yml alertname=X severity=warning
curl -s localhost:9093/metrics | grep -E 'alertmanager_notifications_(total|failed_total)'

Check in order: state is suppressed → silenced or inhibited; receiver is not the expected one → routing (matchers spelling,continue); route carries mute_time_intervals; still in group_wait ; notification failure → Module 4.

Receiving many duplicate notifications (every 30 seconds)

Cause: the set of alerts in the group keeps changing (an alert repeatedly fires and resolves), so every group_interval counts as “changed”; or group_by in the group_by list contains frequently changing labels.

Fix: use keep_firing_for to eliminate flapping; remove volatile labels from group_by; set group_interval sensibly (5m is common in production).

yaml: unmarshal errors: field match_re not found / rules have no effect

Cause: old and new syntax are mixed, or there is a spelling error; match/match_re is deprecated.

Fix: Unify to matchers: ['label=~"regex"']. Note that regular expressions in matchers are fully anchored: severity=~"crit" does not match critical.

Inhibition rule “over-applies”: all warnings are suppressed by a single critical

Cause:equal labels in the equal list are treated as equal when they are absent on both sides (missing = empty value), so the inhibition applies to all alerts.

Fix:equal only list labels that are guaranteed to exist on both sides (such as alertname,service), or further narrow the scope in target_matchers.

Command-line tasks
1. Expire in bulk all silences that have env="lab".
AM="docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093"
$AM silence expire $($AM silence query -q env=lab)
2. In CI, assert that critical-level myapp alerts are sent to both audit-log and oncall-critical.
amtool config routes test --config.file=alertmanager/alertmanager.yml \
  --verify.receivers=audit-log,oncall-critical severity=critical service=myapp alertname=X
Scenario analysis
The database team wants: database alerts go to Teams during the day, and to PagerDuty at night and on weekends. How do you implement this in one routing tree?

Write two sibling routes, both with matchers team="db": the first one receiver: db-teams,active_time_intervals: [workhours],continue: true; the second one receiver: db-pagerduty,mute_time_intervals: [workhours]. A route outside active hours sends no notification but still counts as a match, so the first one must set continue: true before the second one can be reached. Time intervals must specify location a location and ensure the image contains time zone data.

Verified teaching videos

▶
Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences on Alertmanager — Tech with Lian
English · hands-on demo of grouping, inhibition and silences, matching this module’s labs
▶
Prometheus Alertmanager for Beginners: Routes, Webhooks and Silences (Real Output) — DevOps Simplified
English · routing, webhooks and silences, with real output
▶
Lightning Talk: New matchers in the Alertmanager config and silences - Atibhi Agrawal, Grafana Labs — CNCF [Cloud Native Computing Foundation]
English · the design of matcher syntax and background on UTF-8 matchers
▶
Prometheus and Grafana : 14 - Alertmanager: Grouping, Routing and Silences — Oddly Yogi
English · explanation of grouping / routing / silence concepts

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Scene: an alert label card drops from the root route, matchers are compared level by level down the tree, and the matching node lights up.
Narration: every alert enters from the root route, is matched depth-first, and by default stops at the first matching branch.
Shot 2 · 25–50s
Scene: a node with the continue flag makes a copy of the card that keeps moving right, finally landing in two receivers.
Narration: set continue to true, and the alert will keep matching the sibling routes that follow.
Shot 3 · 50–75s
Scene: the RedisDown red light comes on, and a translucent cover hides MyappRedisUnavailable.
Narration: when the upstream alert exists, an inhibition rule automatically suppresses downstream alerts with matching labels.
Shot 4 · 75–100s
Scene: a maintenance engineer creates a time-limited silence in the UI, which expires automatically when the timer ends.
Narration: silences are created at runtime and are time-limited; inhibition is written in the configuration and takes effect automatically based on alert state.
or score ≥ 70% on the quiz

Module 4 · Notification channels: email, Teams, Slack, PagerDuty and webhook

21:00 – 28:00 · A receiver defines “where notifications go and what they look like”; all labs run locally and need no external accounts
7 minLocal webhook + MailpitSecrets via *_file★★★★☆
Learning objectives
  • Know that one receiver can contain several integrations (webhook_configs,email_configs,msteamsv2_configs,slack_configs,pagerduty_configs …), and remember that the defaults of each integration send_resolved differ.
  • Read webhook payloads (version: "4",groupKey,status,alerts[],fingerprint), and be able to write a minimal receiver for a custom integration.
  • Customise titles and bodies with notification templates (Go templates), and use amtool template render for offline debugging; use *_file to manage secrets such as webhook URLs, tokens and routing keys.
  • Through alertmanager_notifications_failed_total metrics and logs such as those, troubleshoot notification failures and understand the relationship between retries and group_interval timeouts.
Prerequisites: The routing tree from Module 3. Importance:★★★★☆

What: receiver = name + a set of integration configs

receivers:
  - name: oncall-critical          # the name referenced in routes
    webhook_configs:   [ ... ]     # multiple integrations can coexist
    email_configs:     [ ... ]     # each integration type can also have multiple entries
    pagerduty_configs: [ ... ]

Integrations listed in the v0.35.0 docs: discord, email, incidentio, jira, mattermost, msteams,msteamsv2, opsgenie, pagerduty, pushover, rocketchat, slack, sns, telegram, victorops (Splunk On-Call), webex,webhook, wechat. Systems without a built-in integration (internal enterprise IM, ticketing systems) can all be connected via webhook.

Key points of each integration (per the Alertmanager v0.35.0 docs)

IntegrationKey fieldssend_resolved DefaultNotes
webhookurl / url_file,max_alerts,timeout,payloadtruepayload format is fixed as JSON version "4"; payload JSON can be customised (officially “at your own risk”)
emailto,from,smarthost,auth_*,require_tls,headers,html/textfalseGo does not support plaintext connection authentication to remote SMTP; port 465 automatically uses implicit TLS
msteamsv2webhook_url / webhook_url_file,title,texttrueUse Teams Workflows (Power Automate) generated URL, Adaptive Card format; the legacy msteams_configs corresponds to Office 365 Connectors, which Microsoft has retired
slackapi_url / api_url_file (Incoming Webhook) or app_token,channel,title,textfalseadded in v0.35.0 post_updates_to_thread; on 429, retry according to Retry-After the Retry-After value
pagerdutyrouting_key / routing_key_file (Events API v2),severity,detailstrueservice_key corresponds to the legacy “Prometheus” integration type; deduplicates by groupKey, and resolved automatically closes the events

Why: why notifications should be “carefully designed”

  • On-call people only look at the title on their phone, so the title must include status, alert name, count and environment.
  • The body must be actionable: summary, current value, start time,runbook link, dashboard link, silence link.
  • Tiered delivery: critical → PagerDuty (phone / push), warning → Teams/Slack channel, info → email / tickets.
  • Every notification must be auditable: add another webhook that writes to a log or ticketing system (Module 3’s audit-log).

How: sending and retry mechanics

  1. When a group reaches its send time (group_wait / group_interval / repeat_interval) → generate the notification data (Status,Alerts,GroupLabels,CommonLabels,CommonAnnotations,ExternalURL).
  2. Check the notification log: if the content is the same as the last successful send and repeat_interval has not elapsed → do not send (the cluster also relies on it for deduplication).
  3. Each integration in a receiver sends in parallel; on failure, it retries with exponential backoff until success or until this attempt’s context timeout is exceeded (group_interval).
  4. Results are counted in alertmanager_notifications_total{integration},alertmanager_notifications_failed_total{integration,reason},alertmanager_notification_latency_seconds.

When: choosing which channel

ScenarioRecommendation
Needs phone calls / escalation policies / on-call schedulingIncident management platforms such as PagerDuty, Opsgenie and incident.io
Team collaboration, non-urgentTeams (msteamsv2), Slack channels
Auditing, tickets, internal systemswebhook (self-built service), Jira integration
Low-frequency summariesEmail
Common misconceptions① “Slack sends resolved notifications by default”: wrong. The default of slack_configs and email_configs of send_resolved send_resolved is false false. ② “Putting the webhook URL directly in alertmanager.yml is fine”: not so. Teams/Slack webhook URLs are credentials in themselves; anyone who has one can post to the channel. Use *_file a _file secret and restrict file permissions, so the config file can safely go into Git. ③ “Alertmanager retries failed notifications forever”: it only retries within the context of the current group_interval; the next attempt happens at the next send time. ④ “a webhook’s alerts are only ever firing”: the same notification can contain both firing and resolved alerts; handle each alert according to each alert’s status status.

How a notification is generated and delivered

Group duereceiver: oncall-criticalAlerts: 2 firingGroupLabels: alertname… Notification logContent unchanged and repeat_interval not yet reached?repeat_interval?Yes → skip Render templatestemplates/*.tmpltitle / text / htmlRead *_file secrets webhook → POST JSON v4 email → SMTP (Mailpit) pagerduty → Events API v2 Each integration is independent: failure → exponential backoff retry (until group_interval times out) alertmanager_notifications_total{integration="webhook"} alertmanager_notifications_failed_total{integration,reason} alertmanager_notification_latency_seconds Log: msg="Notify for alerts failed" receiver=… integration=… webhook payload (version "4") { "receiver", "status": "firing|resolved", "groupLabels", "commonLabels", "commonAnnotations", "externalURL", "groupKey", "truncatedAlerts", "alerts": [{status, labels, annotations, startsAt, endsAt, generatorURL, fingerprint}] }
Figure 4-1: integrations in the same receiver send in parallel and retry independently; the notification log guarantees no duplicates

Interactive: notification payload previewer

Choose a group state and a receiving channel to see what Alertmanager would send (webhook uses the official JSON structure; other channels show a rendered sketch based on this lesson’s templates). Click “Simulate send failure” to observe retries and metric changes.


        

Core commands and configuration snippets

Command / metricPurpose
amtool template render --template.glob=G --template.text='{{ template "x" . }}'Render templates offline using built-in sample data
amtool alert add alertname=X severity=critical --annotation=summary=...Send a test alert and verify end to end
curl localhost:9093/metrics | grep alertmanager_notificationsView success / failure counts per integration
docker compose logs alertmanager | grep -i notifyFailure causes (HTTP status codes, TLS, DNS)
curl localhost:8025/api/v1/messagesMailpit API: list received emails

Production channel configuration example (not enabled in the lab)

receivers:
  - name: team-myapp-teams
    msteamsv2_configs:
      - webhook_url_file: /etc/alertmanager/secrets/teams-myapp-url   # URL generated by Teams Workflows
        title: '{{ template "promlab.title" . }}'
        text: '{{ template "promlab.text" . }}'

  - name: team-myapp-slack
    slack_configs:
      - api_url_file: /etc/alertmanager/secrets/slack-myapp-webhook
        channel: '#myapp-alerts'
        send_resolved: true                                           # slack defaults to false
        title: '{{ template "promlab.title" . }}'
        text: '{{ template "promlab.text" . }}'

  - name: oncall-pagerduty
    pagerduty_configs:
      - routing_key_file: /etc/alertmanager/secrets/pd-routing-key     # Events API v2 integration key
        severity: '{{ if eq .CommonLabels.severity "critical" }}critical{{ else }}warning{{ end }}'
        description: '{{ template "promlab.title" . }}'
        details:
          runbook: '{{ .CommonAnnotations.runbook_url }}'

Secret files use Compose secrets: or are provided via a read-only mount, and .gitignore. PagerDuty details syntax should be checked against the documentation for the version in use.

Lab 4: email + custom templates + failure troubleshooting (about 7 minutes)

Write a notification template:
{{ define "promlab.title" -}}
[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .GroupLabels.alertname }} ({{ .CommonLabels.env }})
{{- end }}

{{ define "promlab.text" -}}
{{ range .Alerts -}}
- [{{ .Status }}][{{ .Labels.severity }}] {{ .Annotations.summary }}
  {{ .Annotations.description }}
  Start: {{ .StartsAt.Format "2006-01-02 15:04:05 MST" }}
{{- if .Annotations.runbook_url }}
  Runbook: {{ .Annotations.runbook_url }}
{{- end }}
{{ end -}}
Alertmanager: {{ .ExternalURL }}
{{- end }}
Modify alertmanager.yml: add global the SMTP settings for templates, and make oncall-critical send to both webhook and email (the rest stays as in Module 3):
global:
  resolve_timeout: 5m
  smtp_smarthost: 'mailpit:1025'
  smtp_from: 'alertmanager@promlab.local'
  smtp_require_tls: false          # local Mailpit only; production must use TLS

templates:
  - '/etc/alertmanager/templates/*.tmpl'

# in receivers, replace oncall-critical:
  - name: oncall-critical
    webhook_configs:
      - url: 'http://webhook:5001/critical'
    email_configs:
      - to: 'oncall@promlab.local'
        send_resolved: true        # email defaults to false
        headers:
          Subject: '{{ template "promlab.title" . }}'
        text: '{{ template "promlab.text" . }}'
Render the template offline, validate, reload:
cd ~/promlab
AMX="docker compose exec alertmanager amtool"
$AMX template render --template.glob='/etc/alertmanager/templates/*.tmpl' --template.text='{{ template "promlab.title" . }}'
$AMX check-config /etc/alertmanager/alertmanager.yml
curl -s -XPOST localhost:9093/-/reload && echo reloaded
[FIRING:2] Test_Alert ()
Checking '/etc/alertmanager/alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 2 inhibit rules
 - 6 receivers
 - 1 templates
  SUCCESS
reloaded

template render Uses amtool’s built-in sample data, so the alert name and labels are sample values; the key point is that the template renders successfully.

Send a test alert and check the email and webhook:
AM="docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093"
$AM alert add alertname=NotifyTest severity=critical service=myapp env=lab \
  --annotation=summary='Notification pipeline test' --annotation=description='Lab 4' \
  --annotation=runbook_url='https://runbooks.example.com/notify-test'
sleep 12
curl -s localhost:8025/api/v1/messages | jq -r '.messages[] | "\(.Subject)\t\(.To[0].Address)"' | head -3
docker compose logs --no-log-prefix webhook --since 1m | grep NotifyTest
docker compose exec webhook python -c "import json;d=json.load(open('/tmp/last.json'));print(d['version'],d['status'],d['groupKey']);print(sorted(d['alerts'][0].keys()))"
[FIRING:1] NotifyTest (lab)	oncall@promlab.local
14:31:05 POST /audit receiver=audit-log status=firing alerts=1 [NotifyTest] …
14:31:05 POST /critical receiver=oncall-critical status=firing alerts=1 [NotifyTest] …
4 firing {}/{severity=~"critical|warning"}/{severity="critical"}:{alertname="NotifyTest", env="lab", service="myapp"}
['annotations', 'endsAt', 'fingerprint', 'generatorURL', 'labels', 'startsAt', 'status']

Open the browser at http://localhost:8025 to see the complete email. groupKey consists of the routing path and grouping labels; the last one written /tmp/last.json may be audit or critical; both have the same structure.

Create a notification failure: change the team-myapp ’s URL temporarily to a port that does not exist http://webhook:5999/x, reload, and then send a warning:
sed -i 's#http://webhook:5001/myapp-warning#http://webhook:5999/x#' alertmanager/alertmanager.yml
curl -s -XPOST localhost:9093/-/reload
$AM alert add alertname=NotifyFailTest severity=warning service=myapp env=lab --annotation=summary='Failure test'
sleep 45
curl -s localhost:9093/metrics | grep -E '^alertmanager_notifications_failed_total\{.*webhook'
docker compose logs alertmanager --since 1m | grep -i 'notify' | tail -n 2
alertmanager_notifications_failed_total{integration="webhook",reason="other"} 3
time=… level=WARN source=notify.go msg="Notify attempt failed, will retry later" receiver=team-myapp integration=webhook[0] attempts=1 err="Post \"<redacted>\": dial tcp 172.20.0.9:5999: connect: connection refused"
time=… level=ERROR source=dispatch.go msg="Notify for alerts failed" num_alerts=1 err="team-myapp/webhook[0]: notify retry canceled after 4 attempts: …"

Log fields and reason label values differ between versions (a refused connection is usually classified as other); the URL is treated as a secret and is shown in the logs as <redacted>. Module 8 will create an alert for this metric.

Recovery:
sed -i 's#http://webhook:5999/x#http://webhook:5001/myapp-warning#' alertmanager/alertmanager.yml
curl -s -XPOST localhost:9093/-/reload && echo reloaded

Case 1: all Teams notifications suddenly failed

Problem: A Teams Incoming Webhook (Office 365 Connector) configured years ago no longer accepts messages. Approach: In Teams, use Workflows to create a flow that “posts to a channel when a webhook request is received”, and switch Alertmanager to use msteamsv2_configs (Adaptive Card format). Configuration: See the “Commands” page; put the URL in webhook_url_file. Limits: Workflows URLs are also credentials and must be rotated like secrets; messages have a length limit, so replace overly long content with a link.

Case 2: PagerDuty incidents duplicate and do not close

Problem: The same alert creates several incidents in PagerDuty, and they do not close automatically after recovery. Approach: The cause was that two Alertmanager instances were not clustered (each sent on its own), and the route set group_by to ['...']. Fixed by changing it to the correct --cluster.peer, and grouped by alertname, service . Limits: PagerDuty deduplicates by Alertmanager’s groupKey, so changing group_by changes the groupKey, and old incidents must be closed manually.

Case 3: webhook URL appears in Git history

Problem: A Slack webhook was written in alertmanager.yml and committed to a public repository, and the channel was flooded with spam. Approach: Immediately revoke the webhook in Slack and generate a new one; switch to api_url_file, with the secret injected via Kubernetes Secrets / Compose secrets; enable secret scanning on the repository (GitHub course, Lesson 5). Limits: Rewriting Git history does not retract credentials that have already leaked; revocation is the only reliable remedy.

Common errors and fixes

msg="Notify for alerts failed" … x509: certificate signed by unknown authority

Cause: The receiver uses a certificate issued by an enterprise CA.

Fix: In that integration’s http_config.tls_config.ca_file specify the CA; do not use insecure_skip_verify: true as a long-term solution.

email: … 530 Must issue a STARTTLS command first / unencrypted connection

Cause: The SMTP service requires TLS, but the configuration require_tls: false; or conversely, the local test server does not support TLS but TLS is required.

Fix: In production, keep smtp_require_tls: true (the default), use 587 (STARTTLS) or 465 (implicit TLS); only turn it off for a local test server.

template: … function "toupper" not defined / can't evaluate field Firing

Cause: Function name case (toUpper); or, inside range .Alerts accessing group-level fields.

docker compose exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml
docker compose exec alertmanager amtool template render --template.glob='/etc/alertmanager/templates/*.tmpl' --template.text='{{ template "promlab.text" . }}'

Fix: Inside range, use $.CommonLabels to access outer data.

Not receiving resolved notifications

Cause: email/slack default to send_resolved: false; or the alert was resolved during group_wait the period (so no notification is sent).

Fix: Explicitly set send_resolved: true.

The webhook receiver occasionally gets duplicate notifications

Cause: Alertmanager delivers “at least once”: if the receiver processes the request successfully but the response times out, Alertmanager retries; an HA cluster may also send duplicates during a network partition.

Fix: The receiver should deduplicate by groupKey + status + alert fingerprint , i.e. make processing idempotent.

Command-line tasks
1. Calculate the notification failure rate for each integration over the past hour.
sum by (integration) (increase(alertmanager_notifications_failed_total[1h]))
/
sum by (integration) (increase(alertmanager_notifications_total[1h]))
2. Use jq to list each alert’s status and fingerprint from the webhook payload.
docker compose exec webhook cat /tmp/last.json | jq -r '.alerts[] | "\(.status)\t\(.fingerprint)\t\(.labels.alertname)"'
Scenario analysis
The company’s internal IM has no built-in Alertmanager integration and only offers a bot interface that accepts a “POST of a specific JSON”. What options are there?

① Write a small translation service (similar to receiver.py in this lesson): receive the webhook v4 payload, make it idempotent by groupKey, convert it, and call the IM API. This is the most flexible option, and retries and auditing can be added. ② Use the webhook’s payload field to build the target JSON directly (the v0.35 docs have a Gotify example), skipping the intermediate service; but the official docs say “use at your own risk”, there is no validation, and complex formats are hard to maintain. ③ If a community adapter exists, first evaluate how well it is maintained. For production, option ① is recommended.

Verified teaching videos

▶
How to Setup Prometheus alertmanager with Pagerduty and Slack — Arvind Konar
English · PagerDuty and Slack integration demo (the UI depends on the current version)
▶
Prometheus Alertmanager for Beginners: Routes, Webhooks and Silences (Real Output) — DevOps Simplified
English · webhook receiver and real payload output

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Scene: a receiver box unfolds into three pipes: webhook, email and PagerDuty.
Narration: one receiver can contain several integrations; they send in parallel and retry independently.
Shot 2 · 20–45s
Scene: the JSON payload is highlighted field by field: status, groupKey, alerts, fingerprint.
Narration: the webhook payload uses the fixed version 4 format; the receiver should process it idempotently by groupKey and fingerprint.
Shot 3 · 45–70s
Scene: the template file renders a phone notification title “[FIRING:2] MyappHighErrorRate (lab)”.
Narration: the title must include status, count, alert name and environment; the body gives the runbook link.
Shot 4 · 70–90s
Scene: the webhook URL is moved from the config file into a locked secrets file.
Narration: the webhook address and routing key are both secrets; reference them with a file field, and do not commit them to Git.
or score ≥ 70% on the quiz

Module 5 · Grafana Alerting and unified alerting

28:00 – 35:00 · Grafana ships with a complete alerting system (a built-in Alertmanager); understand how it divides work with Prometheus + Alertmanager, so you avoid “two alerting systems each firing once”
7 minGrafana 13.3.1File provisioning★★★★☆
Learning objectives
  • Distinguish between Grafana-managed alerting rules (evaluated by Grafana, can query any data source) and data-source-managed alerting rules (evaluated by the Prometheus/Mimir/Loki ruler; Grafana only displays or edits them).
  • Master the objects of Grafana Alerting: alert rules (query + expressions + condition), contact points, notification policies, silences and time intervals, and how each maps one-to-one to Alertmanager concepts.
  • Understand the six states of an alert instance: Normal, Pending, Alerting, Recovering, No Data, Error, as well as the Pending period, Keep firing for, and No Data / Error handling options.
  • Use file provisioning (provisioning/alerting/*.yaml) to put rules, contact points and policies under version control, and reload and export them via the API.
Prerequisites: Modules 2–4; the Grafana data source from Lesson 1. Importance:★★★★☆

What: the object model of Grafana Alerting

Grafana objectCorresponding Prometheus / Alertmanager conceptDescription
Alerting rule (Grafana-managed)alerting ruleone or more queries (refId A, B…) + expressions (Reduce, Math, Threshold, etc.) + a condition (which refId serves as the decision); placed in folder in an evaluation group, the group sets the evaluation interval
Pending periodforwhen 0, Pending is skipped
Keep firing forkeep_firing_forwhen 0, the Recovering state is skipped
labels / annotationslabels / annotationsGrafana automatically adds grafana_folder labels; annotations can link to dashboard panels
contact pointreceiverone contact point can contain multiple integrations (email, webhook, Teams, Slack, PagerDuty…)
notification policyroute treedefault policy + nested policies, matched by labels; supports group_by, timers, mute/active timings
silence / time interval (mute timings)silence / time_intervalssame name and meaning
Alertmanager data sourceexternal Alertmanagerview / manage alerts and silences of an external Alertmanager in Grafana, and configure Grafana to send alerts to an external Alertmanager

Alert instance states (official Grafana documentation)

StateMeaning
Normalcondition not met
Pendingcondition met, but the Pending period has not been reached
Alertingcondition continuously met for the Pending period; notification starts (equivalent to firing)
Recoveringwhile Alerting, the condition is no longer met; it stays in this state during Keep firing for
No Dataquery succeeds but returns no data points (by default this produces a DatasourceNoData alert)
Errorquery or expression evaluation fails (by default this produces an DatasourceError alert)

The No Data and Error states exist only for Grafana-managed rules. The rule’s “No Data / Error handling” can be set to: No Data (or Error), Alerting, Normal (written as OK in provisioning), Keep Last State (KeepLast).

Why: why (and when) to use Grafana Alerting

  • Multiple data sources: the same rule can combine Prometheus metrics with Loki logs, SQL data and cloud monitoring APIs, which Prometheus rules cannot do.
  • User-friendly UI: non-PromQL experts can preview queries and adjust thresholds in the UI; rules are linked to dashboard panels, and alerts show their annotations on the panels.
  • Unified view: a single alert list shows both Grafana-managed rules and data-source-managed rules (Prometheus rules are shown read-only), along with alerts from external Alertmanagers.

How: the execution path of Grafana-managed rules

  1. The scheduler runs rules at the evaluation group interval: query the data source (A) → expression (e.g. Threshold C) → each series produces one alert instance.
  2. The state machine advances state according to Pending period / Keep firing for / No Data / Error handling.
  3. Alerting instances are sent to Grafana built-in Alertmanager (by default), routed to contact points by notification policy; in settings you can change it to send to an external Alertmanager (or in addition to it).

When: Prometheus rules vs Grafana-managed rules

Choose Prometheus rules + AlertmanagerChoose Grafana-managed rules
pure Prometheus metrics; needs promtool unit tests; rules are managed in Git alongside the application; in Kubernetes, use the PrometheusRule CRD (Lesson 5); a Grafana outage should not affect alertingneeds to combine multiple data sources; the team works mainly in the UI; needs log / SQL-based alerts; already uses managed alerting in Grafana Cloud / Azure Managed Grafana
Avoid duplicate alerts Do not define the same condition in both Prometheus rules and Grafana rules. This lesson’s convention: service SLO / symptom alerts are defined in Prometheus (unit-testable, decoupled from Grafana); Grafana-managed rules are used only for cross-data-source or business-level alerts; notifications from both systems converge on the same set of receivers, uniformly using the severity,service labels.
Common misconceptions① “Grafana alerts depend on dashboards”: unified alert rules have existed independently since Grafana 8 and can optionally be linked to panels. ② “No Data means everything is fine”: by default it produces a DatasourceNoData alert; for queries where “no errors means no series”, set No Data handling to Normal (OK). ③ “provisioning a notification policy only adds my child policies”: the policy tree is a single whole resource, and provisioning will overwrite the entire tree. ④ “you can freely write $A” — Grafana interpolates environment variables in provisioning files, so the $A in a Math expression must be written as $$A (this lesson uses a Threshold expression to avoid the issue).

How two alerting systems coexist

Prometheus (data-source-managed rules)rules/*.yml · promtool testsMyappHighErrorRate, RedisDown…read-only display in Grafana Alertmanager :9093routing tree / inhibition / silences (Module 3)→ webhook /audit /critical … Grafana :3000 Grafana-managed rulesfolder promlabevaluation group myapp-grafanaA query → C Threshold built-in Alertmanagernotification policy treesilences / mute timings contact pointslab-webhook→ /grafana alert list (unified view)Grafana-managed + Prometheus rulesalert annotations on panelsstate history Alertmanager data sourceview / silence external AM alerts(optional) send Grafana alertsto an external AM read The notifications of the two systems finally converge on the same webhook receiver (different paths); unify the severity / service labels to avoid defining the same condition twice
Figure 5-1: the coexistence model in this lesson: Prometheus handles service alerts, and Grafana-managed rules add supplementary coverage

Queries and expressions of Grafana-managed rules

A: Prometheus querysum(up{job="myapp"})instant · returns 1 numeric value C: Threshold expressioninput A, is below 1(range queries must first be reduced with Reduce) condition: Ceach series → one alert instancefor 30s → Alerting
Figure 5-2: an instant query can feed directly into Threshold; a range query must first be reduced to a single value with Reduce

Interactive: Grafana alerting state machine

Set the rule parameters, then enter the result of each evaluation round (condition met / not met / no data / query error), and observe the changes in alert instance state and whether a notification is sent. The evaluation interval is counted as 30 seconds.

Each button press represents one evaluation round (30s).

Grafana Alerting API and provisioning

Interface / filePurpose
/etc/grafana/provisioning/alerting/*.yamlFile provisioning: groups (rules),contactPoints,policies,muteTimes,templates; you can add deleteRules and other delete sections
POST /api/admin/provisioning/alerting/reloadReload alerting provisioning (requires Server Admin)
GET /api/v1/provisioning/alert-rules/exportExport rules (?format=yaml|json|hcl), which can be used directly as provisioning files or Terraform
GET /api/v1/provisioning/contact-points/export,/policies/exportExport contact points and notification policies
GET /api/prometheus/grafana/api/v1/rulesGrafana rules and states in Prometheus-compatible format
GET /api/datasourcesList data sources and UIDs (rules reference datasourceUid)
GF="admin:${GF_ADMIN_PASSWORD:-promlab-admin}"   # Grafana admin from Lesson 1
curl -s -u $GF localhost:3000/api/datasources | jq -r '.[] | "\(.name)\t\(.type)\t\(.uid)"'
curl -s -u $GF 'localhost:3000/api/v1/provisioning/alert-rules/export?format=yaml' | head -n 20
Prometheus	prometheus	prometheus
apiVersion: 1
groups: []

The Lesson 1 data source name is Prometheus, with a fixed uid of prometheus. Rules created through provisioning are marked “Provisioned” in the UI and cannot be edited directly in the UI by default; this is intentional, and changes should be made in the file.

Lab 5: provision one Grafana-managed rule with a file (about 7 minutes)

Add the Alertmanager data source (to view the Prometheus-side alerts and silences in Grafana):
apiVersion: 1
datasources:
  - name: Alertmanager
    type: alertmanager
    uid: alertmanager
    access: proxy
    url: http://alertmanager:9093
    jsonData:
      implementation: prometheus
      handleGrafanaManagedAlerts: false   # in this lesson, Grafana alerts are still handled by the built-in Alertmanager
Find the Prometheus data source UID and generate the alerting provisioning file:
cd ~/promlab
GF="admin:${GF_ADMIN_PASSWORD:-promlab-admin}"
PROM_UID=$(curl -s -u $GF localhost:3000/api/datasources | jq -r '[.[] | select(.type=="prometheus")][0].uid')   # fixed as prometheus in Lesson 1
echo "Prometheus UID = $PROM_UID"
cat > grafana/provisioning/alerting/lab-alerting.yaml <<EOF
apiVersion: 1

contactPoints:
  - orgId: 1
    name: lab-webhook
    receivers:
      - uid: lab-webhook-1
        type: webhook
        disableResolveMessage: false
        settings:
          url: http://webhook:5001/grafana
          httpMethod: POST

policies:                      # note: this overwrites the entire notification policy tree
  - orgId: 1
    receiver: lab-webhook
    group_by: ['grafana_folder', 'alertname']
    group_wait: 10s
    group_interval: 30s
    repeat_interval: 1h

groups:
  - orgId: 1
    name: myapp-grafana
    folder: promlab
    interval: 15s
    rules:
      - uid: myapp-no-healthy-target
        title: GrafanaMyappNoHealthyTarget
        condition: C
        data:
          - refId: A
            relativeTimeRange: {from: 300, to: 0}
            datasourceUid: ${PROM_UID}
            model:
              refId: A
              expr: sum(up{job="myapp"})
              instant: true
              range: false
          - refId: C
            datasourceUid: __expr__
            model:
              refId: C
              type: threshold
              expression: A
              conditions:
                - evaluator: {type: lt, params: [1]}
        noDataState: Alerting       # even if no up series exist at all, treat this as a failure
        execErrState: Error
        for: 30s
        labels:
          severity: warning
          service: myapp
          source: grafana
        annotations:
          summary: "Grafana-managed rule: myapp has no healthy scrape targets"
EOF
grep -n 'datasourceUid' grafana/provisioning/alerting/lab-alerting.yaml
Prometheus UID = prometheus
21:            datasourceUid: prometheus
28:            datasourceUid: __expr__

The heredoc end marker is unquoted, so ${PROM_UID} is substituted when the file is generated; the file contains no other $ shell variables.

Let Grafana load (data source provisioning requires a restart; alerts can be reloaded via the API; restarting directly is simplest here):
docker compose restart grafana
sleep 15
curl -s -u $GF -XPOST localhost:3000/api/admin/provisioning/alerting/reload
curl -s -u $GF localhost:3000/api/prometheus/grafana/api/v1/rules | jq -r '.data.groups[].rules[] | "\(.name)\t\(.state)\t\(.health)"'
{"message":"Alerting config reloaded"}
GrafanaMyappNoHealthyTarget	inactive	ok
Trigger and observe: stop myapp; about 45–60 seconds later the webhook will /grafana receive Grafana’s notification (at the same time, Prometheus’s MyappDown is routed to /audit and /critical according to Module 3’s routing):
docker compose stop myapp
sleep 75
curl -s -u $GF localhost:3000/api/prometheus/grafana/api/v1/rules | jq -r '.data.groups[].rules[] | "\(.name)\t\(.state)"'
docker compose logs --no-log-prefix webhook --since 2m | grep -E '/grafana|MyappDown'
GrafanaMyappNoHealthyTarget	firing
14:41:22 POST /grafana receiver=lab-webhook status=firing alerts=1 [GrafanaMyappNoHealthyTarget] groupLabels={"alertname": "GrafanaMyappNoHealthyTarget", "grafana_folder": "promlab"}
14:41:31 POST /audit receiver=audit-log status=firing alerts=1 [MyappDown] …
14:41:31 POST /critical receiver=oncall-critical status=firing alerts=1 [MyappDown] …

This is exactly the scene of “two systems each reporting once”. In a real environment you should keep only one of them (this lesson keeps Prometheus’s MyappDown; the Grafana rule is for demonstration only). Grafana’s webhook payload adds more title,state,message,orgId and other fields.

Recover, and view in the UI:
docker compose start myapp

Open Grafana in the browser → Alerting → Alert rules: you can see the Grafana-managed rules in the promlab folder (marked Provisioned), and under the Prometheus data source myapp-alerts the rule groups, etc. (data-source-managed, read-only). In Alerting → Silences, select the “Alertmanager” data source to view or create silences on the Prometheus-side Alertmanager.

Case 1: after migrating to Grafana alerting, every Prometheus restart triggers DatasourceError

Problem: Grafana-managed rules enter Error when the data source is briefly unavailable, triggering DatasourceError alerts. Approach: Set Error handling to Keep Last State and set a reasonable Pending period for the rule; data source availability itself is handled by monitoring on the Prometheus side (Module 8). Limits: Keep Last State may mask long data source outages, so a separate data source health alert is needed.

Case 2: notification policy overwritten by provisioning

Problem: The platform team manages notification policies with provisioning, but sub-policies added in the UI by business teams disappeared after the next deployment. Approach: Make it explicit that “the policy tree can only be managed from one source”: either all via files / Terraform (recommended) or all in the UI; when teams need autonomy, configure once in the central policy using label-based routing conventions (such as team=) in the central policy. Limits: The file generated by the export API can be used directly as a starting point (/api/v1/provisioning/policies/export).

Case 3: combined log + metric alert

Problem: The payment service should page on-call only when the “5xx ratio rises and logs show card_declined_timeout”. Approach: Grafana-managed rule: A is the Prometheus error ratio, B is the Loki count_over_time, C is Math $A > 0.05 && $B > 10. Limits: The labels of the two queries must match (or both be reduced to a single value); otherwise you get multiple instances or no result.

Common errors and fixes

failed to provision alert rules: data source not found / invalid datasourceUid
docker compose logs grafana --since 5m | grep -i -E 'provision|alert'
curl -s -u $GF localhost:3000/api/datasources | jq -r '.[] | "\(.name)\t\(.uid)"'

Fix: the datasourceUid in the rule must match the data source UID; in the data source provisioning, explicitly pin uid, to avoid differences between environments.

The rule is always NoData and receives DatasourceNoData notifications

Cause: the query has no series during normal operation (for example a 5xx rate that only exists when errors occur).

Fix: set No Data handling to Normal (OK) or make the query always return a value (or vector(0), Module 1).

Math expression $A > 0.8 became " > 0.8" after provisioning

Cause: Grafana performs environment variable interpolation on provisioning files, so $A is replaced with an empty string.

Fix: write it as $$A, or use a Threshold / Reduce expression.

The same fault sends two notifications (one from Grafana, one from Alertmanager)

Cause: the same condition is defined in both systems (deliberately, in this lab).

Fix: keep one place; or send Grafana alerts to an external Alertmanager (via the Alertmanager data source handleGrafanaManagedAlerts: true and enable it in the Alerting settings), and unify suppression / deduplication in Alertmanager.

Command-line tasks
1. Export all alert rules currently in Grafana as Terraform HCL.
curl -s -u $GF 'localhost:3000/api/v1/provisioning/alert-rules/export?format=hcl' > grafana-alert-rules.tf
2. Reload only alerting provisioning, without restarting Grafana.
curl -s -u $GF -XPOST localhost:3000/api/admin/provisioning/alerting/reload
Scenario analysis
The team has 200 Prometheus alerting rules and a mature Alertmanager routing setup; the new manager requires “migrate everything to Grafana Alerting for a unified interface”. What is your recommendation?

Full migration is not recommended. Prometheus rules can be unit-tested and are decoupled from Grafana availability, and Grafana can already display data-source-managed rules read-only in the same interface and view / silence alerts through the Alertmanager data source, so the “unified interface” goal can be reached without migrating. Write only new alerts that need multiple data sources as Grafana-managed rules; to unify notifications, send Grafana-managed alerts to the same external Alertmanager so they use the same routing, inhibition and silences.

Verified teaching videos

▶
Get started with Grafana Alerting: Create and receive your first alert — Grafana
English · Grafana official channel, creating your first Grafana-managed alert
▶
Get started with Grafana Alerting: Group alert notifications — Grafana
English · grouping in notification policies
▶
Get started with Grafana Alerting: Route alerts using dynamic labels — Grafana
English · routing alerts using labels
▶
Get started with Grafana Alerting: Template your alert notifications — Grafana
English · notification templates
▶
Learn Grafana Alerting in 2026 | Alert Manager vs Grafana Alerts - Part 1 — Bhoopesh Sharma
English · comparison of Alertmanager and Grafana alerting

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Scene: Prometheus rule file on the left, Grafana rule editor on the right; a comparison table lights up row by row in the middle.
Narration: Grafana’s rules, contact points and notification policies correspond to Prometheus alerting rules, receivers and the routing tree respectively.
Shot 2 · 25–55s
Scene: state machine: Normal → Pending → Alerting → Recovering → Normal, with No Data and Error branches beside it.
Narration: Grafana adds three states (Recovering, No Data and Error), whose handling can be configured per rule.
Shot 3 · 55–90s
Scene: a YAML file is placed in the provisioning/alerting directory; the Grafana icon spins, and the rule gets a Provisioned badge.
Narration: manage alerts with file provisioning; note that the notification policy tree is overwritten as a whole.
or score ≥ 70% on the quiz

Module 6 · Dashboard design: USE / RED / the four golden signals

35:00 – 42:00 · Once alerts have woken people up, the dashboard must answer “how big is the impact and where to start looking” within 30 seconds
7 minRED · USE · Golden Signalsdashboard provisioning★★★★☆
Learning objectives
  • Distinguish three methods: RED (Rate, Errors, Duration; for request-driven services),USE (Utilization, Saturation, Errors; for resources),the four golden signals (Latency, Traffic, Errors, Saturation; Google SRE).
  • Design layered dashboards: overview → service → component / instance, each layer answering one question; choose panel types, units, thresholds and legends correctly.
  • Make panel queries use recording rules and stay consistent with alert thresholds, link dashboards and runbooks in alert annotations, and manage dashboards with file provisioning.
Prerequisites: Lesson 1 Modules 6–7 (Grafana panels and variables), and Module 1 of this lesson. Importance:★★★★☆

What: three methodologies

MethodSourceSubjectMetricsmyapp example queries
REDTom Wilkie (Weaveworks / Grafana Labs)each service / endpointRate request rate · Errors error rate / ratio · Duration latency distributionjob:myapp_http_requests:rate5m,job:myapp_http_errors:ratio_rate5m,job:myapp_http_request_duration_seconds:p95_5m
USEBrendan Greggeach resource (CPU, memory, disk, network, connection pools)Utilization · Saturation (queuing) · ErrorsCPU: 1 - avg(rate(node_cpu_seconds_total{mode="idle"}[5m])); saturation: node_load1 / count(node_cpu_seconds_total{mode="idle"})
four golden signalsGoogle, Site Reliability Engineeringuser-facing systemsLatency · Traffic · Errors · Saturationthe three RED items + saturation (for example gunicorn worker occupancy, Redis connections)

A way to remember it: RED shows how well the service is doing its work, USE shows whether the resource can still cope; golden signals ≈ RED + Saturation.

Why: criteria for a good dashboard

  • answers one question: the title of each dashboard is the question it answers, for example “Is myapp healthy for users right now?”.
  • from top to bottom, from overall to detail: the top row is the most important status (large numbers + threshold colours), below it trends, and below that breakdowns and resources.
  • consistent with alerts: panels use the same recording rules and threshold lines as alerts; alert dashboard annotations link directly here.
  • drill-down: through variables (job, instance, route) and data links, you can move into more detailed dashboards or Explore.

How: layered structure (convention for this lesson)

LevelQuestionContent
L0 overviewWhich service has a problem?one row of RED status per service + current alert list
L1 service (this lab)Is this service healthy for users? How big is the impact?RED large numbers, trends by status / route, p50/p95/p99, dependency status, active alerts
L2 component / instanceWhich instance / resource is the cause?USE: CPU, memory, disk, network, processes, connection pools; split by instance

Panel and unit quick reference

DataPanelUnit (Grafana)Key points
current error ratioStatpercentunit (0–1)thresholds the same as alerts: green < 5%, orange 5–20%, red ≥ 20%
request rateStat / Time seriesreqpsstacked by status
latency quantilesTime seriessp50 / p95 / p99 on the same chart, plus a 0.5s threshold line; do not average quantiles
latency distributionHeatmap—use directly _bucket rate, choose Heatmap format
whether a dependency is availableState timeline / Statvalue mapping 0=DOWN, 1=UP—
active alertsAlert list—can filter by folder / label

When: which method to use when

request-driven services (API, Web, gRPC) → RED; infrastructure and capacity-limited components (nodes, databases, queues, connection pools) → USE; user-facing product dashboards → golden signals (upgraded to SLO dashboards in Lesson 6).

Common misconceptions① “more panels means more professional”: an overview that does not fit on one screen is not read; split into layers beyond ~20 panels. ② “average latency is enough”: averages hide the long tail; look at p95/p99 at least. ③ “Y-axis auto-scaling is fine”: ratio panels should be fixed at 0–100%, otherwise a 0.1% wobble looks like a spike. ④ “writing complex PromQL directly in panels is more flexible”: the same expression scattered across panels leads to thresholds that disagree with alerts; use recording rules. ⑤ “just edit the dashboard in the UI”: no version control, no review; production dashboards should use provisioning / Terraform / Grafonnet (Lesson 5).

myapp service dashboard layout (L1)

myapp service overview · variable: job | time range 6h | links: Runbook · Alertmanager · L2 node dashboard Request rate9.8 req/s 5xx ratio0.0 % (thresholds 5% / 20%) p95 latency4.8 ms (threshold 500ms) Redis dependencyUP Request rate (stacked by status) Latency p50 / p95 / p99 + threshold line Active alerts (Alert list)MyappHighErrorRate · RedisDown …Click to jump to runbook / silence USE: node CPU / memory / load saturationfrom node-exporter (drill down to L2) ①⓪
Figure 6-1: the first row answers “is it healthy?”, the second row answers “since when, and how severe?”, the third row answers “what is firing, and is a resource the cause?”

Coverage of the three methods

RED (services)Rate ≈ TrafficDuration ≈ Latency USE (resources)UtilizationSaturation Errors (both have it)Golden signals = Latency + Traffic + Errors + Saturation
Figure 6-2: the golden signals combine RED’s three items with USE’s saturation

Interactive: dashboard method generator

Choose a monitoring target and method to generate a recommended panel list and PromQL; switch to “counter-examples” to see common design mistakes and their consequences.

Dashboard management commands

Command / filePurpose
provisioning/dashboards/*.yamldashboard provider: loads JSON from a directory,folder,allowUiUpdates,updateIntervalSeconds
GET /api/search?query=myappsearch dashboards and obtain the uid
GET /api/dashboards/uid/<uid>export dashboard JSON (.dashboard field)
POST /api/admin/provisioning/dashboards/reloadreload dashboard provisioning
UI: Dashboard → Export → Export as JSONWhen exporting, you can choose “Export for external sharing”, which replaces the data source with input variables
curl -s -u $GF 'localhost:3000/api/search?query=myapp' | jq -r '.[] | "\(.uid)\t\(.title)\t\(.folderTitle)"'
curl -s -u $GF localhost:3000/api/dashboards/uid/myapp-overview | jq '.dashboard.panels | length'
myapp-overview	myapp service overview (RED + USE)	promlab
9

Lab 6: provision the “myapp service overview” dashboard (about 6 minutes)

Reuse the dashboard provider from Lesson 1: the Lesson 1 grafana/provisioning/dashboards/promlab.yml already mapped the host grafana/dashboards/ (inside the container /etc/grafana/dashboards) to the promlab folder, polling every 30 seconds. This lesson puts the new dashboard directly into this directory; no new provider is needed, and Grafana does not need to be restarted. The Lesson 1 myapp-red.json (uid myapp-red) is the RED exploration dashboard; this lesson’s myapp-overview is an L1 service overview for on-call use: panels use recording rules, thresholds match alerts, and an alert list and USE panels are added.
ls ~/promlab/grafana/dashboards
myapp-red.json
Generate the dashboard JSON (all panels use the Module 1 recording rules; thresholds match the Module 2 alerts):
cd ~/promlab
GF="admin:${GF_ADMIN_PASSWORD:-promlab-admin}"
DS='{"type":"prometheus","uid":"prometheus"}'   # data source uid fixed in Lesson 1
cat > grafana/dashboards/myapp-overview.json <<EOF
{
  "uid": "myapp-overview",
  "title": "myapp service overview (RED + USE)",
  "tags": ["promlab", "myapp", "red"],
  "timezone": "browser",
  "schemaVersion": 39,
  "refresh": "30s",
  "time": {"from": "now-6h", "to": "now"},
  "links": [
    {"title": "Runbook", "type": "link", "url": "https://runbooks.example.com/myapp", "targetBlank": true},
    {"title": "Alertmanager", "type": "link", "url": "http://localhost:9093", "targetBlank": true}
  ],
  "panels": [
    {"id": 1, "type": "stat", "title": "Request rate", "gridPos": {"x": 0, "y": 0, "w": 6, "h": 4}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "sum(job:myapp_http_requests:rate5m{job=\"myapp\"})"}],
     "fieldConfig": {"defaults": {"unit": "reqps", "decimals": 1}, "overrides": []}},
    {"id": 2, "type": "stat", "title": "5xx ratio (alert thresholds 5% / 20%)", "gridPos": {"x": 6, "y": 0, "w": 6, "h": 4}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "max(job:myapp_http_errors:ratio_rate5m{job=\"myapp\"})"}],
     "fieldConfig": {"defaults": {"unit": "percentunit", "decimals": 2,
       "thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": null}, {"color": "orange", "value": 0.05}, {"color": "red", "value": 0.2}]}}, "overrides": []}},
    {"id": 3, "type": "stat", "title": "p95 latency (alert threshold 500ms)", "gridPos": {"x": 12, "y": 0, "w": 6, "h": 4}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "max(job:myapp_http_request_duration_seconds:p95_5m{job=\"myapp\"})"}],
     "fieldConfig": {"defaults": {"unit": "s",
       "thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": null}, {"color": "red", "value": 0.5}]}}, "overrides": []}},
    {"id": 4, "type": "stat", "title": "Redis dependency", "gridPos": {"x": 18, "y": 0, "w": 6, "h": 4}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "min(myapp_redis_up)"}],
     "fieldConfig": {"defaults": {"mappings": [{"type": "value", "options": {"0": {"text": "DOWN", "color": "red"}, "1": {"text": "UP", "color": "green"}}}],
       "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 1}]}}, "overrides": []}},
    {"id": 5, "type": "timeseries", "title": "Request rate (by status)", "gridPos": {"x": 0, "y": 4, "w": 12, "h": 8}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "sum by (status) (job_route_status:myapp_http_requests:rate5m{job=\"myapp\"})", "legendFormat": "{{status}}"}],
     "fieldConfig": {"defaults": {"unit": "reqps", "custom": {"stacking": {"mode": "normal"}, "fillOpacity": 20}}, "overrides": []}},
    {"id": 6, "type": "timeseries", "title": "Latency quantiles", "gridPos": {"x": 12, "y": 4, "w": 12, "h": 8}, "datasource": $DS,
     "targets": [
       {"refId": "A", "expr": "histogram_quantile(0.50, job_le:myapp_http_request_duration_seconds_bucket:rate5m{job=\"myapp\"})", "legendFormat": "p50"},
       {"refId": "B", "expr": "job:myapp_http_request_duration_seconds:p95_5m{job=\"myapp\"}", "legendFormat": "p95"},
       {"refId": "C", "expr": "histogram_quantile(0.99, job_le:myapp_http_request_duration_seconds_bucket:rate5m{job=\"myapp\"})", "legendFormat": "p99"}],
     "fieldConfig": {"defaults": {"unit": "s", "custom": {"thresholdsStyle": {"mode": "line+area"}},
       "thresholds": {"mode": "absolute", "steps": [{"color": "transparent", "value": null}, {"color": "red", "value": 0.5}]}}, "overrides": []}},
    {"id": 7, "type": "alertlist", "title": "Active alerts", "gridPos": {"x": 0, "y": 12, "w": 12, "h": 8},
     "options": {"viewMode": "list", "groupMode": "default", "maxItems": 20, "sortOrder": 1,
       "stateFilter": {"firing": true, "pending": true, "normal": false, "error": true, "noData": true}}},
    {"id": 8, "type": "timeseries", "title": "USE: node CPU utilisation / memory utilisation", "gridPos": {"x": 12, "y": 12, "w": 12, "h": 8}, "datasource": $DS,
     "targets": [
       {"refId": "A", "expr": "1 - avg(rate(node_cpu_seconds_total{mode=\"idle\"}[5m]))", "legendFormat": "CPU"},
       {"refId": "B", "expr": "1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes", "legendFormat": "Memory"}],
     "fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []}},
    {"id": 9, "type": "timeseries", "title": "USE: saturation (load1 / CPU cores)", "gridPos": {"x": 12, "y": 20, "w": 12, "h": 6}, "datasource": $DS,
     "targets": [{"refId": "A", "expr": "node_load1 / count without (cpu, mode) (node_cpu_seconds_total{mode=\"idle\"})", "legendFormat": "{{instance}}"}],
     "fieldConfig": {"defaults": {"unit": "none", "decimals": 2}, "overrides": []}}
  ]
}
EOF
jq '.panels | length' grafana/dashboards/myapp-overview.json
sleep 35      # Lesson 1's provider scans the directory every 30 seconds
curl -s -u $GF 'localhost:3000/api/search?query=myapp' | jq -r '.[] | "\(.uid)\t\(.title)"'
9
myapp-overview	myapp service overview (RED + USE)
myapp-red	myapp RED

Heredoc without quotes: $DS is replaced with the data source object when generated. legendFormat The {{status}} does not contain $, so it is kept as is. Open the promlab folder in Grafana to see the result (myapp-red the title follows Lesson 1). The Lesson 1 provider is set to allowUiUpdates: true, so changes can be saved in the UI, but the JSON file remains the only source of truth — in production, changes should be written back to the file and committed.

Add dashboard links to alert annotations: in prometheus/rules/myapp-alerts.yml the MyappHighErrorRate (two) annotations, add:
          dashboard: "http://localhost:3000/d/myapp-overview"
docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp-alerts.yml && docker compose kill -s SIGHUP prometheus

Note: in the unit tests, the exp_annotations must also be added dashboard, otherwise promtool test rules will fail — this is exactly the value of unit tests (the capstone lab will run them again).

Verify “dashboard and alerts are consistent”: stop Redis for 1 minute and observe the “Redis dependency” panel turn red and RedisDown appear in the “Active alerts” panel (if the alert list only shows Grafana-managed alerts, choose Alertmanager / data source rules in the panel options; the option name depends on the current version), then restore Redis.
docker compose stop redis; sleep 90; docker compose start redis

Case 1: an incident review finds “the dashboard is green but the alert is red”

Problem: The alert uses rate(...[5m]), while the dashboard uses rate(...[$__rate_interval]) and averages by instance; the values disagree, and on-call mistook it for a false alarm. Approach: Alerts and the overview panels use the same recording rule; threshold lines are drawn on the panels. Limits: Exploratory panels may still use $__rate_interval, but the overview’s “traffic lights” must come from the same source as the alerts.

Case 2: a “god dashboard” with 120 panels

Problem: All metrics are piled into one dashboard; it loads slowly, the key points are hard to find, and Prometheus query concurrency is saturated. Approach: Split into L0/L1/L2; L1 has at most 15 panels per service, with secondary rows collapsed by default; drill down using data links. Limits: After splitting, links and variables must be kept consistent; it is recommended to generate them from code (Grafonnet / Terraform, Lesson 5).

Case 3: woken up at night, not knowing where to look

Problem: The alert notification contains only one phrase, “HighErrorRate”. Approach: Every page-level alert carries runbook_url and dashboard annotations; the first step of the runbook is “open this dashboard and look at these three panels”. Limits: The runbook needs to be maintained as the system changes; it is recommended to review it in the same repository as the rules.

Common errors and fixes

The panel shows "No data", but the data can be queried in Prometheus

Cause: the data source UID does not match; the recording rule was just created and has no data in the time range yet; the query job labels do not match the actual labels.

Fix: Panel → Inspect → Query to check the actual request and response; confirm datasource.uid; shorten the time range.

Dashboard title or uid already exists / two dashboards with the same name appear after provisioning

Cause: a dashboard with the same uid already exists in the UI, or two providers point to the same JSON.

docker compose logs grafana --since 5m | grep -i dashboard

Fix: give each JSON a fixed, unique uid; provider directories must not overlap.

Ratio panel shows 2000%

Cause: the data is a 0–1 ratio but the percent (0–100) unit is used, or vice versa.

Fix: use percentunit for 0–1 data.

The p95 curve is very jagged or stays exactly on a bucket boundary

Cause: histogram buckets are too coarse (for example, no buckets between 0.1 and 1); the quantile is an estimate from linear interpolation within a bucket; with low traffic there are few samples.

Fix: add buckets near the SLO threshold (Lesson 1’s myapp buckets run from 0.005 to 5); look at a Heatmap under low traffic; consider native histograms (Lesson 7).

Command-line tasks
1. Export the JSON for myapp-overview (remove id and version, so it is easy to commit to Git).
curl -s -u $GF localhost:3000/api/dashboards/uid/myapp-overview | jq '.dashboard | del(.id, .version)' > myapp-overview.json
2. Name one usable metric for “memory saturation” in USE (node-exporter).
rate(node_vmstat_pgmajfault[5m])        # major page-fault rate: rises when memory is short
# or: swap usage (if swap is enabled)
1 - node_memory_SwapFree_bytes / node_memory_SwapTotal_bytes
Scenario analysis
The product manager wants a “system health score” (0–100) on a big screen, computed as a weighted sum of 20 metrics. How do you respond?

You can show a simple overall status on the big screen, but do not use an unexplainable weighted score: when the score drops, nobody knows why, and the weights are hard to maintain. Use SLOs (Lesson 6) to express health: for example “availability over the past 30 days is 99.95%, with 62% of the error budget remaining”, together with each service’s RED traffic light; clicking drills down to the L1 dashboard. Metrics like this share the same source as alerts, and are explainable and actionable.

Verified teaching videos

▶
Tom Wilkie [Kausal] | The Red Method: How To Instrument Your Services | InfluxDays 2018 — InfluxData
English · presented by the author of the RED method
▶
SRE Golden Signals Explained — IBM Technology
English · the four golden signals concept
▶
Grafana Campfire 🔥- Data Visualization Tips and Best Practices (Grafana Community Call- April 2025) — Grafana
English · visualisation best practices from the Grafana official channel
▶
Grafana Dashboards: RED & USE Methods for Production — Gheware DevOps AI
English · hands-on RED/USE dashboards

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–30s
Scene: three cards (RED, USE, golden signals) flip open, and the metric names fall into a Venn diagram.
Narration: RED looks at services, USE looks at resources, and the golden signals put latency, traffic, errors and saturation together.
Shot 2 · 30–60s
Scene: a cluttered 120-panel dashboard is split into three layers; the first layer keeps only four large numbers.
Narration: dashboards are layered, each layer answers one question, and the most important status sits at the top.
Shot 3 · 60–90s
Scene: the link in an alert notification opens directly to the matching panel; the red threshold line on the panel matches the alert threshold.
Narration: panels and alerts use the same recording rule and the same threshold, so the on-call person sees exactly the number that triggered the alert.
or score ≥ 70% on the quiz

Module 7 · Storage, retention and capacity planning

42:00 – 50:00 · Prometheus is a single-node database: when the disk fills or memory runs short, the alerting system fails along with it
8 min1–2 bytes / sampleretention can already be written in the config file★★★★☆
Learning objectives
  • Describe the structure of the local TSDB: head block (memory + mmap chunks), WAL, 2-hour persistent blocks, and background compaction (up to 10% of the retention period or 31 days, whichever is smaller).
  • Configure retention policies: time, size, percentage (experimental); know that 3.16 recommends writing them in the config file storage.tsdb.retention, and that “whichever triggers first wins”.
  • Use the official formulas needed_disk_space = retention_time_seconds × ingested_samples_per_second × bytes_per_sample to estimate disk, estimate memory from measured metrics, and plan for the data of Alertmanager / Grafana.
Prerequisites: The scraping and sample concepts from Lesson 1. Importance:★★★★☆ (for in-depth TSDB internals and cardinality troubleshooting, see Lesson 7)

What: components of local storage (official Storage documentation)

PartLocationDescription
Head blockMemory + chunks_head/ (mmap)data from roughly the last 2–3 hours; all active series have an index in memory; the main source of memory consumption
WALwal/ (out-of-order samples have a separate wbl/)write-ahead log, replayed after a crash to restore the head; compression enabled by default (since 2.20); split into 128MB segments
persistent blocks01H…/ directory: chunks/,index,meta.json,tombstonesevery 2 hours the data in the head is cut into one block; in the background, small blocks are compacted into larger ones (spanning at most 10% of the retention period or 31 days, whichever is smaller)

Why: why planning matters

  • disk full → writes and compaction fail, Prometheus may not start, and alerting rules stop working as a result.
  • not enough memory → OOM restart → WAL replay (large instances can take minutes) → no scraping and no alerts in the meantime.
  • Retention determines how far back you can ask questions (period-over-period comparisons, capacity trends), and it also determines cost. Long-term storage goes to Thanos/Mimir/managed services (Lessons 3, 4, 6).
  • Officially: local storage is not clustered and not replicated; does not support NFS (including AWS EFS) or other non-POSIX filesystems.

How: retention policies

Setting3.16 config fileCommand line (deprecated, still works)Description
Timestorage.tsdb.retention.time--storage.tsdb.retention.timedefault if neither is set 15d; units y w d h m s ms
Sizestorage.tsdb.retention.size--storage.tsdb.retention.sizemust have a unit (512MB,20GB, computed in powers of 2); only persistent blocks are deleted, but the WAL and mmap chunks count toward the total
Percentage (experimental)storage.tsdb.retention.percentage—as a percentage of total disk capacity; when set, size is ignored; startup fails if disk capacity cannot be read
  • when both time and size are set,whichever triggers first takes effect; expired blocks are deleted in the background, with a delay of up to 2 hours (a block must expire in full before it is deleted).
  • Retention settings in the config file can take effect at runtime via reload, and take precedence over command-line flags (official configuration docs).
  • Official recommendation: retention.size set at most to 80–85% of disk capacity, leaving 15–20% as temporary space for old and new blocks to coexist during compaction.

Capacity formula

needed_disk_space = retention_time_seconds × ingested_samples_per_second × bytes_per_sample
# bytes_per_sample: official average is 1–2 bytes (after compression)
# ingested_samples_per_second ≈ number of active series ÷ scrape interval (seconds)

Example: 50,000 active series, 15s scrape → about 3,333 samples/s; 15 days, 1.5 bytes/sample → 3,333 × 1.5 × 86,400 × 15 ≈ 6.5 GB, plus WAL and compaction headroom, so at least 10 GB of disk. Official tip: when lowering the sample rate,reducing the number of series is usually more effective than lengthening the scrape interval (samples within the same series compress very well).

Memory estimation

The official docs give no fixed formula; memory mainly depends on the number of active series in the head, label length and query load. It is recommended to estimate from measured ratios: process_resident_memory_bytes / prometheus_tsdb_head_series This gives “bytes per series”; multiply by the target number of series, then leave at least 50% headroom for queries and peaks. A community rule of thumb is on the order of KB per active series; for rough estimates only.

When: what to adjust

SymptomWhat to do first
Disk grows faster than expectedcheck ingestion rate and top metrics (/api/v1/status/tsdb); drop metrics you do not use (metric_relabel_configs drop)
Memory approaches the limitcheck head series and churn; limit sample_limit/label_limit (Lesson 7); split Prometheus
Need to retain more than 1 yearkeep 15–30 days locally + remote storage / Thanos / Mimir (Lesson 6)
Common misconceptions① “setting retention.size=100GB means a 100GB disk is enough”: WAL, mmap chunks and compaction temporary space also use disk; the official advice is to leave 15–20%. ② “lengthening the scrape interval saves much disk”: the effect is limited, deleting unused series is more effective, and scrape intervals longer than 2 minutes cause data to be treated as stale. ③ “putting the data directory on NFS/EFS for durability”: officially not supported. ④ “recording rules take no space”: they are real series and count toward storage too (though usually far fewer than raw series). ⑤ “Alertmanager does not need persistence”: silences and the notification log live in --storage.path, and if they are lost, silences disappear and notifications may be repeated.

How samples flow from scrape to deletion

Scrape / rulessample append3,333 samples/s Head (memory)active series index + current chunkchunk full at 120 samples → mmapchunks_head/≈ the last 2–3 hours WAL (wal/)crash recovery: replayed on restart every 2h persistent block (2h)chunks/ index meta.jsonimmutable1–2 bytes / sample compacted large blockspan ≤ min(10% of retention,31 days)old and new coexist during compaction retention policy (background, ≤ 2h delay)time: deleted only once the whole block has expiredsize / percentage: delete starting from the oldest blockif both are set: whichever triggers first wins memory ≈ number of head series × bytes per series (measured) + query overheaddisk ≈ retention seconds × samples/s × 1–2 bytes + WAL + 15–20% headroom
Figure 7-1: memory is determined by active series; disk is determined by sample rate × retention period

Interactive: Prometheus capacity calculator

Estimate disk using the official formula; estimate memory using “bytes per series” (the default 4 KiB is only a rough estimate; replace it with the ratio measured in the lab).

Capacity-related metrics, interfaces and commands

Metric / interface / commandMeaning
rate(prometheus_tsdb_head_samples_appended_total[5m])ingestion rate (samples/s), the ingested_samples_per_second in the formula
prometheus_tsdb_head_seriesnumber of active series in the head
prometheus_tsdb_storage_blocks_bytesbytes occupied by persistent blocks
prometheus_tsdb_head_chunks_storage_size_bytesbytes occupied by mmap head chunks
prometheus_tsdb_wal_storage_size_bytesWAL size
prometheus_tsdb_retention_limit_seconds / _bytesretention limits currently in effect
prometheus_tsdb_time_retentions_total / size_retentions_totalnumber of times blocks were deleted due to time / size
GET /api/v1/status/runtimeinfostorageRetention and other runtime information
GET /api/v1/status/tsdbhead statistics, top 10 series counts by metric name / label
promtool tsdb analyze DATA_DIRanalyse blocks: series count, label cardinality, the “most expensive” labels
promtool tsdb list DATA_DIRlist the time range and sample count of blocks
curl -s localhost:9090/api/v1/status/runtimeinfo | jq '.data | {storageRetention, timeSeriesCount: .timeSeriesCount, corruptionCount}'
curl -s localhost:9090/api/v1/status/tsdb | jq -r '.data.seriesCountByMetricName[] | "\(.value)\t\(.name)"' | head -5
{
  "storageRetention": "15d",
  "timeSeriesCount": null,
  "corruptionCount": 0
}
1173	node_cpu_seconds_total
…

The set of runtimeinfo fields varies by version; use the actual output as the reference; use jq '.data' to see all fields.

Lab 7: measure, calculate and set retention (about 7 minutes)

Measure the current ingestion rate, series count, memory and disk:
q(){ curl -s localhost:9090/api/v1/query --data-urlencode "query=$1" | jq -r '.data.result[] | .value[1]'; }
echo "samples/s:      $(q 'sum(rate(prometheus_tsdb_head_samples_appended_total[5m]))')"
echo "head series:    $(q 'prometheus_tsdb_head_series')"
echo "RSS bytes:     $(q 'process_resident_memory_bytes{job="prometheus"}')"
echo "bytes per series:   $(q 'process_resident_memory_bytes{job="prometheus"} / on(instance) prometheus_tsdb_head_series')"
echo "block bytes:       $(q 'prometheus_tsdb_storage_blocks_bytes')"
echo "WAL bytes:     $(q 'prometheus_tsdb_wal_storage_size_bytes')"
samples/s:      182.4
head series:    2734
RSS bytes:     118734848
bytes per series:   43428.0
block bytes:       5642719
WAL bytes:     21894112

For small instances, the “bytes per series” figure is inflated by fixed overhead (Go runtime, query engine, caches) and has no reference value; when planning for production, measure on an instance close to the target scale.

Calculate using the formula: estimate the disk needed for 7 days using the measured sample rate:
SPS=$(q 'sum(rate(prometheus_tsdb_head_samples_appended_total[5m]))')
python3 -c "s=float('$SPS'); d=7*86400; print(f'7 days ≈ {s*d*1.5/1024**2:.0f} MiB (1.5 bytes/sample)')"
7 days ≈ 105 MiB (1.5 bytes/sample)
Set retention in the config file (3.16 recommended method; can be reloaded at runtime). In prometheus/prometheus.yml append at the top level:
storage:
  tsdb:
    retention:
      time: 10d
      size: 2GB         # adjust as needed for the lab disk; in production keep it within 80–85% of disk capacity
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml
docker compose kill -s SIGHUP prometheus; sleep 3
curl -s localhost:9090/api/v1/status/runtimeinfo | jq -r '.data.storageRetention'
echo "limit seconds: $(q 'prometheus_tsdb_retention_limit_seconds')  bytes: $(q 'prometheus_tsdb_retention_limit_bytes')"
 SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax
10d or 2GiB
limit seconds: 864000  bytes: 2147483648

In Lesson 1’s Compose file, the command command already sets --storage.tsdb.retention.time=7d; the value in the config file takes precedence (so 10d is effective), and the log will show a deprecation notice for the flag. It is recommended to then remove this command-line flag from compose.yaml the command, keeping only the setting in the config file. storageRetention The display format of the output depends on the actual version.

Analyse blocks (requires at least one persisted block; if the environment has run for less than 2–3 hours, it may report that there are no blocks):
docker compose exec prometheus promtool tsdb list /prometheus | head -5
docker compose exec prometheus promtool tsdb analyze /prometheus | sed -n '1,25p'
BLOCK ULID                  MIN TIME       MAX TIME       DURATION  NUM SAMPLES  NUM CHUNKS  NUM SERIES  SIZE
01JD…                       1763200800000  1763208000000  2h0m0s    1302841      11488       2731        2.1MiB
Block ID: 01JD…
Duration: 2h0m0s
Total Series: 2731
Label names: 41
Postings (unique label pairs): 1385
Postings entries (total label pairs): 21874

Label pairs most involved in churning:
…
Highest cardinality labels:
1173 cpu …

Data directory /prometheus from Lesson 1’s --storage.tsdb.path=/prometheus (data volume prom-data).

Check persistence for Alertmanager data:
docker compose exec alertmanager ls /alertmanager
docker volume ls | grep am-data
nflog  silences
local     promlab_am-data

nflog is the notification log,silences is silences; they are cleaned up according to --data.retention (default 120h).

Case 1: disk filled over the weekend, Prometheus would not start

Problem: Only retention.time=30d was set, and a release introduced metrics with request_id labels, and sample volume grew tenfold. Approach: Also set retention.size (80% of disk) as a fallback; create alerts for predict_linear(node_filesystem_avail_bytes{mountpoint="/prometheus"}[6h], 24*3600) < 0 ; use metric_relabel_configs to drop that label. Limits: size-based retention deletes old data early, so alerts must show that “effective retention has shortened” (prometheus_tsdb_size_retentions_total growth rate).

Case 2: Prometheus takes 8 minutes to restart after an OOM

Problem: 3 million active series; WAL replay takes a long time, and there are no alerts during that period. Approach: Split Prometheus by team / function; deploy two highly available instances with identical configuration (Alertmanager deduplicates automatically); reduce churn. Limits: The data of an HA pair is not merged; a global view requires Thanos / Mimir (Lesson 6).

Case 3: data directory on EFS, block corruption

Problem: To make persistence “easier”, the TSDB was placed on a network file system, and corruption and locking problems appeared. Approach: Following the official advice, switch to local block storage (EBS / Azure Disk); backups use the snapshot API (requires --web.enable-admin-api) or block storage snapshots. Limits: A plain copy without a snapshot may be missing roughly the last 2–3 hours of data.

Common errors and fixes

opening storage failed: … no space left on device
docker compose exec prometheus df -h /prometheus
docker compose exec prometheus du -sh /prometheus/wal /prometheus/chunks_head

Fix: Expanding the disk is the safest; in an emergency you can delete the oldest block directory (losing data for that period); do not delete WAL segments in use; then set size retention.

retention.time=7d is set, but data from 8 days ago is still on disk

Cause: blocks must entirely expire before they are deleted; compacted large blocks can span up to 10% of the retention period; cleanup runs in the background and may be delayed.

Fix: This is normal; when planning, estimate as “retention period + one maximum block span”.

field retention not found in type config.TSDBConfig

Cause: The Prometheus version is old, and the config file does not yet support storage.tsdb.retention.

Fix: Upgrade to 3.16 (this lesson’s baseline), or keep using the --storage.tsdb.retention.time/size command-line flag.

WAL replay is slow / memory spikes after a restart
docker compose logs prometheus | grep -iE 'replay|WAL'

Fix: Reduce active series and churn; confirm WAL compression has not been disabled; the memory limit must cover the replay peak. For deeper analysis, see Lesson 7.

Command-line tasks
1. Write an alert: the Prometheus data volume will be full within 24 hours.
- alert: PrometheusDiskWillFillIn24h
  expr: predict_linear(node_filesystem_avail_bytes{mountpoint="/prometheus"}[6h], 24*3600) < 0
  for: 30m
  labels: {severity: warning, service: prometheus}

node-exporter must be able to see this mount point (in container deployments, the host root is usually mounted; the mount point name depends on the actual setup).

2. Find the 5 metric names with the most series.
curl -s localhost:9090/api/v1/status/tsdb | jq -r '.data.seriesCountByMetricName[:5][] | "\(.value)\t\(.name)"'
Scenario analysis
Requirement: keep 13 months of metrics for annual capacity comparison, with a single-node Prometheus on a 2 TB local disk. Is it OK to just set retention.time=400d?

It is technically possible but not recommended: a single point with no replication means a disk or node failure loses all history; with a long retention period, queries over long ranges are slow, compacted blocks grow, and restart and maintenance risk rises. It is better to keep 15–30 days locally, send annual data via remote_write to Mimir / Thanos (object storage + downsampling) or a managed cloud service (Lessons 3, 4, 6), and keep only aggregated recording-rule series for long-term analysis to control cost.

Verified teaching videos

▶
PromCon EU 2019: Practical Capacity Planning Using Prometheus — Prometheus Monitoring
English · Prometheus official channel, capacity planning with Prometheus
▶
PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable — Prometheus Monitoring
English · TSDB internals and production issues
▶
Prometheus and Grafana : 15 - Storage, Retention and Cardinality — Oddly Yogi
English · storage, retention and cardinality concepts

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–30s
Scene: samples flow into the head (memory) and are written to the WAL at the same time; every 2 hours a block is cut and written to disk.
Narration: the last two or three hours of data sit in the head in memory, and the WAL ensures recovery after a crash.
Shot 2 · 30–60s
Scene: small blocks are compacted into large blocks; the oldest large block disappears entirely once the retention period is reached.
Narration: retention deletes whole blocks; whichever of time or size triggers first is the one applied.
Shot 3 · 60–90s
Scene: formula: retention seconds × samples per second × 1.5 bytes, with 20% headroom added to the result.
Narration: estimate disk with the official formula, estimate memory from measured per-series memory, and leave room for compaction.
or score ≥ 70% on the quiz

Module 8 · Production-readiness review and common mistakes

50:00 – 60:00 · “No alerts” only means “all is well” once you can prove the monitoring system itself is working
10 minWatchdog · meta-monitoringScorecard + troubleshooting tree★★★★★
Learning objectives
  • Use a six-dimension alerting production-readiness checklist Review monitoring: rule quality, routing and notifications, operability, monitoring itself, capacity, and process.
  • Deploy rules that “monitor the monitoring system”: Watchdog (dead man’s switch), rule evaluation failures, configuration reload failures, Prometheus → Alertmanager sending failures, and notification failures.
  • Identify and fix the most common alerting mistakes: thresholds with no basis, no for, labels with volatile values, no runbook, alert fatigue, and notifications silently swallowed by silences.
Prerequisites: Modules 1–7. Importance:★★★★★

What: alerting production-readiness checklist

DimensionChecksCorresponding module
Rule qualitysymptoms first; every page alert is actionable; has for; thresholds are backed by evidence (SLO / historical data); expressions reference recording rules; promtool check + test rules runs in CIM1, M2
Labels and annotationsconsistent severity (critical/warning/info),service,team; no $value; annotations include summary, description, runbook_url, dashboardM2, M6
Routing and notificationscritical is staffed (PagerDuty etc.); warning goes to a team channel; grouping is sensible; inhibition avoids duplicates; send_resolved is explicit; secrets are referenced via *_file; amtool config routes test asserted in CIM3, M4
Monitoring itselfWatchdog external heartbeat; alerts exist for rule failures, reload failures, notification failures and disappearing targets; Alertmanager is highly available; Prometheus runs as an HA pair or at least recovers quicklyM8
Capacity and storageretention meets requirements; disk headroom with predictive alerts; memory headroom; Alertmanager data is persistedM7
Processsilences must have a comment and an expiry; review alerts weekly (delete false positives and alerts that need no action); review alerts and dashboards when a new service goes liveM3, M8

Why: monitoring systems break too

Prometheus configuration is wrong, rule queries error out, Alertmanager cannot reach Teams, or the whole monitoring host loses power — in these cases the number of notifications you receive is zero, which is indistinguishable from “all is well”. So you must have one alert that is always firing (Watchdog), and a service outside the monitoring system checks whether it arrives on time: when the heartbeat stops, the external service pages on-call.

How: meta-monitoring rule set

AlertExpressionDescription
Watchdogvector(1)always firing; routed to the heartbeat receiver,repeat_interval very short
PrometheusRuleEvaluationFailuresincrease(prometheus_rule_evaluation_failures_total[5m]) > 0rule query errors (for example many-to-many matching)
PrometheusRuleGroupMissedIterationsincrease(prometheus_rule_group_iterations_missed_total[10m]) > 0rule group too slow
PrometheusConfigReloadFailedprometheus_config_last_reload_successful == 0configuration is wrong, still running the old configuration
PrometheusNotificationsFailingrate(prometheus_notifications_errors_total[5m]) > 0Prometheus → Alertmanager sending failures
PrometheusAlertmanagerNotConnectedprometheus_notifications_alertmanagers_discovered < 1no Alertmanager discovered
AlertmanagerConfigReloadFailedalertmanager_config_last_reload_successful == 0Alertmanager configuration is wrong
AlertmanagerNotificationsFailingrate(alertmanager_notifications_failed_total[5m]) > 0notifications cannot be delivered (per integration)
TargetDownup == 0 (per job ratio)any scrape target failure

kube-prometheus-stack ships a whole set of similar rules (Lesson 5); this lesson writes out the most critical part by hand so that you understand what each one means.

When: when to review

  • Before a new service goes live (review alerts, dashboards and runbooks together).
  • After every incident review: “Did the alert fire in time? Did it reach the right people? Was there noise?”
  • Weekly / monthly: count how often each alert fires and what share of firings were acted on; delete or downgrade alerts that never need action.
Top 8 common mistakes① no for, so transient spikes page. ② thresholds picked by gut feeling (“CPU > 80%”), unrelated to user experience. ③ $value placed in labels, creating countless alert instances. ④ every alert is critical, so on-call becomes numb. ⑤ no runbook, so people do not know what to do when an alert arrives. ⑥ root route group_by: ['...'], so one incident sends hundreds of notifications. ⑦ overly broad or overly long silences swallow real incidents. ⑧ no Watchdog, so nobody notices when the monitoring system goes down.

Dead man’s switch

PrometheusWatchdog = vector(1)always firing Alertmanagerroute → heartbeatrepeat_interval 1m once a minute external heartbeat service(an infrastructure / SaaS servicedifferent from the monitoring system)expected interval + grace period on-callheartbeat stopsthen pages A failure anywhere in the chain (Prometheus down, rules not loaded, Alertmanager down, network, notification channel) stops the heartbeatThis lab demonstrates this with the local webhook’s /heartbeat path; in production, a service outside the monitoring system must be used
Figure 8-1: the reverse alert that “rings all the time when normal and goes quiet when something is wrong”

Alert quality funnel

All possible alert conditions (metrics, logs, events) affecting users or about to affect users (symptoms / capacity forecasts) needs a person to act immediately → page (critical)
Figure 8-2: only a small part at the bottom of the funnel should be able to reach page

Interactive: alerting production-readiness scorecard

Score each item against your environment (or the capstone lab results). Scores for each dimension and the total are calculated live, and the highest-priority improvement is suggested. Results are saved in this browser.

Queries and commands commonly used in reviews

Query / commandPurpose
sum by (alertname) (changes(ALERTS{alertstate="firing"}[7d]))estimate how many state changes each alert has in 7 days (flapping / noise ranking)
count by (severity) (ALERTS{alertstate="firing"})current alert count per severity
alertmanager_silences{state="active"}number of active silences
curl -s localhost:9090/api/v1/rules | jq '[.data.groups[].rules[] | select(.type=="alerting" and (.annotations.runbook_url == null))] | map(.name)'find alerts with no runbook
promtool check rules / test rules,amtool check-config / config routes testCI gate
curl -s localhost:9090/api/v1/rules | jq -r '[.data.groups[].rules[] | select(.type=="alerting" and (.annotations.runbook_url == null))] | map(.name) | unique | .[]'
MyappHighLatencyP95
MyappRedisUnavailable
MyappTargetMissing
RedisDown

The output is the list of runbooks still to be written.

Lab 8: deploy meta-monitoring and perform fault injection (about 9 minutes)

Write the meta alerting rules:
groups:
  - name: meta-alerts
    interval: 15s
    labels:
      env: lab
    rules:
      - alert: Watchdog
        expr: vector(1)
        labels:
          severity: none
        annotations:
          summary: "Alerting pipeline heartbeat: this alert should always be firing"

      - alert: PrometheusRuleEvaluationFailures
        expr: increase(prometheus_rule_evaluation_failures_total[5m]) > 0
        for: 1m
        labels: {severity: warning, service: prometheus}
        annotations:
          summary: "Rule group {{ $labels.rule_group }} evaluation failed"

      - alert: PrometheusConfigReloadFailed
        expr: prometheus_config_last_reload_successful == 0
        for: 1m
        labels: {severity: warning, service: prometheus}
        annotations:
          summary: "Prometheus configuration reload failed; still using the old configuration"

      - alert: PrometheusNotificationsFailing
        expr: rate(prometheus_notifications_errors_total[5m]) > 0
        for: 2m
        labels: {severity: critical, service: prometheus}
        annotations:
          summary: "Prometheus failed to send alerts to Alertmanager"

      - alert: AlertmanagerConfigReloadFailed
        expr: alertmanager_config_last_reload_successful == 0
        for: 1m
        labels: {severity: warning, service: alertmanager}
        annotations:
          summary: "Alertmanager configuration reload failed"

      - alert: AlertmanagerNotificationsFailing
        expr: sum by (integration) (rate(alertmanager_notifications_failed_total[5m])) > 0
        for: 1m
        labels: {severity: warning, service: alertmanager}
        annotations:
          summary: "Notifications failed for Alertmanager’s {{ $labels.integration }}"

      - alert: TargetDown
        expr: 100 * (1 - avg by (job) (up)) > 10
        for: 5m
        labels: {severity: warning, service: monitoring}
        annotations:
          summary: "{{ $value | humanize }}% of {{ $labels.job }} targets cannot be scraped"
cd ~/promlab
docker compose exec prometheus promtool check rules /etc/prometheus/rules/meta-alerts.yml
docker compose kill -s SIGHUP prometheus
sleep 75
docker compose logs --no-log-prefix webhook --since 70s | grep heartbeat
Checking /etc/prometheus/rules/meta-alerts.yml
  SUCCESS: 7 rules found

14:52:16 POST /heartbeat receiver=heartbeat status=firing alerts=1 [Watchdog] groupLabels={"alertname": "Watchdog", "env": "lab"}
14:53:16 POST /heartbeat receiver=heartbeat status=firing alerts=1 [Watchdog] groupLabels={…}

The heartbeat route is not covered group_by, inheriting from the root route’s [alertname, env, service]; Watchdog has no service label, so it is grouped by an empty value. The once-a-minute heartbeat comes from repeat_interval: 1m. AlertmanagerNotificationsFailing Depends on the alertmanager scrape job added in Module 0.

Fault injection 1: write a broken rule file, observe the configuration reload failure alert:
printf 'groups:\n  - name: broken\n    rules:\n      - alert: Broken\n        expr: sum(\n' > prometheus/rules/zz-broken.yml
docker compose kill -s SIGHUP prometheus; sleep 5
docker compose logs prometheus --since 30s | grep -iE 'error|reload' | tail -n 2
sleep 75
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | select(.labels.alertname=="PrometheusConfigReloadFailed") | .state'
time=… level=ERROR source=main.go msg="Error reloading config" err="one or more errors occurred while applying the new configuration (--config.file=\"/etc/prometheus/prometheus.yml\")"
time=… level=ERROR … msg="loading groups failed" err="/etc/prometheus/rules/zz-broken.yml: 5:15: group \"broken\", rule 1, \"Broken\": could not parse expression: …"
firing

When a reload fails, Prometheus keeps using the old configuration, and all existing alerts still work. This is why failures must themselves be alerted on; otherwise you will think the new rules are in effect.

Fix:
rm prometheus/rules/zz-broken.yml
docker compose kill -s SIGHUP prometheus; sleep 3
curl -s localhost:9090/api/v1/query --data-urlencode 'query=prometheus_config_last_reload_successful' | jq -r '.data.result[0].value[1]'
1
Fault injection 2: Alertmanager down, observe the heartbeat stop and the Prometheus-side errors:
docker compose stop alertmanager
sleep 150
docker compose logs --no-log-prefix webhook --since 140s | grep -c heartbeat
curl -s localhost:9090/api/v1/query --data-urlencode 'query=sum(increase(prometheus_notifications_errors_total[2m]))' | jq -r '.data.result[0].value[1]'
docker compose start alertmanager
0
6

Heartbeat count is 0: if the external heartbeat service is monitoring /heartbeat, it will page on-call right away. But PrometheusNotificationsFailing itself cannot send notifications (Alertmanager is down). This is exactly why Watchdog must be judged by an external system. After Alertmanager recovers, Prometheus resends the still-firing alerts on its next resend cycle.

Review: open the scorecard on the “Animation” page, score it against your environment, and record the top three improvement items.

Case 1: no alerts for three days, and it turned out Alertmanager had been unable to reach Teams all along

Problem: The Teams webhook broke; the Alertmanager log filled with failure records, but nobody read the logs. Approach: add AlertmanagerNotificationsFailing, and route it to another channel (for example email or PagerDuty); hand the Watchdog heartbeat to an external service. Limits: If all channels share the same network egress, they can still fail at the same time; the external heartbeat is the last line of defence.

Case 2: taming alert fatigue

Problem: One team received 400 notifications a week, of which fewer than 20 needed action. Approach: use changes(ALERTS{alertstate="firing"}[7d]) to find the top 10 noisy alerts; delete alerts that need no action, downgrade cause-type alerts to warning and notify only during working hours (active_time_intervals), add for/keep_firing_for for flapping alerts; review weekly. Results: notification volume dropped by 85%, and only symptom alerts remain at page level. Limits: Noise reduction must be coordinated with SLOs (Lesson 6); otherwise important alerts are easily deleted by mistake.

Case 3: a maintenance silence swallowed another team’s alerts

Problem: While maintaining the database, a silence was created with env="prod" too broad a matcher. Approach: Silence policy: must include a severity service/instance level matcher, the duration must be ≤ the maintenance window, the comment must include a ticket number; regularly audit using alertmanager_silences amtool and the API. Limits: Only process and auditing can enforce this; Alertmanager does not stop overly broad silences.

Interactive troubleshooting tree: “alerts are not arriving as expected”

Work step by step from the symptom: Prometheus rules → Prometheus to Alertmanager → inside Alertmanager → notification channels.

Quick reference for common errors

The Watchdog heartbeat arrives every minute, but real alerts are not notified

Cause: the pipeline as a whole is healthy; the problem is in a specific rule or route: the rule is not loaded / the expression returns nothing / it is inhibited or silenced / it routes to a receiver nobody watches.

curl -s localhost:9090/api/v1/rules?type=alert | jq -r '.data.groups[].rules[] | "\(.name)\t\(.state)\t\(.health)"'
docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093 alert query -s -i -o extended
The same fault produces both a critical and a warning notification

Cause: missing the inhibition rule “critical suppresses warning with the same name”, or equal the labels in the equal list are inconsistent on both sides.

Fix: refer to the critical-mutes-same-warning in Module 3.

The alert has resolved, but the incident in the on-call system stays open

Cause: the receiver’s send_resolved: false send_resolved (email/slack default to false); or the alert simply disappears from Prometheus (the rule was deleted), and Alertmanager waits until endsAt expires before treating the alert as resolved.

Fix: explicitly set send_resolved: true send_resolved; before deleting a rule, confirm there are no active alerts.

Command-line tasks
1. List the 5 alerts with the most firing state changes in the past 24 hours.
topk(5, sum by (alertname) (changes(ALERTS{alertstate="firing"}[24h])))
2. Find all active silences older than 7 days.
curl -s localhost:9093/api/v2/silences | jq -r --arg now "$(date -u +%s)" '.[] | select(.status.state=="active") | select(((.endsAt | sub("\\.[0-9]+";"") | fromdateiso8601) - ($now|tonumber)) > 7*86400) | "\(.id)\t\(.createdBy)\t\(.comment)"'
Scenario analysis
You take over a service: 47 alerts, all severity=critical, no runbooks, and on-call is woken up 3 times every night. Give a 30-day remediation plan.

Week 1: count each alert’s firings over the past 30 days and their handling records, and classify them by “does it need immediate action”; fill in consistent labels (severity/service/team). Week 2: keep only 3–5 symptom alerts as critical (error ratio, latency, availability); downgrade cause-type alerts to warning and notify only during working hours; add inhibition rules and sensible grouping; delete alerts that nobody acts on. Week 3: write a runbook and dashboard link for each critical alert; add meta-monitoring and Watchdog; add promtool unit tests for rules and run them in CI. Week 4: introduce SLOs and burn-rate alerts (Lesson 6), and establish a weekly alert review. Metrics: number of night-time pages, share of alerts acted on, and MTTA.

Verified teaching videos

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
English · common monitoring and alerting mistakes
▶
Four Golden Signals for Monitoring Systems | Site Reliability Engineering (SRE) — Interview Kickstart US
English · golden signals and alert design (interview perspective)
▶
Four Golden Signals: Monitoring the health of your service | Michael McAllister | Conf42 SRE 2022 — Conf42
English · conference talk: reviewing service monitoring with the golden signals

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Scene: a quiet phone screen, next to a smoking Alertmanager server.
Narration: no alerts could mean everything is fine, or that the monitoring system itself has broken.
Shot 2 · 25–55s
Scene: Watchdog emits a heartbeat every minute, and the external service’s timer resets each time; when the heartbeat stops, the timer runs down to zero and the phone rings.
Narration: a dead man’s switch is an alert that always rings, and a service outside the monitoring system calls you when it stops.
Shot 3 · 55–80s
Scene: a radar chart of the six scorecard dimensions, with the weakest dimension flashing.
Narration: use the checklist to review rule quality, routing and notifications, monitoring itself, capacity and process.
Shot 4 · 80–100s
Scene: 47 critical alerts are filtered down to 4 symptom alerts; the rest are downgraded or deleted.
Narration: the fewer alerts that can wake a person up, the better; each one must be actionable and have a runbook.
or score ≥ 70% on the quiz

Command cheat sheet

All commands and configuration essentials from this lesson, arranged by workflow
Printable
Rules: check, test, load
docker compose exec prometheus promtool check rules /etc/prometheus/rules/*.yml
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml
docker compose exec -w /etc/prometheus/tests prometheus promtool test rules myapp-alerts_test.yml
docker compose kill -s SIGHUP prometheus          # or POST /-/reload (requires --web.enable-lifecycle)
curl -s localhost:9090/api/v1/rules | jq '.data.groups[].rules[] | {name, health, lastError}'
curl -s localhost:9090/api/v1/alerts | jq '.data.alerts[] | {a: .labels.alertname, state}'
Alertmanager: amtool
AMX="docker compose exec alertmanager amtool"
AM="$AMX --alertmanager.url=http://localhost:9093"
$AMX check-config /etc/alertmanager/alertmanager.yml
$AMX config routes test --config.file=/etc/alertmanager/alertmanager.yml --tree severity=critical service=myapp
$AM config routes
$AM alert query -s -i -o extended
$AM alert add alertname=Test severity=warning --annotation=summary=test
$AM silence add alertname=X -d 1h -c "reason / ticket number" -a me
$AM silence query ; $AM silence expire ID
curl -s -XPOST localhost:9093/-/reload
Recording rule naming
level:metric:operations
job:myapp_http_requests:rate5m          # for a counter rate, drop _total
job:myapp_http_errors:ratio_rate5m      # ratio: aggregate separately first, then divide
job_le:myapp_http_request_duration_seconds_bucket:rate5m
job:myapp_http_request_duration_seconds:p95_5m
Alerting rule skeleton
- alert: Name
  expr: <recording rule> > threshold and <traffic> > minimum
  for: 2m
  keep_firing_for: 1m
  labels: {severity: warning, service: myapp}
  annotations:
    summary: "…{{ $labels.job }}"
    description: "current {{ $value | humanizePercentage }}"
    runbook_url: "https://…"
    dashboard: "http://…/d/uid"
Routing and timers
ParameterDefaultMemory aid
group_wait30sWait before the first send for a new group
group_interval5mUpdate interval when the group changes
repeat_interval4hResend when unchanged; a multiple of group_interval
continuefalseContinue matching sibling routes after a match
resolve_timeout5mHow long before an alert without endsAt is treated as resolved
--rules.alert.resend-delay1mPrometheus resend interval
send_resolved default
truefalse
webhook, pagerduty, msteamsv2, msteams, discord, jira, etc.email, slack

all have secret fields *_file Versions: url_file,webhook_url_file,api_url_file,routing_key_file,auth_password_file.

Grafana Alerting
GF="admin:${GF_ADMIN_PASSWORD:-promlab-admin}"
curl -s -u $GF -XPOST localhost:3000/api/admin/provisioning/alerting/reload
curl -s -u $GF 'localhost:3000/api/v1/provisioning/alert-rules/export?format=yaml'
curl -s -u $GF localhost:3000/api/v1/provisioning/policies/export
curl -s -u $GF localhost:3000/api/prometheus/grafana/api/v1/rules | jq '.data.groups[].rules[] | {name, state}'

States: Normal · Pending · Alerting · Recovering · No Data · Error; no-data handling: NoData / Alerting / OK / KeepLast.

Storage and capacity
needed_disk = retention_seconds × samples_per_second × (1–2 bytes)
retention.size ≤ 80–85% of disk; whichever of time and size triggers first takes effect; default 15d
storage:
  tsdb:
    retention: {time: 15d, size: 50GB}        # 3.16: config-file method, reloadable
rate(prometheus_tsdb_head_samples_appended_total[5m])
prometheus_tsdb_head_series · prometheus_tsdb_storage_blocks_bytes
promtool tsdb analyze /prometheus
Required meta-monitoring
vector(1)                                                   # Watchdog
increase(prometheus_rule_evaluation_failures_total[5m]) > 0
prometheus_config_last_reload_successful == 0
rate(prometheus_notifications_errors_total[5m]) > 0
alertmanager_config_last_reload_successful == 0
sum by (integration) (rate(alertmanager_notifications_failed_total[5m])) > 0
Methodologies in one line
  • RED: Rate · Errors · Duration (services)
  • USE: Utilization · Saturation · Errors (resources)
  • Golden signals: Latency · Traffic · Errors · Saturation
  • Alerts: symptoms first; page alerts must be actionable and carry a runbook

Capstone lab + final quiz

Deliver a reviewable set of alerts and dashboards for myapp: rules have unit tests, routing has assertions, notifications are verifiable, and the monitoring itself has a heartbeat
After class ≈ 40 minutesAll runs locally · zero cost
Scenario The platform team requires myapp to pass an “alerting production-readiness review” before it is added to on-call. You need to deliver, in ~/promlab the lab directory: recording rules + alerting rules + unit tests, an Alertmanager routing tree (including inhibition, time intervals and heartbeat), local notifications (webhook + Mailpit), one supplementary Grafana-managed rule, a service dashboard, a retention policy, and a check script that runs in CI ci-check.sh.
Pre-flight checks
cd ~/promlab
ls prometheus/rules prometheus/tests alertmanager alertmanager/templates grafana/provisioning/alerting grafana/dashboards
docker compose ps --format '{{.Service}}' | sort | tr '\n' ' '
prometheus/rules:  meta-alerts.yml  myapp-alerts.yml  myapp-recording.yml
prometheus/tests:  myapp-alerts_test.yml
alertmanager:  alertmanager.yml  templates
alertmanager/templates:  promlab.tmpl
grafana/provisioning/alerting:  lab-alerting.yaml
grafana/dashboards:  myapp-overview.json  myapp-red.json
alertmanager grafana mailpit myapp node-exporter prometheus redis redis-exporter webhook

If any part is missing, go back to the “Lab” page of the corresponding module and fill it in (Module 1: recording rules; 2: alerts and tests; 3: routing; 4: templates and email; 5: Grafana rules; 6: dashboards; 7: retention; 8: meta rules).

Keep unit tests in sync (Module 6 added dashboard annotations to the alerts): in myapp-alerts_test.yml the two MyappHighErrorRate expected exp_annotations entries, add one line to each:
              dashboard: "http://localhost:3000/d/myapp-overview"
Then add a test group for the Redis inhibition scenario (verifying that both cause alerts fire, with inhibition handled by Alertmanager):
  - name: redis-down
    interval: 15s
    input_series:
      - series: 'redis_up{job="redis",instance="redis-exporter:9121"}'
        values: '1 1 0x20'
      - series: 'myapp_redis_up{job="myapp",instance="myapp:5000"}'
        values: '1 1 0x20'
    alert_rule_test:
      - eval_time: 2m
        alertname: RedisDown
        exp_alerts:
          - exp_labels: {severity: critical, service: redis, env: lab, job: redis, instance: "redis-exporter:9121"}
            exp_annotations:
              summary: "Redis unavailable (exporter cannot connect)"
              description: "redis_exporter redis-exporter:9121 reports redis_up=0."
      - eval_time: 2m
        alertname: MyappRedisUnavailable
        exp_alerts:
          - exp_labels: {severity: warning, service: myapp, env: lab, job: myapp, instance: "myapp:5000"}
            exp_annotations:
              summary: "myapp reports Redis unavailable (myapp:5000)"
              description: "myapp_redis_up has been 0 for 1 minute; counting functionality is degraded."
Write the CI check script (use the same image version as at runtime, not depending on a local installation):
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
P="docker run --rm -v $PWD/prometheus:/w -w /w --entrypoint promtool prom/prometheus:v3.16.0"
A="docker run --rm -v $PWD/alertmanager:/etc/alertmanager:ro --entrypoint amtool prom/alertmanager:v0.35.0"

echo "== promtool check rules";  $P check rules $(cd prometheus && ls rules/*.yml)   # glob expands under the host prometheus/ directory
echo "== promtool test rules";   docker run --rm -v "$PWD/prometheus:/w" -w /w/tests --entrypoint promtool prom/prometheus:v3.16.0 test rules myapp-alerts_test.yml
echo "== amtool check-config";   $A check-config /etc/alertmanager/alertmanager.yml
echo "== route assertions"
$A config routes test --config.file=/etc/alertmanager/alertmanager.yml --verify.receivers=audit-log,oncall-critical alertname=X severity=critical service=myapp
$A config routes test --config.file=/etc/alertmanager/alertmanager.yml --verify.receivers=audit-log,team-myapp    alertname=X severity=warning  service=myapp
$A config routes test --config.file=/etc/alertmanager/alertmanager.yml --verify.receivers=heartbeat              alertname=Watchdog
$A config routes test --config.file=/etc/alertmanager/alertmanager.yml --verify.receivers=default-webhook        alertname=X severity=info
echo "== dashboard json";        jq -e '.uid == "myapp-overview" and (.panels | length) >= 8' grafana/dashboards/myapp-overview.json >/dev/null
echo "ALL CHECKS PASSED"
chmod +x ci-check.sh && ./ci-check.sh
== promtool check rules
Checking rules/meta-alerts.yml
  SUCCESS: 7 rules found
Checking rules/myapp-alerts.yml
  SUCCESS: 7 rules found
Checking rules/myapp-recording.yml
  SUCCESS: 6 rules found

== promtool test rules
Unit Testing:  myapp-alerts_test.yml
  SUCCESS

== amtool check-config
Checking '/etc/alertmanager/alertmanager.yml'  SUCCESS
…
== route assertions
audit-log,oncall-critical
audit-log,team-myapp
heartbeat
default-webhook
== dashboard json
ALL CHECKS PASSED

If --verify.receivers does not match, amtool exits with code 1,set -e causing the script to fail. It can be dropped directly into GitHub Actions / Azure Pipelines (Git, GitHub, Azure DevOps courses).

End-to-end drill 1: error alert + inhibition (verifies Modules 2 and 3 at the same time):
docker compose kill -s SIGHUP prometheus
docker compose stop redis
sleep 120
curl -s localhost:9093/api/v2/alerts | jq -r '.[] | "\(.labels.alertname)\t\(.labels.severity)\t\(.status.state)"' | sort
docker compose start redis
MyappRedisUnavailable	warning	suppressed
RedisDown	critical	active
Watchdog	none	active
End-to-end drill 2: notification delivery (Module 4):
AM="docker compose exec alertmanager amtool --alertmanager.url=http://localhost:9093"
$AM alert add alertname=FinalDrill severity=critical service=myapp env=lab --annotation=summary='Capstone drill' --annotation=runbook_url='https://runbooks.example.com/final'
sleep 15
curl -s localhost:8025/api/v1/messages | jq -r '.messages[0].Subject'
docker compose logs --no-log-prefix webhook --since 30s | grep FinalDrill | cut -c1-80
[FIRING:1] FinalDrill (lab)
14:58:03 POST /audit receiver=audit-log status=firing alerts=1 [FinalDrill] …
14:58:03 POST /critical receiver=oncall-critical status=firing alerts=1 [FinalDrill] …
End-to-end drill 3: silence policy (Modules 3 and 8): create a silence with a ticket number lasting 30 minutes, verify it, then end it immediately.
SID=$($AM silence add alertname=FinalDrill service=myapp -d 30m -c "CHG-1234 drill" -a lab-user)
$AM alert query -s alertname=FinalDrill
$AM silence expire "$SID"
Capacity and retention check (Module 7):
curl -s localhost:9090/api/v1/status/runtimeinfo | jq -r '.data.storageRetention'
curl -s localhost:9090/api/v1/query --data-urlencode 'query=sum(rate(prometheus_tsdb_head_samples_appended_total[5m]))' | jq -r '.data.result[0].value[1]'
Clean-up (optional): keep the environment for review before Lesson 3; to fully clean up what this lesson added:
cd ~/promlab
docker compose down                     # stop all services (keep volumes)
sed -i '/^COMPOSE_FILE=/d' .env         # revert to using only Lesson 1’s compose.yaml
docker volume rm promlab_am-data   # delete silences and the notification log (Lesson 1 alertmanager data volume)
docker compose up -d

Rules, templates and provisioning files stay in the directory; Lesson 5 converts them into PrometheusRule / AlertmanagerConfig.

Acceptance checklist

Open-ended self-test (6 questions)

1. Why does this lesson’s error-rate alert add “and job:myapp_http_requests:rate5m > 0.1”?

At low traffic, one or two errors can push the ratio to 50%, producing meaningless alerts; and 0/0 yields NaN. The minimum-traffic condition makes the alert fire only when it is statistically meaningful. A better approach is SLO burn-rate alerting (Lesson 6).

2. From the moment a condition holds until the webhook receives the notification, how long is the shortest and longest time? (With this lesson’s parameters)

Shortest ≈ rule evaluation alignment (0–15s) + for (2m) + Prometheus sending (same round) + group_wait (10s, 5s for a critical route). If it joins an existing group, it must wait until the next group_interval (up to 30s), not group_wait. The scrape interval also adds up to 15s of discovery delay.

3. Why is it said that “silencing an upstream alert does not let downstream symptoms surface”?

An inhibition source only requires the alert to be in firing (active) state; a silenced alert is still firing and merely does not notify, so it can still act as an inhibition source.

4. Why can’t the Watchdog alert rely only on Alertmanager itself to judge?

Watchdog exists to detect failures of Prometheus, Alertmanager, the network and the notification channels themselves; when such failures occur, the monitoring system cannot send any notification. Only an external service independent of the monitoring system can raise an alarm when the “heartbeat stops”.

5. When would you choose Grafana-managed rules rather than Prometheus rules?

When you need to combine several data sources (logs + metrics + SQL), when the team works mainly in the UI, or when you use managed Grafana alerting capabilities. For service alerts on pure Prometheus metrics that need unit tests and GitOps, prefer Prometheus rules.

6. A 100 GB disk, a sample rate of 20,000/s, and 30 days of retention: is this feasible?

20,000 × 1.5 B × 30 × 86,400 ≈ 77.8 GB (about 104 GB at 2 B); the official advice is retention.size ≤ 80–85% (about 80–85 GB), and WAL and compaction also need space. At 1.5 B it is barely feasible but has insufficient headroom; at 2 B it is not feasible. Expand to ≥ 150 GB, reduce the number of series, or shorten retention and introduce remote storage.

Sources and version notes

Verification basis for the technical facts in this lesson (verified 2026-11-15)
TopicVerified conclusionsSources (access date 2026-11-15)
Prometheus versionv3.16.0 (2026-11-04) is the latest stable release; the previous version is v3.15.1 (2026-10-21)prometheus/prometheus releases · CHANGELOG
Alertmanager versionv0.35.0 (2026-11-09): --auto-gomemlimit replaces the feature flag; the new Mantine UI is at /ui/, slack post_updates_to_thread, template functions addDuration; from v0.34.2 (2026-10-29) onward, CORS headers are not sent by default (--web.cors.origin)alertmanager CHANGELOG
Grafana version13.3.1 (2026-11-10) is the latest; 13.2.6 / 13.1.10 / 13.0.13 released patches on the same daygrafana/grafana releases
Other componentsnode_exporter v1.12.1; redis_exporter v1.97.0; Mailpit v1.33.1 (2026-11-07)each project’s GitHub releases
Recording ruleswithin a group, executed in order with the same evaluation time; group fields interval,limit,query_offset,labels; exceeding the limit drops all results; slow groups are skipped and counted in rule_group_iterations_missed_totalRecording rules(v3.16.0 docs source files)
Naming conventionlevel:metric:operations, drop when applying rate _total, ratio uses ratioBest practices: rules
Alerting rulesfor,keep_firing_for (default 0s), templates $labels/$value/$externalLabels,ALERTS series; pending alerts are not sentAlerting rules
Alert sending detailsresolved instances are kept for 15 minutes (resolvedRetention); ValidUntil = ts + 4 × max(resend-delay, interval); --rules.alert.resend-delay 1m,for-outage-tolerance 1h,for-grace-period 10m; humanizePercentage use %.4g%%source code rules/alerting.go,cmd/prometheus/main.go,template/template.go (v3.16.0)
promtool unit testsrule_files,evaluation_interval,fuzzy_compare,input_series extended notation,alert_rule_test,promql_expr_test,start_timestamp; group labels take effect via LoadGroups ; --run,--junitUnit testing for rules · source code cmd/promtool/unittest.go
Alertmanager routing and timersdefaults: group_wait 30s, group_interval 5m, repeat_interval 4h; repeat is rounded up to a multiple of group_interval; group_interval is also the notification timeout; mute/active_time_intervals are not inherited, and the root route cannot use themAlertmanager configuration(v0.35.0 docs source files)
Inhibitionsource_matchers/target_matchers/equal, optional name; a missing label equals an empty value; target_match*/source_match* deprecatedsame as above
Time intervalsif no location is given, UTC is used; times start inclusive, end exclusive; weekday ranges can span weekends (0.35); Alertmanager does not embed tzdata (time.LoadLocation), and the official image is based on busyboxsame as above · source code timeinterval/timeinterval.go,Dockerfile
receiverintegration list; webhook payload version "4" fields; send_resolved defaults: webhook/pagerduty/msteamsv2 true, email/slack false; msteamsv2_configs used for Teams Workflowssame as above
amtoolcheck-config,config routes [test] --tree --verify.receivers,silence add/query/expire,alert query/add,template render, config file ~/.config/amtool/config.ymlalertmanager README
Grafana Alertingstates Normal/Pending/Alerting/Recovering/No Data/Error; keep firing for of 0 skips Recovering; No Data/Error apply only to Grafana-managed rules; provisioning file format and “the policy tree is overwritten as a whole”; POST /api/admin/provisioning/alerting/reload; export /api/v1/provisioning/alert-rules/export (yaml/json/hcl)Alert rule evaluation · File provisioning · Admin API
Storagedefault 15d; size takes units, powers of 2; 1–2 bytes/sample; capacity formula; retention.size ≤ 80–85%; compaction span ≤ min(10% of retention, 31d); NFS/EFS not supported; 3.16 config file storage.tsdb.retention.{time,size,percentage}, command-line flag marked deprecatedStorage · Configuration <tsdb> · source code cmd/prometheus/main.go
TSDB metric namesprometheus_tsdb_head_series,…_head_samples_appended_total,…_storage_blocks_bytes,…_head_chunks_storage_size_bytes,…_wal_storage_size_bytes,…_retention_limit_seconds/bytes/percentage,…_time/size_retentions_totalsource code tsdb/db.go,tsdb/head.go,tsdb/wlog/wlog.go
MethodologyRED (Tom Wilkie), USE (Brendan Gregg), four golden signals (Google SRE Book, Chapter 6)SRE Book · USE Method

Video verification notes

The following videos had their titles and channels verified via the YouTube oEmbed API (2026-11-15): DevOps Hint “Recording Rules in Prometheus with Examples | Best Practices…” (Kk3uDNV0EQw), “Recording Rules in Prometheus | … Tutorial for Beginners” (lVeECk5nxgs), “Alerting Rules in Prometheus | …” (9joXN3ipABg); Prometheus Monitoring with Julius | PromLabs “Understanding Counter Rates and Increases in PromQL…” (7uy_yovtyqw), “Don't Make These 6 Prometheus Monitoring Mistakes…” (NEMsO1qeI1s); DevOps Simplified “Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output)” (Op0cUlooq4k), “Prometheus Alertmanager for Beginners: Routes, Webhooks and Silences (Real Output)” (YhHhZyJCAWE); Tech with Lian “Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences on Alertmanager” (IoCz7NJ-LT0); CNCF “Lightning Talk: New matchers in the Alertmanager config and silences - Atibhi Agrawal, Grafana Labs” (8rgZ_pr5OqU); Oddly Yogi “Prometheus and Grafana : 14 - Alertmanager: Grouping, Routing and Silences” (QUXvTCqznF8), “… : 15 - Storage, Retention and Cardinality” (G-uUyFan_HQ); Arvind Konar “How to Setup Prometheus alertmanager with Pagerduty and Slack” (QKkrsY-sndg); Grafana “Get started with Grafana Alerting: Create and receive your first alert” (YVhKNbQNNss), “…: Group alert notifications” (WZ8gqKIQ5Oc), “…: Route alerts using dynamic labels” (hSejnv1cdYY), “…: Template your alert notifications” (9CSrQGKeZwQ), “Grafana Campfire 🔥- Data Visualization Tips and Best Practices (Grafana Community Call- April 2025)” (0G5dDDZLrVI); Bhoopesh Sharma “Learn Grafana Alerting in 2026 | Alert Manager vs Grafana Alerts - Part 1” (HfI4HOs6Cmg); InfluxData “Tom Wilkie [Kausal] | The Red Method: How To Instrument Your Services | InfluxDays 2018” (9dRSYjBPaZM); IBM Technology “SRE Golden Signals Explained” (-U9E1PhrM3o); Gheware DevOps AI “Grafana Dashboards: RED & USE Methods for Production” (8bVj5NuLhlA); Prometheus Monitoring “PromCon EU 2019: Practical Capacity Planning Using Prometheus” (swnj6KTRg08), “PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable” (zTH7DKAWqHc); Interview Kickstart US “Four Golden Signals for Monitoring Systems | Site Reliability Engineering (SRE)” (OTqikK7bbik); Conf42 “Four Golden Signals: Monitoring the health of your service | Michael McAllister | Conf42 SRE 2022” (rZzGr5Zj1KM). Videos that appeared in search results but for which oEmbed returned no data (for example several videos from the SBCODE channel) are not included. Some third-party videos were recorded on earlier versions; this lesson’s interface and parameters take precedence.

Voice narration notes

The “Voice” page reads the narration script aloud using the browser’s built-in Web Speech API (en-US); English terms are pronounced with en-US, and results depend on the system voice pack. This courseware does not embed MP3; if offline audio is needed, the narration script can be given to a TTS service to generate it.

Known limitations

  • The lab commands were not actually run in the environment that generated this courseware (the generation environment does not allow pulling and running container images); all “expected outputs” are examples inferred from the official docs and the v3.16.0 / v0.35.0 source code,example, timestamps, IDs, values, log wording, amtool tables and --tree rendering formats depend on your environment. The rules, tests and configuration files have been checked item by item against the official syntax, but promtool test rules and amtool check-config have not actually been run; please rely on your own local results.
  • myapp_redis_up indicates “whether the most recent Redis access succeeded” (Lesson 1 refreshes it on requests and scrapes); after Redis is stopped, traffic or a scrape is needed before it becomes 0. The error-rate alert is tested with synthetic data in promtool; you can also trigger it for real using Lesson 1’s /error route (returns 500) (last step of the Module 2 lab).
  • Grafana 13's UI menu locations, the Alert list panel option names, and extra fields in the webhook payload may change between minor versions; for the provisioning file format, follow the official docs. The concepts for Grafana 12.x are the same as in this lesson.
  • Whether the official Alertmanager image includes timezone data has not been verified inside the image; this lesson conservatively assumes it may not (the lab uses UTC).
  • Prometheus has no official fixed value for “bytes per series” in memory; this lesson only gives a measurement method, and the default values in the capacity calculator are illustrative only.
  • For the exact retirement dates of the legacy Microsoft Teams Office 365 Connectors, follow Microsoft’s announcements; this lesson only gives the direction for migration (Workflows + msteamsv2_configs).
  • The timing and routing in the animations are simplified simulations of the real mechanisms (for example, the lifecycle animation uses 15 seconds per cell and ignores scrape delay; the routing simulator implements only the fields used by this lesson’s configuration).