Skip to content
devops/architect
08 prometheus 01 01 prometheus & alerting
0/8 read · lab 0/1
STARTUP TO ENTERPRISE
08 / 14 • METRICS & ALERTING

Prometheus & Alerting

Pull-based time series database. Master PromQL, recording rules, alerting rules, AlertManager, exporters, and production SLO-based monitoring on Kubernetes.

node-exporter kube-prom-stack Federation + SLOs

Lesson objective

What it teaches
Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: SLOs and Advanced Alerting · Securing Prometheus: TLS, Basic Auth and Exposure
Why it matters
A required lesson for DevOps Engineer, SRE, Observability Engineer. Recommended for Container/Kubernetes Engineer, FinOps / Cloud Optimization, MLOps / LLMOps Engineer. See the role paths
What you demonstrate
  • Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
  • Predict 3 results this lesson prints. You mark each one yourself.
  • Optional, real environment: 5 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

Architecture & How It Works 08.1

Prometheus scrapes /metrics endpoints on a fixed interval. Data is stored locally in TSDB. AlertManager receives alerts and handles routing, grouping, inhibition and silencing.

graph TD P[Prometheus] -- scrape --> Node[node-exporter] P -- scrape --> KSM[kube-state-metrics] P -- scrape --> App[Application metrics] P -- alerts --> AM[AlertManager] AM --> Slack AM --> PagerDuty

Core Components 08.2

TypeBehaviorPromQL Example
CounterMonotonically increasingrate(http_requests_total[5m])
GaugeCan go up or downnode_memory_MemAvailable_bytes
HistogramBucketed observationshistogram_quantile(0.95, rate(...))
SummaryPrecomputed quantilesquantile(0.9, ...)

WSL Hands-On Lab 08.3

Full Observability Stack: Prometheus + AlertManager + Grafana + Custom Metrics

stack
$ docker compose up -d
$ curl http://localhost:9090/api/v1/query?query=up
prometheus.yml
global:
  scrape_interval: 15s
scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['node-exporter:9100']
  - job_name: 'app'
    static_configs:
      - targets: ['host.docker.internal:9464']
  • Deploy full Prometheus + Grafana + AlertManager stack via Compose
  • Instrument a simple Express app with prom-client and expose /metrics
  • Write recording rule and alerting rule for high CPU usage
  • Configure AlertManager to route to Slack or email
  • Complete Killercoda Prometheus and Grafana Play labs

Real-World Project 08.4

node-exporter + basic application metrics dashboard

kube-prometheus-stack on EKS + custom ServiceMonitors + PagerDuty

Multi-cluster federation + SLO recording rules + HA AlertManager

Troubleshooting 08.5

Target DOWN

Verify scrape config, network, labels, and relabeling rules.

Alert not firing

Use query inspector in Prometheus UI. Check for clause and vector matching.

High cardinality explosion

Drop unwanted labels early with relabel_configs or metric_relabel_configs.

30-Day Roadmap 08.6

WEEK 1
Metrics & PromQL
  • Four metric types
  • rate/irate/increase
  • by/without/group_left
WEEK 2
Alerting Rules
  • for: clause
  • labels + annotations
  • AlertManager config
WEEK 3
Kubernetes Monitoring
  • ServiceMonitor/PodMonitor
  • kube-state-metrics
  • Recording rules
WEEK 4
SLOs & Advanced
  • Error budget alerts
  • Federation
  • HA AlertManager

Deep Dive: SLOs and Advanced Alerting 08.7

Defining SLOs

Availability = good events / total events. Error budget = 1 - SLO target. Alert when burn rate is too high for the window. Use multi-window, multi-burn-rate alerts.

Recording Rules for Performance

Pre-compute expensive queries (rate over long windows, complex joins). Store results as new time series that are fast to query from Grafana.

SLO ALERTING ARCHITECTURE

Multi-Window Multi-Burn-Rate SLO Alerting & Promtool Unit Tests

Standard threshold alerts fire either too slowly on acute outages or page on transient blips. Production SRE teams use Google's multi-window, multi-burn-rate pattern. According to the Google SRE Workbook (Chapter 5) and Prometheus Alerting Rules Documentation:

  • Service Level Objective (SLO): 99.9% availability over a 30-day window (43,200 minutes). The allowable error budget fraction is 0.001 (0.1%).
  • Critical Page (14.4x Burn Rate): Consumes 2% of the entire 30-day error budget in 1 hour (14.4 × 1h / 720h = 0.02). Alert requires both a 1-hour long window and a 5-minute short window error rate > 0.0144 (1.44%). When the incident is mitigated, the 5-minute short window drops instantly, clearing the alert within 5 minutes rather than waiting an hour.
  • Warning Ticket (6.0x Burn Rate): Consumes 5% of the error budget in 6 hours (6.0 × 6h / 720h = 0.05). Alert requires both a 6-hour long window and a 30-minute short window error rate > 0.006 (0.6%).
  • Low/No-Traffic Floor Guard: A naive division by zero (or 1 failed request during zero-traffic hours) causes false 100% error spikes. We enforce a traffic floor guard: and sum(rate(http_requests_total{job="api-gateway"}[5m])) > 1 (requiring at least 1 req/s before alerting).
