Prometheus & Alerting
Pull-based time series database. Master PromQL, recording rules, alerting rules, AlertManager, exporters, and production SLO-based monitoring on Kubernetes.
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.
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.
Core Components 08.2
| Type | Behavior | PromQL Example |
|---|---|---|
| Counter | Monotonically increasing | rate(http_requests_total[5m]) |
| Gauge | Can go up or down | node_memory_MemAvailable_bytes |
| Histogram | Bucketed observations | histogram_quantile(0.95, rate(...)) |
| Summary | Precomputed quantiles | quantile(0.9, ...) |
WSL Hands-On Lab 08.3
Full Observability Stack: Prometheus + AlertManager + Grafana + Custom Metrics
$ docker compose up -d $ curl http://localhost:9090/api/v1/query?query=up
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
- Four metric types
- rate/irate/increase
- by/without/group_left
- for: clause
- labels + annotations
- AlertManager config
- ServiceMonitor/PodMonitor
- kube-state-metrics
- Recording rules
- 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.
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).
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.
# 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: []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 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).
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:
#!/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/-/healthyHierarchical 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
/federatefrom regional leaf instances. Crucially,honor_labels: trueis required so local metric labels (such as originaljobandinstance) 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). Duringgroup_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.
# 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 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:9093Securing 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.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# 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:
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"]# 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.