slo_rules.yml (Prometheus Alerting Rules v2.55+)
groups:
  - name: slo_recording_rules
    rules:
      # Pre-aggregate request and error rates across all pods for api-gateway
      - record: job:http_requests_total:rate5m
        expr: sum(rate(http_requests_total{job="api-gateway"}[5m]))
      - record: job:http_requests_errors:rate5m
        expr: sum(rate(http_requests_total{job="api-gateway",code=~"5.."}[5m]))
      - record: job:http_requests_total:rate1h
        expr: sum(rate(http_requests_total{job="api-gateway"}[1h]))
      - record: job:http_requests_errors:rate1h
        expr: sum(rate(http_requests_total{job="api-gateway",code=~"5.."}[1h]))
      - record: job:http_requests_total:rate30m
        expr: sum(rate(http_requests_total{job="api-gateway"}[30m]))
      - record: job:http_requests_errors:rate30m
        expr: sum(rate(http_requests_total{job="api-gateway",code=~"5.."}[30m]))
      - record: job:http_requests_total:rate6h
        expr: sum(rate(http_requests_total{job="api-gateway"}[6h]))
      - record: job:http_requests_errors:rate6h
        expr: sum(rate(http_requests_total{job="api-gateway",code=~"5.."}[6h]))

  - name: slo_alerting_rules
    rules:
      # Critical: 14.4x burn rate (2% budget consumed in 1 hour)
      - alert: HttpApiErrorBudgetBurnCritical
        expr: |
          (job:http_requests_errors:rate1h / job:http_requests_total:rate1h > (14.4 * 0.001))
          and
          (job:http_requests_errors:rate5m / job:http_requests_total:rate5m > (14.4 * 0.001))
          and
          (job:http_requests_total:rate5m > 1)
        for: 2m
        labels:
          severity: page
          tier: api
        annotations:
          summary: "High error budget burn rate (14.4x) on api-gateway"
          description: "Current error rate exceeds 1.44% across 1h and 5m windows with sufficient traffic (>1 req/s)."

      # Warning: 6.0x burn rate (5% budget consumed in 6 hours)
      - alert: HttpApiErrorBudgetBurnWarning
        expr: |
          (job:http_requests_errors:rate6h / job:http_requests_total:rate6h > (6.0 * 0.001))
          and
          (job:http_requests_errors:rate30m / job:http_requests_total:rate30m > (6.0 * 0.001))
          and
          (job:http_requests_total:rate30m > 1)
        for: 15m
        labels:
          severity: ticket
          tier: api
        annotations:
          summary: "Moderate error budget burn rate (6x) on api-gateway"
          description: "Current error rate exceeds 0.6% across 6h and 30m windows with sufficient traffic."

Offline Promtool Validation: Promtool simulates metric series deterministically across time intervals to verify that alerts fire during genuine multi-window burns, clear within 5m of recovery, and remain silent during low-traffic trickles.

slo_test.yml (promtool test rules fixture)
# promtool test rules slo_test.yml
rule_files:
  - slo_rules.yml

evaluation_interval: 1m

tests:
  - interval: 1m
    input_series:
      # Simulated 100 req/s normal traffic, 2 req/s 500 errors (2% error rate > 1.44% threshold)
      - series: 'http_requests_total{job="api-gateway",code="200"}'
        values: '0+6000x120'
      - series: 'http_requests_total{job="api-gateway",code="500"}'
        values: '0+120x120'
    alert_rule_test:
      - eval_time: 10m
        alertname: HttpApiErrorBudgetBurnCritical
        exp_alerts:
          - exp_labels:
              severity: page
              tier: api
            exp_annotations:
              summary: "High error budget burn rate (14.4x) on api-gateway"
              description: "Current error rate exceeds 1.44% across 1h and 5m windows with sufficient traffic (>1 req/s)."

  - interval: 1m
    input_series:
      # Low-traffic edge case: 1 total request with code 500 over 5m (0.003 req/s)
      # Should NOT fire because total rate <= 1 req/s traffic floor guard
      - series: 'http_requests_total{job="api-gateway",code="500"}'
        values: '0+1x60'
    alert_rule_test:
      - eval_time: 15m
        alertname: HttpApiErrorBudgetBurnCritical
        exp_alerts: []
SECURITY & COMPLIANCE

Alertmanager TLS, Basic Auth & Secret-File Credential Isolation

By default, Alertmanager exposes its API without authentication. Any pod on the network can silence active alerts, inspect webhook endpoints, or trigger arbitrary notification events. Under Alertmanager HTTPS & TLS Architecture (v0.22.0+, tested with v0.27+), transport security and authentication are enforced via --web.config.file, while secrets are read from isolated filesystem paths.

alertmanager/web.yml (--web.config.file)
# Alertmanager web server TLS and mutual client authentication
tls_server_config:
  cert_file: /etc/alertmanager/tls/server.crt
  key_file: /etc/alertmanager/tls/server.key
  min_version: TLS13
  # Require mutual TLS (mTLS) for Prometheus dispatchers
  client_ca_file: /etc/alertmanager/tls/prom-ca.crt
  client_auth_type: RequireAndVerifyClientCert

basic_auth_users:
  # bcrypt hash generated via: htpasswd -nbBC 10 "" "PromOpAlerts#2026"
  prom-operator: $2y$10$891kC7GjO6z7qXmZbq9lYeJ50Y8t6x9B1gL2oM3pQ4rS5tU6vW7xY

Decoupled Secret-File Directives: Never commit raw API tokens or webhooks to Git. Modern Alertmanager receivers support _file suffixes to mount credentials into an unprivileged pod (UID 65534 nobody, mode 0400).

alertmanager/alertmanager.yml (Receiver Secrets)
global:
  resolve_timeout: 5m

route:
  group_by: ['alertname', 'cluster']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h
  receiver: default-pagerduty
  routes:
    - matchers:
        - severity = "ticket"
      receiver: slack-notifications

receivers:
  - name: default-pagerduty
    pagerduty_configs:
      - routing_key_file: /etc/alertmanager/secrets/pagerduty_routing_key
        send_resolved: true

  - name: slack-notifications
    slack_configs:
      - api_url_file: /etc/alertmanager/secrets/slack_webhook_url
        channel: '#sre-alerts'
        send_resolved: true

  - name: remediation-webhook
    webhook_configs:
      - url: 'https://remediation.internal/hooks'
        http_config:
          bearer_token_file: /etc/alertmanager/secrets/webhook_token
          tls_config:
            ca_file: /etc/alertmanager/tls/internal-ca.crt

Validation & Diagnostics: Validate configuration offline using amtool check-config and dry-run syntax verification:

validate-alertmanager.sh (Offline Syntax Checks)
#!/usr/bin/env bash
set -euo pipefail

# 1. Validate Alertmanager configuration syntax and receiver files
amtool check-config /etc/alertmanager/alertmanager.yml

# 2. Verify TLS web configuration and certificates offline
openssl verify -CAfile /etc/alertmanager/tls/internal-ca.crt /etc/alertmanager/tls/server.crt

# 3. Simulated mTLS health probe syntax using client certificate
# curl --cacert /etc/alertmanager/tls/internal-ca.crt \
#      --cert /etc/prometheus/tls/client.crt \
#      --key /etc/prometheus/tls/client.key \
#      -u prom-operator:"$(cat /etc/alertmanager/secrets/prom-op.pass)" \
#      https://127.0.0.1:9093/-/healthy
FEDERATION & HIGH AVAILABILITY

Hierarchical Federation, External Labels & HA Alertmanager Gossip Mesh

Enterprise observability separates local cluster monitoring from a global multi-cluster pane. As documented in Prometheus Federation and Alertmanager High Availability Clustering:

  • Hierarchical Federation: Global Prometheus scrapes /federate from regional leaf instances. Crucially, honor_labels: true is required so local metric labels (such as original job and instance) are not overwritten with the global scraper's job labels.
  • Match Selectors & Cardinality Explosion: Global Prometheus must only pull pre-aggregated recording rules (e.g., {__name__=~"^job:.*"}). Pulling raw counters (e.g., match[]={__name__=~".+"}) is a known production disaster that exhausts global TSDB memory and causes federate scrape timeouts.
  • HA Alertmanager Gossip Mesh (Memberlist): Prometheus instances broadcast all alerts simultaneously to all Alertmanager peers in the cluster (e.g. am-1:9093, am-2:9093, am-3:9093). During group_wait, peers communicate over port 9094 (TCP/UDP) via gossip to deduplicate notifications and sync silence state.
  • Failure Mode (Split-Brain): If gossip port 9094 is partitioned, peers cannot verify notification status. Alertmanager is intentionally designed to prioritize availability over deduplication: both sides will dispatch the alert, ensuring critical pages are never lost during a network split.
prometheus-federation.yml (Central Federation Scraper)
# Global Prometheus configuration pulling from regional leaf clusters
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  external_labels:
    tier: global
    monitor: enterprise-core

scrape_configs:
  - job_name: 'federate-us-east-1'
    scrape_interval: 30s
    honor_labels: true
    metrics_path: '/federate'
    params:
      match[]:
        - '{__name__=~"^job:.*"}'
        - '{__name__=~"^cluster:.*"}'
        - '{alertname!=""}'
    static_configs:
      - targets:
          - 'prometheus-leaf.us-east-1.internal:9090'
        labels:
          region: us-east-1
          cluster: prod-k8s-01

alerting:
  alertmanagers:
    # All Alertmanager peers specified simultaneously for redundant parallel dispatch
    - scheme: https
      basic_auth:
        username: prom-operator
        password_file: /etc/prometheus/secrets/prom-op.pass
      tls_config:
        ca_file: /etc/prometheus/tls/internal-ca.crt
        cert_file: /etc/prometheus/tls/client.crt
        key_file: /etc/prometheus/tls/client.key
      static_configs:
        - targets:
            - 'am-01.monitoring.internal:9093'
            - 'am-02.monitoring.internal:9093'
            - 'am-03.monitoring.internal:9093'
alertmanager-cluster-args.txt (Memberlist Gossip CLI Flags)
# Alertmanager HA daemon invocation flags (simulated production setup)
/bin/alertmanager \
  --config.file=/etc/alertmanager/alertmanager.yml \
  --web.config.file=/etc/alertmanager/web.yml \
  --cluster.listen-address=0.0.0.0:9094 \
  --cluster.peer=am-01.monitoring.internal:9094 \
  --cluster.peer=am-02.monitoring.internal:9094 \
  --cluster.peer=am-03.monitoring.internal:9094 \
  --cluster.gossip-interval=200ms \
  --cluster.pushpull-interval=1m \
  --cluster.peer-timeout=15s

# Offline Verification Command:
# amtool cluster show --alertmanager.url=https://am-01.monitoring.internal:9093

Securing Prometheus: TLS, Basic Auth and Exposure 08.8

Prometheus has no authentication by default: anyone who reaches :9090 can query every metric, and its labels often carry hostnames, customer IDs and internal URLs. Since v2.24, --web.config.file adds TLS and basic auth to the UI and API. Publish the port on an internal address only, and still treat it as reachable.

Recorded from a real run of scripts/recordings/prometheus.sh; every output below is pasted from scripts/recordings/prometheus.out. Cover the output, predict it, then compare.

Environment: prom/prometheus:v2.55.1 containers on Docker 26.1.5. prom-open has no web config; prom-secure uses the file below and a self-signed certificate for localhost. Both publish on 127.0.0.1 only. The password is a demo value.

web.yml
# --web.config.file: TLS on the HTTP API and UI, and basic auth for every request.
tls_server_config:
  cert_file: /etc/prometheus/tls/server.crt
  key_file: /etc/prometheus/tls/server.key
basic_auth_users:
  # bcrypt hash of the demo password in admin.pass (htpasswd -nbBC 10 "" demo-only-pass)
  admin: $2y$10$1LCubrH4k1iYCvYfjEkB/e5sNg3cwF5A1qUFyBc6w/lUMm7.LUjzW
recorded run
# The default instance, no credentials
$ curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost:9090/api/v1/query?query=up'
200

# The secured instance, without trusting its certificate
$ curl -s -o /dev/null -w '%{http_code}\n' https://localhost:9091/-/healthy; echo "exit=$?"
000
exit=60

# Certificate trusted, no credentials
$ curl -s -o /dev/null -w '%{http_code}\n' --cacert tls/server.crt 'https://localhost:9091/api/v1/query?query=up'
401

# With credentials: is the server scraping itself?
$ curl -s --cacert tls/server.crt -u admin:"$(cat admin.pass)" 'https://localhost:9091/api/v1/query?query=up' | jq -r '.data.result[0].value[1]'
0

# Why the self-scrape fails
$ curl -s --cacert tls/server.crt -u admin:"$(cat admin.pass)" https://localhost:9091/api/v1/targets | jq -r '.data.activeTargets[0].lastError'
server returned HTTP status 400 Bad Request

Prometheus scrapes itself, and its scrape config still says plain HTTP with no credentials. Once the server requires TLS and auth, every scraper must present them too, including Prometheus itself and any federation or Grafana datasource. Keep the password in a file the process reads, not in the config:

prometheus.yml
global:
  scrape_interval: 5s
scrape_configs:
  - job_name: prometheus
    scheme: https
    tls_config:
      ca_file: /etc/prometheus/tls/server.crt
    basic_auth:
      username: admin
      password_file: /etc/prometheus/admin.pass
    static_configs:
      - targets: ["localhost:9090"]
recorded run
# After restarting with the scrape config above
$ curl -s --cacert tls/server.crt -u admin:"$(cat admin.pass)" 'https://localhost:9091/api/v1/query?query=up' | jq -r '.data.result[0].value[1]'
1

# Where the port is published
$ docker port prom-secure
9090/tcp -> 127.0.0.1:9091

Basic auth over TLS is a minimum, not access control: every user sees every series. For per-team access, put Prometheus behind an authenticating proxy or query it through Grafana with its own roles.

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost:9090/api/v1/query?query=up'
Show the lesson's result

The lesson shows:

200

What result does the lesson show for this command?

$ curl -s -o /dev/null -w '%{http_code}\n' https://localhost:9091/-/healthy; echo "exit=$?"
Show the lesson's result

The lesson shows:

000
exit=60

What result does the lesson show for this command?

$ curl -s -o /dev/null -w '%{http_code}\n' --cacert tls/server.crt 'https://localhost:9091/api/v1/query?query=up'
Show the lesson's result

The lesson shows:

401

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

An error-rate alert that never fires

Output recorded from a real run on promtool 3.5.0 from the prom/prometheus:v3.5.0 Docker image, run from Git Bash on Windows; the unit tests use a 1m scrape interval, as the scenario does. No Prometheus server or cluster involved. Nothing runs on your machine.

Builds on Troubleshooting.

Checkout returned 30% errors for 20 minutes last night and nobody was paged. Prometheus scrapes checkout every 1m. The CheckoutHighErrorRate rule loads without errors and the Alerts page lists it as inactive, never pending. You copy the rule and the incident's request counts into a promtool unit test to reproduce it.

  1. Step 1 of 3: The unit test reproduces the miss: at 10 minutes into a 30% error rate, no alert. What do you check first?

Design decision

Static threshold or burn-rate alerts for a 99.9% SLO?

Builds on Troubleshooting.

Checkout has a 99.9% availability SLO over 30 days, so the error budget is 0.1% of requests. Today it pages on error rate > 5% for 5m. Last month a 1% error rate ran for two days and used most of the budget without paging, while short 6% spikes paged on-call at night and cleared by themselves.

Constraints

  • A page must mean the budget is at risk and a human must act now
  • A slow, steady burn must still be caught before the budget is gone
  • On-call is one engineer per week; fewer than two night pages a week
  • Rules must be testable with promtool in CI
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Run the first command shown in the section “WSL Hands-On Lab”
Run the first command shown in the section “WSL Hands-On Lab”

Ready. Type the command for the current goal.

Check yourself

In a Prometheus monitoring architecture, which component is responsible for alert routing, grouping, inhibition, and silencing?

Explanation

In 'Architecture & How It Works', AlertManager receives alerts and handles routing, grouping, inhibition and silencing.

Which checklist does the lesson give specifically for a scrape target reported as DOWN?

Explanation

In 'Troubleshooting', diagnosing a Target DOWN status requires verifying scrape config, network, labels, and relabeling rules.

To prevent a high cardinality explosion from exhausting Prometheus resources, how does the lesson recommend dropping unwanted labels?

Explanation

In 'Troubleshooting', for a 'High cardinality explosion', the lesson directs you to drop unwanted labels early with relabel_configs or metric_relabel_configs.

Why are Prometheus recording rules used for SLO and dashboard performance?

Explanation

In 'Deep Dive: SLOs and Advanced Alerting', recording rules pre-compute expensive queries (rate over long windows, complex joins) and store results as new time series that are fast to query from Grafana.

How does Prometheus collect metric data from monitored targets?

It scrapes /metrics endpoints on a fixed interval using HTTP pull.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 3 sections Not covered Not covered Not covered
Operate Not covered Missing · 2 sections Not covered Not covered
Troubleshoot Not covered Not covered Missing · 1 section Not covered
Automate Not covered Not covered Not covered Not covered
Secure Not covered Not covered Not covered Not covered
Observe Not covered Missing · 2 sections Missing · 1 section Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Not covered Not covered

How this lesson fits each role