/targets page; on the right, the terminal curl … | jq .lastError. Introduce the seven-step diagram.up and scrape_* automatic metrics,rate() the range window and extrapolation, vector matching, alert pending/firing with Alertmanager grouping/inhibition/retries, and the TSDB head block, WAL, compaction and locking.~/promlab Docker Compose environment from lessons 1–2 and the kind cluster from lessons 5–7 lab + kps on reproduce, diagnose, fix, clean up 16 typical faults; for cloud platform issues (AKS managed Prometheus, AMP/AMG), give the diagnostic commands and expected output.| # | Time | Module | Core content | Animations · interactive | Lab |
|---|---|---|---|---|---|
| 0 | Pre-course | Usage guide and fault lab environment | Reuse ~/promlab (Compose) and kind lab + kps; create ~/promlab/lab8 the fault overlay files | Environment self-check | Start the fakeexp / cardgen two fault containers |
| 1 | 00–08 | A · Collection, scraping and exporters | Issues 1–12: connection refused, scrape timeout, 404, 401/403, x509, Content-Type (Prometheus 3), sample/label/body limits, kind control-plane target down, ServiceMonitor not working, SD RBAC, gunicorn multi-process, duplicate samples | Scrape loop fault simulator | Compose: timeout · Content-Type · sample_limit; kind: ServiceMonitor labels |
| 2 | 08–16 | A · PromQL, rules and alerts | Issues 13–25: many-to-many, same labelset, rate window too short, ranges only allowed, le label normalization, histogram_quantile NaN, too many samples, rule loading failure, pending but never firing, alert silenced when a metric disappears, Prometheus cannot send alerts, notification failure, alert storms and duplicate notifications | "Alert not received" troubleshooting tree | matching errors · le="5.0" · pending→firing · amtool |
| 3 | 16–24 | A · Grafana, managed cloud services | Issues 26–38: data source localhost, importing ${DS_PROMETHEUS}, panel No data, provisioned dashboards cannot be saved, origin not allowed, SQLite database is locked, DatasourceNoData, ama-metrics ConfigMap, azmonitoring CRD, Managed Grafana 403, minimal scrape config, AMP 403/SigV4, managed quota 429 | "Panel no data / error" troubleshooting tree | data source · import · provisioning · Azure diagnostic commands |
| 4 | 24–30 | A · Storage, cardinality, performance and architecture | Issues 39–50: cardinality explosion, OOM and WAL replay, disk full, lock DB directory, block corruption, 11,000 points, slow queries and timeouts, remote write backlog, HA duplicate data, Mimir tenant limits, federation exported_ labels, Prometheus 3 upgrade pitfalls | Cardinality and memory estimator | cardgen cardinality explosion · 11,000 points · directory lock · remote write backlog |
| 5 | 30–37 | B · Core concepts and architecture | Interview 1–13 | Mock interview | 2 scenario questions |
| 6 | 37–44 | B · PromQL and alert design | Interview 14–25 | Mock interview | 2 scenario questions |
| 7 | 44–52 | B · Kubernetes and cloud monitoring | Interview 26–38 | Mock interview | 3 scenario questions |
| 8 | 52–60 | B · Scale, SLO and scenario design | Interview 39–50 | Mock interview | 3 scenario questions |
| — | Post-course | Cheat sheet · Comprehensive drill | 50 "error → first command → fix" entries; 50 recall cards; 8 mixed faults; full mock interview | Full mock interview | Final quiz, 12 questions |
| Topic | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 |
|---|---|---|---|---|---|---|---|---|
| scrape loop / service discovery / relabel | ● | — | ● | — | ● | — | ● | — |
| exporter / application instrumentation (myapp) | ● | — | — | ● | ● | — | ● | — |
| PromQL: rate / matching / histogram | — | ● | ● | ● | — | ● | — | ● |
| rules / Alertmanager / notifications | — | ● | ● | — | — | ● | — | ● |
| Grafana data sources / dashboards / Alerting | — | — | ● | ● | ● | — | ● | — |
| Operator / kps / ServiceMonitor | ● | — | ● | — | — | — | ● | — |
| Azure managed Prometheus / Managed Grafana | — | — | ● | — | — | — | ● | ● |
| AMP / AMG / SigV4 | — | — | ● | ● | — | — | ● | ● |
| TSDB / cardinality / capacity / query performance | ● | ● | — | ● | ● | — | — | ● |
| HA / remote write / Thanos / Mimir / SLO | — | ● | — | ● | ● | ● | ● | ● |
deadline,Content-Type,many-to-many,DS_PROMETHEUS or 429) into the filter box.Symptom → error message → root cause (mechanism level) → diagnostic command → example expected output → fix → prevention and best practices → see Lesson N. Error strings for Prometheus and Alertmanager have been checked against the Prometheus v3.16.0 and Alertmanager v0.35.0 source code; Grafana strings checked against the Grafana v13.3.1 source code; cloud service errors come from Microsoft Learn / AWS official troubleshooting docs. Where the wording cannot be verified word-for-word against source code or official docs, it is marked "exact wording may differ, check actual output".
Question → 30-second answer → in-depth answer (principles, code) → common follow-ups → bonus points → common wrong answers. Difficulty:BeginnerIntermediateAdvanced.
| Lesson | Most-referenced content in this lesson |
|---|---|
| Lesson 1 core fundamentals | pull model, metric types, scrape config and exporters, myapp instrumentation, rate and aggregation, histogram_quantile, Grafana data sources and variables |
| Lesson 2 alerting and production readiness | recording rule naming, alerting rule for/labels, Alertmanager routing/grouping/inhibition/silences, notification channels, Grafana Alerting, storage and retention |
| Lesson 3 Azure · Lesson 4 AWS | ama-metrics and ConfigMap, azmonitoring CRD, Managed Grafana roles; AMP workspaces, managed collector/ADOT, SigV4, AMG and IAM Identity Center |
| Lesson 5 Operator and monitoring as code | kps, ServiceMonitor/PodMonitor/PrometheusRule selectors, provisioning, Terraform/Grafonnet, promtool test rules, blackbox |
| Lesson 6 monitoring architecture in practice | HA replicas and the Alertmanager cluster, Thanos/Mimir, multi-cluster multi-tenancy, burn rate, OpenTelemetry |
| Lesson 7 deep troubleshooting | scrape failure investigation, cardinality, slow queries, head/WAL/compaction, alerts not firing or alert storms, Grafana troubleshooting |
oci://ghcr.io/grafana-community/helm-charts 14.4.1, default Grafana 13.3.1) are the reference versions. Grafana 13 (latest v13.3.1, 2026-11-10; Grafana error strings were checked against this version's source code; menu paths may vary, check the actual UI). Long-term storage: Thanos v0.42.5, Grafana Mimir 3.2.5; AWS ADOT Collector v0.51.0. Prometheus 3 changes relevant to this lesson, compared with 2.x: strict Content-Type checking on scrape (#6),le/quantile label values normalized to floats (#17), range selectors left-open and right-closed (#15), regex . matching newlines,holt_winters renamed, no longer supports the Alertmanager v1 API, remote write no longer uses HTTP/2 by default (#50); in 3.16 --storage.tsdb.retention.* command-line flags are marked DEPRECATED, and writing them to the config file is recommended storage.tsdb.retention (#41).~/promlab that the 7 Compose services are healthy and /-/reload are available, and know which file each fault lab changes and how to restore it.fakeexp (static metrics without the correct Content-Type) and cardgen (to generate high cardinality).lab has the kps (kube-prometheus-stack) available, for Operator-related issues.| Item | Requirement | From |
|---|---|---|
| Docker Engine + Compose v2 | docker compose version Healthy | Docker lesson |
~/promlab | services prometheus (9090),alertmanager (9093),grafana (3000),node-exporter (9100),myapp (5000),redis,redis-exporter (9121) | Lesson 1 setup,Lesson 2 extension |
| myapp metrics | myapp_http_requests_total{method,route,status},myapp_http_request_duration_seconds (buckets 0.005…5),myapp_redis_up | Lesson 1 Module 3 |
kind cluster lab | kps installed on monitoring, with myapp in myapp namespace | Lesson 5 |
| Tools | curl,jq,promtool (bundled in the Prometheus image),amtool (bundled in the Alertmanager image),kubectl,helm | — |
| cloud (optional) | Lesson 3's rg-prom-lab/aks-prom-lab/amw-prom-lab/amg-prom-lab; the EKS from Lesson 4 prom-lab + AMP/AMG (ca-central-1) | Lessons 3–4 |
cd ~/promlab
docker compose ps --format 'table {{.Service}}\t{{.State}}\t{{.Ports}}'
curl -s localhost:9090/-/ready; echo
curl -s 'localhost:9090/api/v1/query?query=up' | jq -r '.data.result[] | "\(.metric.job)\t\(.metric.instance)\t\(.value[1])"'
curl -s -X POST localhost:9090/-/reload && echo "reload OK"
docker compose exec prometheus promtool --version | head -1
SERVICE STATE PORTS alertmanager running 0.0.0.0:9093->9093/tcp grafana running 0.0.0.0:3000->3000/tcp myapp running 0.0.0.0:5000->5000/tcp node-exporter running 0.0.0.0:9100->9100/tcp prometheus running 0.0.0.0:9090->9090/tcp redis running 6379/tcp redis-exporter running 0.0.0.0:9121->9121/tcp Prometheus Server is Ready. prometheus localhost:9090 1 node node-exporter:9100 1 myapp myapp:5000 1 redis redis-exporter:9121 1 reload OK promtool, version 3.16.0 (branch: HEAD, revision: …)
/-/reload Prometheus needs to be started with --web.enable-lifecycle (already added in the Lesson 1 compose). If it returns Lifecycle API is not enabled., then after each config change use docker compose restart prometheus instead.All faults are injected through an extra Compose file and separate scrape/rule fragments injection; the original files only receive small, reversible changes. Back them up before you start:
mkdir -p ~/promlab/lab8 && cd ~/promlab
cp prometheus/prometheus.yml lab8/prometheus.yml.orig
cp alertmanager/alertmanager.yml lab8/alertmanager.yml.orig
# A "non-compliant" exporter: serves static files with python http.server; its Content-Type is not one Prometheus recognizes
cat > lab8/metrics <<'EOF'
# HELP lab8_demo_value A demo gauge.
# TYPE lab8_demo_value gauge
lab8_demo_value 42
EOF
# A high-cardinality generator: every request carries a random user_id label (a deliberately wrong instrumentation)
cat > lab8/cardgen.py <<'EOF'
import random, time
from prometheus_client import Counter, start_http_server
c = Counter("lab8_login_total", "logins", ["user_id"])
start_http_server(8000)
while True:
for _ in range(200):
c.labels(user_id=str(random.randint(1, 10_000_000))).inc()
time.sleep(1)
EOF
cat > lab8/compose.lab8.yml <<'EOF'
services:
fakeexp:
image: python:3.12-slim
command: ["python", "-m", "http.server", "8000", "--directory", "/srv"]
volumes: ["./lab8/metrics:/srv/metrics:ro"]
cardgen:
image: python:3.12-slim
command: ["sh", "-c", "pip install -q prometheus_client && python /app/cardgen.py"]
volumes: ["./lab8/cardgen.py:/app/cardgen.py:ro"]
profiles: ["card"] # only enabled explicitly in Module 4
EOF
docker compose -f compose.yaml -f lab8/compose.lab8.yml up -d fakeexp
docker compose -f compose.yaml -f lab8/compose.lab8.yml ps fakeexp
If your main Compose file is named docker-compose.yml, replace the above compose.yaml with the actual file name. fakeexp and cardgen join the same default network, so Prometheus reaches them by service name.
# After any experiment: restore the config → validate → hot reload cd ~/promlab cp lab8/prometheus.yml.orig prometheus/prometheus.yml cp lab8/alertmanager.yml.orig alertmanager/alertmanager.yml docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml curl -s -X POST localhost:9090/-/reload; curl -s -X POST localhost:9093/-/reload # When everything is finished: docker compose -f compose.yaml -f lab8/compose.lab8.yml --profile card rm -sf fakeexp cardgen
kind get clusters | grep -x lab || kind create cluster --name lab helm repo add prometheus-community https://prometheus-community.github.io/helm-charts && helm repo update helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --version 93.3.0 --wait kubectl -n monitoring get prometheus,alertmanager,servicemonitor | head -20 kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9091:9090 &
NAME VERSION DESIRED READY RECONCILED AVAILABLE AGE prometheus.monitoring.coreos.com/kps-kube-prometheus-stack-prometheus v3.16.0 1 1 True True 3m NAME VERSION REPLICAS READY RECONCILED AVAILABLE AGE alertmanager.monitoring.coreos.com/kps-kube-prometheus-stack-alertmanager v0.35.0 1 1 True True 3m NAME AGE servicemonitor.monitoring.coreos.com/kps-kube-prometheus-stack-apiserver 3m …
The object names generated by kps depend on the release name and fullnameOverride; use kubectl -n monitoring get svc to find the actual Prometheus Service name. Port forwarding uses 9091 so it does not clash with the 9090 of the local Compose setup.
cardgen This makes the local Prometheus memory grow by hundreds of MB within a few minutes; stop and clean up immediately afterwards (module 4).relabel_configs (may drop) → HTTP GET (timeout = scrape_timeout) → check status code and Content-Type → parse → metric_relabel_configs → check sample_limit/label_limit → append to the head and WAL → write up and scrape_*./api/v1/targets of lastError, you can map it directly to one of the steps above and state the fix.Filter by keywords in the error (for example refused,deadline,Content-Type,x509,limit,forbidden) to filter; click a row to jump to the matching entry under "Issue details".
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.health!="up") | "\(.labels.job)\t\(.scrapeUrl)\t\(.lastError)"' —— 9 of the 12 issues have their error message right in lastError .Get "http://myapp:5000/metrics": dial tcp 172.18.0.6:5000: connect: connection refused
Symptom: The myapp container is running, and visiting localhost:5000/metrics also works in the browser, but the Prometheus target stays DOWN,up{job="myapp"} == 0.
Root cause: The TCP connection is refused directly by the target host (RST): no process is listening on that port of that IP. There are three common cases: ① the application only listens on 127.0.0.1 (for example gunicorn -b 127.0.0.1:5000), so the host port mapping works but another container cannot reach it; ② the port is wrong (container port vs host-mapped port; inside the Compose network use the container port); ③ the process has just restarted and is not listening yet. connection refused and no such host (DNS, wrong service name),i/o timeout (network policy / firewall dropping packets) are three different network-layer failures.
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.job=="myapp") | .lastError' # Access from inside the Prometheus container; the path is exactly what Prometheus sees docker compose exec prometheus wget -qO- -T 3 http://myapp:5000/metrics | head -3 docker compose exec myapp sh -c 'cat /proc/net/tcp | head -5' # or ss -lntp (if the image has it) docker compose logs myapp | grep -i "listening"
wget: can't connect to remote host (172.18.0.6): Connection refused [2026-11-15 09:12:01 +0000] [1] [INFO] Listening at: http://127.0.0.1:5000 (1)
# Startup command of myapp in compose.yaml: listen on all interfaces
command: ["gunicorn", "-w", "2", "-b", "0.0.0.0:5000", "app:app"]
# prometheus.yml: inside the Compose network, use "service name:container port"
- job_name: myapp
static_configs:
- targets: ["myapp:5000"]
0.0.0.0; health checks and /metrics use the same port, or document it clearly.up == 0 alert for every job (for 5m), and use absent(up{job="myapp"}) (#22) for "the whole job disappeared".targetPort must be the port the container actually listens on; a NetworkPolicy that drops packets shows up as i/o timeout rather than refused.See Lesson 1 Module 3, scrape config, exporters and application instrumentation · Lesson 7 Module 2, scrape failures.
Get "http://myapp:5000/metrics": context deadline exceeded # Sometimes written as: … context deadline exceeded (Client.Timeout exceeded while awaiting headers) — the wording varies slightly with the Go version
Symptom: the target flaps between good and bad (up jumps between 0 and 1),scrape_duration_seconds close to scrape_timeout (default 10s). Common when an exporter queries a database or calls an API on every scrape (for example a custom exporter, slow queries in mysqld_exporter, or a cloud API exporter), or when the /metrics output is tens of MB.
Root cause: Each scrape's HTTP request carries a deadline = scrape_timeout; if it is exceeded the request is cancelled, and the samples of this scrape are all discarded,up=0. scrape_timeout Must not be greater than scrape_interval (config validation reports scrape timeout greater than scrape interval for scrape config with job name "…"; if set via relabel, __scrape_timeout__ it reports scrape timeout cannot be greater than scrape interval). Prometheus includes it in the request header X-Prometheus-Scrape-Timeout-Seconds how much time remains, and a good exporter adapts to it.
scrape_duration_seconds{job="myapp"}
max_over_time(scrape_duration_seconds{job="myapp"}[1h])
scrape_samples_scraped{job="myapp"} # is the output huge?
docker compose exec prometheus sh -c 'time wget -qO- http://myapp:5000/metrics | wc -c'
8734211 ← 8 MB of /metrics real 0m 11.42s
/metrics size (drop high-cardinality labels, see #39).scrape_interval: 60s + scrape_timeout: 50s, rather than raising the limit globally.Accept-Encoding: gzip, so confirm the exporter supports it. - job_name: slow-exporter
scrape_interval: 60s
scrape_timeout: 50s
static_configs: [{targets: ["slow-exporter:9187"]}]
scrape_duration_seconds / on(job,instance) group_left() (scrape_timeout_seconds) > 0.8 (scrape_timeout_seconds must be enabled in the config extra_scrape_metrics: true— in 3.16 the old --enable-feature=extra-scrape-metrics is being phased out — or replace it with a known constant).prometheus_client custom Collector + cache.See Lesson 7 Module 2 scrape failures: targets down, timeouts and service discovery.
server returned HTTP status 404 Not Found
Symptom: A newly added Spring Boot / .NET / gateway target stays DOWN; opening http://host:port/ in a browser shows a normal page.
Root cause: Prometheus scrapes by default metrics_path: /metrics. The Spring Boot Actuator path is /actuator/prometheus, and many applications expose metrics at /admin/metrics,/stats/prometheus (Envoy), etc.; the common Kubernetes prometheus.io/path annotation is not built-in Prometheus functionality, and it takes effect only when you write it into the relabel rules as __metrics_path__ to take effect. Another case is an older myapp image (myapp:1.0 lacks /metrics).
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.lastError|test("404")) | .scrapeUrl'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5000/metrics
docker compose images myapp
- job_name: spring
metrics_path: /actuator/prometheus
static_configs: [{targets: ["orders:8080"]}]
# Kubernetes annotation convention (self-written relabel; kps does not provide it by default)
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
regex: (.+)
target_label: __metrics_path__
endpoints[].path in ServiceMonitor, instead of relying on the annotation convention./metrics , and the myapp:1.1 in CI for curl -f /metrics smoke tests.See Lesson 1 Module 3.
server returned HTTP status 401 Unauthorized server returned HTTP status 403 Forbidden
Symptom: Self-hosted Prometheus scrapes of kubelet/cAdvisor (:10250/metrics/cadvisor), kube-apiserver and protected application endpoints show DOWN; or everything suddenly goes DOWN after a token rotation.
Root cause: 401 = no credentials, or invalid credentials (expired token, wrong password); 403 = identity recognized but no permission. The kubelet and apiserver authenticate with the ServiceAccount Bearer token and check RBAC via SubjectAccessReview: scraping the kubelet requires nodes/metrics (and cAdvisor's nodes/proxy or nodes/metrics, depending on the kubelet version) with the get permission; scraping the apiserver requires a non-resource URL /metrics with the get. If you hard-code the token into the config file, it breaks on rotation (bound tokens rotate roughly every hour; the mounted file is updated, but a copied string is not).
kubectl auth can-i get nodes/metrics --as=system:serviceaccount:monitoring:prometheus kubectl auth can-i get /metrics --as=system:serviceaccount:monitoring:prometheus curl -sk -H "Authorization: Bearer $(kubectl -n monitoring create token prometheus)" https://NODE_IP:10250/metrics | head -2
no yes
# Use a file instead of a hard-coded token string; Prometheus re-reads the file on every request authorization: credentials_file: /var/run/secrets/kubernetes.io/serviceaccount/token # The ClusterRole should include at least rules: - apiGroups: [""] resources: ["nodes/metrics", "nodes/proxy"] # nodes/proxy is a broad permission; grant it as needed verbs: ["get"] - nonResourceURLs: ["/metrics", "/metrics/cadvisor"] verbs: ["get"]
basic_auth.password_file and oauth2 config blocks, with credentials mounted from a Secret.See Lesson 5 Module 1 kube-prometheus-stack and the Prometheus Operator.
Get "https://172.18.0.3:10250/metrics/cadvisor": tls: failed to verify certificate: x509: certificate signed by unknown authority Get "https://10.0.1.15:8443/metrics": tls: failed to verify certificate: x509: cannot validate certificate for 10.0.1.15 because it doesn't contain any IP SANs
Symptom: All HTTPS targets DOWN. The kubelet in kind/kubeadm clusters uses a self-signed serving certificate by default; application certificates issued by an internal enterprise CA list only DNS names, while service discovery returns Pod IPs.
Root cause: Prometheus validates the certificate chain and the hostname by default. First: the certificate's issuer is not in the ca_file/ system trust store; second: the scrape address is an IP, but the certificate SAN does not contain that IP (only DNS names).
echo | openssl s_client -connect 10.0.1.15:8443 2>/dev/null | openssl x509 -noout -issuer -ext subjectAltName
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.version}{"\n"}'
issuer=CN = corp-internal-ca
X509v3 Subject Alternative Name:
DNS:orders.prod.svc, DNS:orders.prod.svc.cluster.local
tls_config: ca_file: /etc/prometheus/certs/corp-ca.crt # trust the internal CA server_name: orders.prod.svc # verify against the DNS name in the certificate; the address is still the Pod IP # kubelet: kps uses insecureSkipVerify for the kubelet by default (self-signed kubelet certificate), # a better production approach is to enable kubelet serving certificate rotation (serverTLSBootstrap) and then verify against the CA
insecure_skip_verify: true Use only as a temporary measure, and flag it in red during code review.server_name in the scrape config.See Lesson 7 Module 2.
received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for target
Symptom: After upgrading from Prometheus 2.x to 3.x, a batch of old exporters (in-house scripts, Nginx serving static files directly, some network devices) go DOWN immediately; everything was fine before the upgrade.
Root cause: Prometheus 2 parsed the body as text by default when the Content-Type was missing or unrecognized; Prometheus 3 switched to strict mode: it only accepts text/plain;version=0.0.4,text/plain;version=1.0.0,application/openmetrics-text, protobuf, etc., otherwise the scrape fails outright (explicitly listed as a breaking change in the official migration guide). Metric files served by python -m http.server, object storage, or Nginx's default MIME mapping get labeled application/octet-stream or text/html.
docker compose exec prometheus wget -S -qO /dev/null http://fakeexp:8000/metrics 2>&1 | grep -i content-type
Content-Type: application/octet-stream
- job_name: legacy
fallback_scrape_protocol: PrometheusText0.0.4 # new in 3.x: parse with this protocol when the Content-Type is non-compliant
static_configs: [{targets: ["fakeexp:8000"]}]
The long-term fix is to make the exporter return Content-Type: text/plain; version=0.0.4; charset=utf-8 (the official client libraries set it automatically).
/api/v1/targets to list all targets, and check each one's curl -sI Content-Type.See Lesson 1 Module 3 · migration covered in #50.
sample limit exceeded label_limit exceeded (metric: myapp_http_requests_total, number of labels: 31, limit: 30) label_value_length_limit exceeded (metric: myapp_http_requests_total, label name: route, value: "/api/orders/…", length: 2210, limit: 1024) body size limit exceeded target_limit exceeded (number of targets: 812, limit: 500)
Symptom: After a developer releases a new version, the target for that service goes entirely DOWN,all metrics stop (not just the new ones).
Root cause: These are the "circuit breakers" that protect Prometheus: sample_limit (samples per scrape after metric relabeling),label_limit,label_name_length_limit,label_value_length_limit,body_size_limit,target_limit. Once one is exceeded,the whole scrape fails (target_limit applies to the whole job),up=0. The kps / Operator ServiceMonitor fields sampleLimit, and the Prometheus CR's enforcedSampleLimit all generate these configs.
scrape_samples_scraped{job="myapp"} # how many were scraped
scrape_samples_post_metric_relabeling{job="myapp"} # how many after relabeling
prometheus_target_scrapes_exceeded_sample_limit_total # is the counter rising?
curl -s localhost:5000/metrics | grep -v '^#' | cut -d'{' -f1 | sort | uniq -c | sort -rn | head
48211 myapp_http_requests_total ← the route label holds the raw URL (including order numbers)
36 myapp_http_request_duration_seconds_bucket
metric_relabel_configs to drop the metric or label, so the target recovers first; do not simply raise the limit./api/orders/<id>, see #39). sample_limit: 20000
metric_relabel_configs:
- source_labels: [__name__]
regex: myapp_debug_.*
action: drop
sample_limit on every job, and alert on increase(prometheus_target_scrapes_exceeded_sample_limit_total[10m]) > 0 , telling the team "your service has been cut off by the circuit breaker"./metrics (for example, fail if > 5000 lines).See Lesson 7 Module 3 Cardinality explosion: label design and limits.
Get "https://172.18.0.2:10257/metrics": dial tcp 172.18.0.2:10257: connect: connection refused Get "https://172.18.0.2:10259/metrics": dial tcp 172.18.0.2:10259: connect: connection refused Get "http://172.18.0.2:2381/metrics": dial tcp 172.18.0.2:2381: connect: connection refused Get "http://172.18.0.2:10249/metrics": dial tcp 172.18.0.2:10249: connect: connection refused
Symptom: Right after installing kps, Alertmanager immediately fires TargetDown,KubeControllerManagerDown,KubeSchedulerDown,etcdMembersDown/etcdInsufficientMembers and other alerts.
Root cause: kubeadm (kind is also based on kubeadm) by default makes the metrics ports of control-plane components listen only on 127.0.0.1: the controller-manager/scheduler --bind-address=127.0.0.1, etcd's --listen-metrics-urls=http://127.0.0.1:2381, kube-proxy's metricsBindAddress default 127.0.0.1:10249. Prometheus Pods reach them via node IPs, so they are naturally refused. On managed clusters such as AKS/EKS these control-plane components cannot be scraped directly at all; turn them off in the kps values.
docker exec lab-control-plane sh -c 'ss -lntp 2>/dev/null | grep -E "10257|10259|2381|10249"'
kubectl -n kube-system get cm kube-proxy -o jsonpath='{.data.config\.conf}' | grep metricsBindAddress
LISTEN 0 4096 127.0.0.1:10257 … LISTEN 0 4096 127.0.0.1:10259 … LISTEN 0 4096 127.0.0.1:2381 … metricsBindAddress: ""
# Option A (lab / self-built cluster): set the listen address when creating the kind cluster
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
kubeadmConfigPatches:
- |
kind: ClusterConfiguration
controllerManager: {extraArgs: {bind-address: "0.0.0.0"}}
scheduler: {extraArgs: {bind-address: "0.0.0.0"}}
etcd: {local: {extraArgs: {listen-metrics-urls: "http://0.0.0.0:2381"}}}
- |
kind: KubeProxyConfiguration
metricsBindAddress: "0.0.0.0:10249"
# Option B (managed cluster, or if these metrics are not needed): turn them off in the kps values
kubeControllerManager: {enabled: false}
kubeScheduler: {enabled: false}
kubeEtcd: {enabled: false}
kubeProxy: {enabled: false}
0.0.0.0 to listen, use a NetworkPolicy/firewall to restrict access to the monitoring namespace only.See Lesson 5 Module 1.
$ kubectl -n myapp get servicemonitor myapp NAME AGE myapp 12m $ curl -s localhost:9091/api/v1/targets | jq '[.data.activeTargets[] | select(.labels.job=="myapp")] | length' 0
Root cause: A ServiceMonitor must pass through four selection checks before it becomes a scrape config; a mismatch at any point fails "silently":
serviceMonitorSelector: kps defaults to serviceMonitorSelectorNilUsesHelmValues: true, which only selects ServiceMonitors carrying the release: kps label.serviceMonitorNamespaceSelector: whether the namespace where the ServiceMonitor lives is selected.selector.matchLabels must match the labels of Service (not the Pod's),namespaceSelector must include the namespace where the Service lives.endpoints[].port is the name (a string), not a number; if the Service port has no name it cannot be matched (you can use targetPort).kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorSelector}{"\n"}{.items[0].spec.serviceMonitorNamespaceSelector}{"\n"}'
kubectl -n myapp get servicemonitor myapp -o yaml | yq '.metadata.labels, .spec.selector, .spec.endpoints'
kubectl -n myapp get svc myapp --show-labels; kubectl -n myapp get svc myapp -o jsonpath='{.spec.ports}{"\n"}'
# Does the Operator-generated config contain this job?
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -n "serviceMonitor/myapp"
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | grep -i myapp | tail -3
{"matchLabels":{"release":"kps"}}
{}
app.kubernetes.io/name: myapp ← the ServiceMonitor itself has no release: kps
(grep returns nothing: the Operator did not write it into the config)
The Secret that holds the generated config and the Operator Deployment name depend on the release name; use kubectl -n monitoring get secret,deploy to confirm.
kubectl -n myapp label servicemonitor myapp release=kps # Wait for config-reloader to hot-reload (usually < 1 minute), then check /targets # To have kps select all ServiceMonitors: helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --reuse-values \ --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false
serviceMonitor.labels), and have the platform team document release: kps.name: http), and use port: http in ServiceMonitor.kubectl get servicemonitor -A -l '!release' to find "orphans" periodically.See Lesson 5 Module 2 ServiceMonitor, PodMonitor and PrometheusRule.
level=ERROR source=reflector.go:… msg="Failed to watch" err="failed to list *v1.EndpointSlice: endpointslices.discovery.k8s.io is forbidden: User \"system:serviceaccount:monitoring:prometheus\" cannot list resource \"endpointslices\" in API group \"discovery.k8s.io\" in the namespace \"myapp\""
Symptom: Targets in some namespaces all disappear for self-hosted Prometheus (or after switching kps's service discovery role from Endpoints to EndpointSlice),/service-discovery the page shows 0 targets, and the Prometheus log keeps repeating the errors above.
Root cause:kubernetes_sd_configs List/watch against the API server via the ServiceAccount. role: endpointslice requires discovery.k8s.io/endpointslices list/watch; role: endpoints requires the endpoints,services,pods in the core group; only a Role in one namespace was granted, but namespaces lists other namespaces. Kubernetes has marked the v1 Endpoints API as deprecated and recommends EndpointSlice; RBAC is the easiest thing to miss during the migration.
kubectl auth can-i list endpointslices.discovery.k8s.io -n myapp --as=system:serviceaccount:monitoring:prometheus kubectl auth can-i watch pods -n myapp --as=system:serviceaccount:monitoring:prometheus kubectl -n monitoring logs prometheus-0 -c prometheus | grep -c forbidden
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata: {name: prometheus-sd}
rules:
- apiGroups: [""]
resources: ["services", "endpoints", "pods", "nodes", "nodes/metrics"]
verbs: ["get", "list", "watch"]
- apiGroups: ["discovery.k8s.io"]
resources: ["endpointslices"]
verbs: ["get", "list", "watch"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get", "list", "watch"]
prometheus_sd_kubernetes_failures_total (use the actual metric name) or on forbidden messages in the logs.nodes/proxy and similar high-privilege permissions are granted only as needed.$ for i in 1 2 3; do curl -s localhost:5000/metrics | grep '^myapp_http_requests_total{method="GET",route="/",status="200"}'; done
myapp_http_requests_total{method="GET",route="/",status="200"} 1832.0
myapp_http_requests_total{method="GET",route="/",status="200"} 917.0
myapp_http_requests_total{method="GET",route="/",status="200"} 1841.0
Root cause: gunicorn uses several worker processes (-w 2 or more), and prometheus_client by default each process has its own in-memory registry; each scrape lands on a different worker, so the counter value jumps up and down. Prometheus treats a "decrease" as a counter reset,rate() and adds the whole value as a new increase, producing spikes; histograms get corrupted too.
resets(myapp_http_requests_total[15m]) # should normally be 0 or very rare
docker compose exec myapp env | grep -i PROMETHEUS_MULTIPROC_DIR || echo "not set"
# app.py: /metrics uses MultiProcessCollector to aggregate all workers
from prometheus_client import CollectorRegistry, generate_latest, CONTENT_TYPE_LATEST, multiprocess
@app.route("/metrics")
def metrics():
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
return generate_latest(registry), 200, {"Content-Type": CONTENT_TYPE_LATEST}
# gunicorn.conf.py: clean up each worker's files when it exits
from prometheus_client import multiprocess
def child_exit(server, worker):
multiprocess.mark_process_dead(worker.pid)
# compose.yaml: use an empty directory (tmpfs) on every startup
environment: {PROMETHEUS_MULTIPROC_DIR: /tmp/prom}
tmpfs: ["/tmp/prom"]
multiprocess_mode (e.g. livesum,max); myapp_redis_up use max.resets() abnormal increases, which can also reveal frequent application restarts.See Lesson 1 Module 3, Module 8 myapp observability readiness.
level=WARN source=scrape.go:… msg="Error on ingesting samples with different value but same timestamp" component="scrape manager" scrape_pool=node target=http://node-exporter:9100/metrics num_dropped=12 level=WARN … msg="Error on ingesting out-of-order samples" … num_dropped=3
Symptom: The log keeps emitting warnings,prometheus_target_scrapes_sample_duplicate_timestamp_total keeps growing; some metric values are "occasionally wrong".
Root cause: Two samples received exactly the same label set and timestamp but different values. Common causes: ① the exporter itself emits duplicate series (for example, two .prom files in the node_exporter textfile collector write metrics with the same name and labels); ② the exporter sets its own timestamps on metrics (honor_timestamps: true default), so multiple targets emit the same series; ③ the same target is scraped by two jobs, and relabeling sets job/instance to the same value; ④ scraping a Pushgateway or federation with honor_labels: true , where the upstream already has conflicting labels.
docker compose logs prometheus 2>&1 | grep -E "same timestamp|out-of-order" | tail -3 curl -s localhost:9100/metrics | grep -v '^#' | sort | uniq -d -w 80 | head curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | "\(.labels.job) \(.labels.instance)"' | sort | uniq -d
instance is unique after relabeling.honor_timestamps: false.rate(prometheus_target_scrapes_sample_duplicate_timestamp_total[5m]) > 0,rate(prometheus_target_scrapes_sample_out_of_order_total[5m]) > 0.Pick a fault, click "run one scrape", and observe at which of the seven steps the failure happens,up and scrape_* how the metrics change,lastError what it is. The simulation logic follows the Prometheus 3 scrape order (a simplified model).
~/promlab (including fakeexp) and the kind cluster lab. At the end of each experiment, run the "restore rules".cd ~/promlab
cat >> prometheus/prometheus.yml <<'EOF'
- job_name: myapp-timeout
scrape_interval: 15s
scrape_timeout: 1ms
static_configs: [{targets: ["myapp:5000"]}]
EOF
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml && curl -s -X POST localhost:9090/-/reloadsleep 20; curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.job=="myapp-timeout") | "\(.health) \(.lastError)"'
down Get "http://myapp:5000/metrics": context deadline exceeded
scrape_timeout: 20s will be rejected by promtool:FAILED: parsing YAML file /etc/prometheus/prometheus.yml: scrape timeout greater than scrape interval for scrape config with job name "myapp-timeout"
This validation text was checked against the v3.16.0 source config/config.go; the outer promtool FAILED: parsing YAML file … prefix format may vary, so follow the actual output.
cp lab8/prometheus.yml.orig prometheus/prometheus.yml && curl -s -X POST localhost:9090/-/reloadcat >> prometheus/prometheus.yml <<'EOF'
- job_name: legacy
static_configs: [{targets: ["fakeexp:8000"]}]
EOF
curl -s -X POST localhost:9090/-/reload; sleep 20
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.job=="legacy") | .lastError'received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target
python http.server guesses MIME types from the extension; a file with no extension is usually served as application/octet-stream, check against wget -S what you actually see.
sed -i 's/ - job_name: legacy/ - job_name: legacy\n fallback_scrape_protocol: PrometheusText0.0.4/' prometheus/prometheus.yml curl -s -X POST localhost:9090/-/reload; sleep 20 curl -s 'localhost:9090/api/v1/query?query=lab8_demo_value' | jq -r '.data.result[0].value[1]'
42
cat >> prometheus/prometheus.yml <<'EOF'
- job_name: node-limited
sample_limit: 50
static_configs: [{targets: ["node-exporter:9100"]}]
EOF
curl -s -X POST localhost:9090/-/reload; sleep 20
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.job=="node-limited") | "\(.health) \(.lastError)"'
curl -s 'localhost:9090/api/v1/query?query=scrape_samples_scraped{job="node-limited"}' | jq -r '.data.result[0].value[1]'down sample limit exceeded 1123
metric_relabel_configs:
- source_labels: [__name__]
regex: node_(cpu_seconds_total|memory_MemAvailable_bytes|filesystem_avail_bytes)
action: keepNote: sample_limit the limit check looks at the samples counted after relabeling, so this approach lets the target recover to up.
kubectl -n myapp get svc myapp -o jsonpath='{.spec.ports[*].name}{"\n"}' # confirm the port name, e.g. http
cat <<'EOF' | kubectl apply -f -
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: {name: myapp-lab8, namespace: myapp}
spec:
selector: {matchLabels: {app.kubernetes.io/name: myapp}}
endpoints: [{port: http, path: /metrics, interval: 15s}]
EOF
sleep 60; curl -s localhost:9091/api/v1/targets | jq '[.data.activeTargets[] | select(.scrapePool|test("myapp-lab8"))] | length'0
The Service's labels follow what you created in Lesson 5,matchLabels so they must match it.
kubectl -n myapp label servicemonitor myapp-lab8 release=kps
sleep 60; curl -s localhost:9091/api/v1/targets | jq -r '.data.activeTargets[] | select(.scrapePool|test("myapp-lab8")) | "\(.scrapePool) \(.health)"'serviceMonitor/myapp/myapp-lab8/0 up
kubectl -n myapp delete servicemonitor myapp-lab8No verified video specifically covering "Prometheus 3 strict Content-Type checking" and "sample_limit circuit breaker" was found. Below is a 3-minute storyboard you can record yourself:
/targets page; on the right, the terminal curl … | jq .lastError. Introduce the seven-step diagram.received unsupported Content-Type; wget -S shows octet-stream; after adding fallback_scrape_protocol it turns green.sample_limit: 50 on node-exporter, the target turns red; emphasize "the whole scrape is discarded"; restore with a metric_relabel keep.for does it hold for the whole for period → can Prometheus send the alert to Alertmanager → Alertmanager routing / inhibition / silences → did the receiver succeed.le label normalization and left-open, right-closed range selectors.Filter by keywords (for example many-to-many,labelset,le,pending,Notify,receiver) to filter; click a row to jump.
execution: found duplicate series for the match group {instance="myapp:5000"} on the right hand-side of the operation: [{__name__="myapp_redis_up", instance="myapp:5000", job="myapp", pod="a"}, {__name__="myapp_redis_up", instance="myapp:5000", job="myapp", pod="b"}];many-to-many matching not allowed: matching labels must be unique on one side
Symptom: An alert or panel that "multiplies the error rate by instance info" works normally, then suddenly reports this error one day (often after scaling out, after adding a label, or during a rolling deploy when old and new Pods coexist).
Root cause: Binary operations default to one-to-one matching, using on(...)/ignoring(...) as the label set; each side must be unique on its own. group_left/group_right The "many" side may have multiple series, but the "one" side must still be unique. When the data changes and the "one" side has duplicates, it fails at execution time, so it is a data-dependent error and may not show up during development.
count by (instance) (myapp_redis_up) > 1 # find which groups on the "one" side have duplicates
# first aggregate the "one" side to be unique, then group_left to bring in the labels you need
sum by (instance, route) (rate(myapp_http_requests_total{status=~"5.."}[5m]))
* on (instance) group_left ()
max by (instance) (myapp_redis_up)
# info-metric join (kube-state-metrics' *_info metrics are often used this way too)
rate(container_cpu_usage_seconds_total[5m]) * on (namespace, pod) group_left (node) max by (namespace, pod, node) (kube_pod_info)
max by/sum by aggregated to the matching labels; add an input series with two Pods on the same instance to the promtool unit tests.info() function that simplifies info-metric joins (requires promql-experimental-functions); check the official docs before using it in production.See Lesson 1 Module 5 PromQL advanced: histogram_quantile, joins and subqueries.
execution: vector cannot contain metrics with the same labelset
Symptom: Trying to compute the rate of two counters at once: rate({__name__=~"myapp_http_requests_total|myapp_jobs_total"}[5m]), or rewriting labels with label_replace and getting an error.
Root cause:rate(),abs() and arithmetic operations drop __name__. If two series are distinguished only by metric name (all other labels equal), then after the name is dropped their label sets are identical, which makes the result vector invalid. label_replace/label_join The same happens when different series are rewritten to identical label sets.
count by (job, instance) ({__name__=~"myapp_http_requests_total|myapp_jobs_total"})
# query them separately; or first save the name to an ordinary label and then compute
rate(label_replace({__name__=~"myapp_http_requests_total|myapp_jobs_total"}, "metric", "$1", "__name__", "(.+)")[5m:])
# better: two recording rules, each with its own name
The subquery in the example above is for demonstration only; it changes the calculation semantics. In production, prefer "two queries / two recording rules".
__name__ write explicit queries or recording rules per metric name.rate(myapp_http_requests_total[1m]) → no data most of the time rate(myapp_http_requests_total[5m]) → normal # subquery: max_over_time(rate(x[1m])[1h:1m]) has values in 2.x but is empty in 3.x
Root cause:rate() A rate needs at least 2 samples within the window. With a 30s or 1m scrape interval,[1m] the window often holds only 1 sample (scrape jitter or one failed scrape turns it into 0 or 1 samples). Prometheus 3 changed range selectors to left-open, right-closed: a sample that falls exactly on the left boundary is no longer counted. When the query time is perfectly aligned with the scrapes (common with subqueries and query-frontend step alignment),[1m] with a 1m interval,always returns only one sample; the official migration guide gives an example of a query foo[1m:1m] that turns into no data.
count_over_time(myapp_http_requests_total[1m]) # how many samples the window actually contains
prometheus_target_interval_length_seconds{quantile="0.99"}
rate window ≥ 4 × scrape interval (15s interval → [1m]; 1m interval → [4m] or [5m]).$__rate_interval, and set the real scrape interval as the Scrape interval in the data source settings —$__rate_interval = max($__interval + scrape interval, 4 × scrape interval).foo[1m:1m] change to foo[2m:1m] or a similar window that covers at least two points.[5m] window in recording rules; cover the one-sample-in-window case with promtool unit tests.See Lesson 1 Module 4 · Lesson 7 Module 4 Query performance.
{"status":"error","errorType":"bad_data","error":"invalid parameter \"query\": 1:6: parse error: ranges only allowed for vector selectors"}
Symptom: You wrote an expression such as rate(sum by (route) (myapp_http_requests_total)[5m]) or rate(myapp_http_requests_total{status="500"} offset 1h[5m]) kind of expression.
Root cause:[5m] can only directly follow a vector selector (for example metric{...}[5m]); taking a range of a function or aggregation result must use the subquery syntax. (...)[5m:30s] A deeper error is "sum first, then rate": after sum, a counter loses its reset handling, so a reset on one instance looks like an overall decrease and the rate result is wrong. The correct order is always rate first, then sum.
# Correct: rate first, then sum
sum by (route) (rate(myapp_http_requests_total[5m]))
# offset placement: put it after the range
rate(myapp_http_requests_total{status="500"}[5m] offset 1h)
rate(sum( and increase(sum( should always be sent back.unknown function with name "holt_winters" (renamed in Prometheus 3, see #50).See Lesson 1 Module 4.
myapp_http_request_duration_seconds_bucket{le="5"} → newly ingested data cannot be found after the upgrade
myapp_http_request_duration_seconds_bucket{le="5.0"} → has data
Root cause: Official migration guide: at ingestion, Prometheus 3 normalizes the le label of classic histograms and the quantile label values normalized to a floating-point representation ("1" → "1.0","5" → "5.0"), to remove the 2.x problem where the text and protobuf protocols gave different label values. Writing integer le values in alerts, recording rules and dashboards will silently turn into empty results. 0.005,0.5 Values that are already decimals are unaffected, so the problem appears only on some buckets and is hard to notice.
grep -rnE 'le="[0-9]+"|quantile="[0-9]+"' ~/promlab/prometheus/rules/ ~/promlab/grafana/ 2>/dev/null curl -s 'localhost:9090/api/v1/label/le/values' | jq -r '.data[]' | head
rules/slo.yml:12: expr: sum(rate(myapp_http_request_duration_seconds_bucket{le="1"}[5m])) / …
0.005
0.01
…
1.0
2.5
5.0
+Inf
le="1.0" or le="5.0"; queries across the upgrade point are briefly inaccurate, which is acceptable.metric_relabel_configs to convert the normalized values back to integers (only for the affected metrics).histogram_quantile() or the native histogram's histogram_fraction(), rather than referencing bucket boundary strings directly.le="[0-9]+" scan over the rules and dashboard repositories; run the promtool unit tests on 3.x.See Lesson 1 Module 5 · migration covered in #50.
histogram_quantile(0.99, rate(myapp_http_request_duration_seconds_bucket[5m]))
{route="/healthz"} NaN
{route="/api/orders"} +Inf ← or P99 exactly equals a bucket upper bound, e.g. exactly 5
Root cause:
le: histogram_quantile(0.99, sum by (route) (rate(..._bucket[5m]))) not kept le, so the result is empty or wrong; you must sum by (le, route).0.5–1 boundaries can only be interpolated between.sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/api/orders"}[5m]))
sum(rate(myapp_http_request_duration_seconds_count{route="/api/orders"}[5m]))
histogram_quantile(0.99, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m]))) # low-traffic routes: filter by request volume so that NaN does not trigger alerts or disturb panels and on (route) sum by (route) (rate(myapp_http_request_duration_seconds_count[5m])) > 0.1
scrape_native_histograms to enable scraping) for higher precision, provided the client library and downstream storage both support them.{"status":"error","errorType":"execution","error":"query processing would load too many samples into memory in query execution"}
Symptom: The "past 30 days" dashboard, or sum(rate(container_cpu_usage_seconds_total[5m])) a 30-day range query without filters fails; sometimes the same panel works and sometimes it does not.
Root cause: The number of samples a single query holds in memory at once exceeds --query.max-samples (default 50,000,000). Samples in a range query ≈ number of series × (time range / step) + raw samples in the range-vector window. High cardinality + long time range + small step hits the limit easily. The limit protects Prometheus from being OOM-killed by a single query.
count(container_cpu_usage_seconds_total) # number of series involved in the calculation prometheus_engine_query_samples_total # finer detail if per-step stats are enabled
curl -s 'localhost:9090/api/v1/query?query=count(up)&stats=all' | jq '.data.stats.samples'
namespace:container_cpu_usage_seconds:sum_rate5m), so panels query the recording rules instead of the raw metric.--query.max-samples.prometheus_engine_query_duration_seconds and the slow-query log (query_log_file).See Lesson 7 Module 4 query performance: slow PromQL and dashboard optimization.
level=ERROR source=manager.go:… component="rule manager" msg="loading groups failed" err="/etc/prometheus/rules/myapp.yml: 9:15: group \"myapp\", rule 2, \"MyappHighErrorRate\": could not parse expression: 1:62: parse error: unexpected right parenthesis ')'" level=ERROR source=main.go:… msg="Error loading config (--config.file=/etc/prometheus/prometheus.yml)" … err="one or more errors occurred while applying the new configuration (--config.file=\"/etc/prometheus/prometheus.yml\")" # the error the rule manager returns to reload: error loading rules, previous rule set restored
Symptom: You change the rule file and reload, but the new rules do not appear in the UI and the old rules remain; if there is an error at startup, Prometheus exits immediately (CrashLoopBackOff).
Root cause: When the rule file fails to parse during reload, Prometheus keeps the previous rule set and logs the error (prometheus_config_last_reload_successful goes to 0), so it never loads "partially". Common mistakes: unbalanced parentheses in expressions, YAML indentation,for written on a recording rule (invalid field 'for' in recording rule), duplicate group names within the same file,record names containing curly braces (braces present in the recording rule name; should it be in expr?), template syntax errors in annotations. In the Operator setup, PrometheusRule has an admission webhook, so errors are rejected at kubectl apply apply time.
docker compose exec prometheus promtool check rules /etc/prometheus/rules/myapp.yml curl -s 'localhost:9090/api/v1/query?query=prometheus_config_last_reload_successful' | jq -r '.data.result[0].value[1]' curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[].name'
Checking /etc/prometheus/rules/myapp.yml FAILED: /etc/prometheus/rules/myapp.yml: 9:15: group "myapp", rule 2, "MyappHighErrorRate": could not parse expression: 1:62: parse error: unexpected right parenthesis ')' 0
Correct by line/column number → promtool check rules passes → reload → confirm prometheus_config_last_reload_successful == 1.
promtool check config,promtool check rules,promtool test rules (Lesson 5 Module 6).prometheus_config_last_reload_successful == 0 (kps ships with PrometheusBadConfig).See Lesson 2 Modules 1 and 2 · Lesson 5 Module 6 rule testing: promtool and CI.
MyappHighErrorRate (1 active) PENDING Active Since: 2026-11-15 09:41:15 ← Active Since resets every few minutes
ALERTS{alertname="MyappHighErrorRate", alertstate="pending"} appears and disappears
Root cause: An alert must produce a result for for the whole period, with every single rule evaluation, to move to firing; as soon as one evaluation returns empty (the error rate jitters around the threshold, a failed scrape makes rate empty, or the window is too short, #15), the pending state is cleared and the timer restarts. for: 15m + a jittery metric = never firing. Also, evaluation_interval is large (e.g. 1m) while for is short, so the actual trigger time gets stretched.
ALERTS{alertname="MyappHighErrorRate"}
ALERTS_FOR_STATE{alertname="MyappHighErrorRate"} # records the timestamp when pending started
# plot the alert expression in the Graph to see its continuity over 1 hour
sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m])) > 0.05
[10m]), or apply avg_over_time(...[10m:1m]) before the threshold comparison.for: usually 2–10 minutes; for "sustained for 1 hour" semantics, use a longer window rather than a longer for.keep_firing_for: 5m (supported since Prometheus 2.42).ALERTS_FOR_STATE (--rules.alert.for-outage-tolerance default 1h).See Lesson 2 Module 2 alerting rules: for, labels and annotations · Lesson 7 Module 6.
The redis-exporter container exited for 10 minutes, but the RedisDown / RedisMemoryHigh alerts show resolved myapp 1.1 renamed myapp_http_requests_total to myapp_requests_total, so the error-rate alert has never fired since
Root cause: Alerting rules only fire for "series returned by the expression". When the metric does not exist, the expression returns an empty vector, and an empty vector is neither "0" nor "1"; it means "no alert", so alerts that were firing are marked resolved. Alerts that depend on a metric value (redis_up == 0) go blind as soon as the exporter itself dies.
up{job="redis"} # is the exporter itself reachable?
absent(redis_up) # has the metric disappeared completely?
count(myapp_http_requests_total) or vector(0)
- alert: RedisExporterDown
expr: up{job="redis"} == 0 or absent(up{job="redis"})
for: 5m
- alert: MyappMetricsMissing
expr: absent(myapp_http_requests_total{job="myapp"})
for: 10m
labels: {severity: warning}
annotations: {summary: "myapp request metrics are missing (renamed, instrumentation removed, or scrape failed)"}
up == 0 and a absent(up{job="…"}) alert; key business metrics should have an absent() alert.See Lesson 2 Module 8 production-readiness review and common mistakes.
level=ERROR source=sendloop.go:… msg="Error sending alerts" component=notifier alertmanager=http://alertmanager:9093/api/v2/alerts count=3 err="Post \"http://alertmanager:9093/api/v2/alerts\": dial tcp: lookup alertmanager on 127.0.0.11:53: no such host"
Symptom: On the Prometheus /alerts page the alerts are already FIRING, but the Alertmanager UI shows nothing at all.
Root cause: The link from Prometheus to Alertmanager is broken: alerting.alertmanagers wrong address (service name, port, path prefix path_prefix), network unreachable, Alertmanager has authentication enabled, or the config still uses api_version: v1——Prometheus 3 no longer supports the Alertmanager v1 API. In the Operator setup, the Service name / namespace / port name that the Prometheus CR's alerting.alertmanagers points to is wrong.
curl -s localhost:9090/api/v1/alertmanagers | jq '.data' docker compose logs prometheus 2>&1 | grep "Error sending alerts" | tail -2
rate(prometheus_notifications_errors_total[5m]) prometheus_notifications_alertmanagers_discovered prometheus_notifications_dropped_total
{"activeAlertmanagers": [], "droppedAlertmanagers": []} ← none discovered
alerting:
alertmanagers:
- api_version: v2 # v2 is the default; delete the v1 config
static_configs:
- targets: ["alertmanager:9093"]
prometheus_notifications_alertmanagers_discovered < 1,rate(prometheus_notifications_errors_total[5m]) > 0 (kps ships with PrometheusNotConnectedToAlertmanagers,PrometheusErrorSendingAlertsToAnyAlertmanager).level=ERROR … component=dispatcher msg="Notify failed" … err="teams/msteamsv2[0]: notify retry canceled due to unrecoverable error after 1 attempts: unexpected status code 400: …" level=WARN … msg="Notify attempt failed, will retry later" attempts=3 … err="… unexpected status code 429 …" # config validation undefined receiver "teams-prod" used in route root route must specify a default receiver
Symptom: The alerts are visible in the Alertmanager UI, but Teams/Slack/email receives nothing; or the config fails to reload and the old config keeps running.
Root cause: Alertmanager retries each integration of each receiver independently: 4xx (except 429) is treated as unrecoverable and given up immediately; 5xx/429/network errors are retried with exponential backoff until the group's group_interval timeout. Common causes: an expired webhook URL (the old Teams Office 365 Connector has been replaced by Workflows, so you need msteamsv2_configs); a revoked Slack token; SMTP authentication; proxy or egress firewall; template rendering errors that produce an invalid payload. Configuration errors (referencing a receiver that does not exist) are rejected at reload (alertmanager_config_last_reload_successful == 0).
docker compose exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml docker compose logs alertmanager 2>&1 | grep -E "Notify (failed|attempt failed)" | tail -3 curl -s localhost:9093/metrics | grep -E '^alertmanager_notifications_failed_total' | grep -v ' 0$' # bypass Prometheus and send a test alert directly to Alertmanager docker compose exec alertmanager amtool alert add lab8_test severity=warning --annotation=summary="test" --alertmanager.url=http://localhost:9093
Checking '/etc/alertmanager/alertmanager.yml' FAILED: undefined receiver "teams-prod" used in route
alertmanager_notifications_failed_total{integration="msteamsv2",reason="clientError"} 7
amtool check-config → reload.*_file referenced Secret).amtool config routes test --config.file=… severity=critical team=shop confirm which receiver the alert is routed to.rate(alertmanager_notifications_failed_total[10m]) > 0,alertmanager_config_last_reload_successful == 0; for key alerts, configure a second receiver (for example email) as a fallback.amtool check-config and routing tests on alertmanager.yml in CI.09:41 [FIRING:1] MyappHighErrorRate myapp-7d9f-abc ×120 (one per Pod, one per route) 09:41 [FIRING:1] MyappHighErrorRate … two identical messages received (each of the two Alertmanagers sent one) 09:42 [RESOLVED] … 09:43 [FIRING] … repeated resolved/firing
Root cause:
group_by includes pod,instance and other highly variable labels (or group_by: ['...'] groups by all labels), so each series gets its own notification.--cluster.peer , or the two Prometheus replicas' external_labels differ (for example because a replica label is included), so the same alert is treated as two (Alertmanager deduplicates by the full label set).inhibit_rules equal labels on the source and target alerts do not match.keep_firing_for.curl -s localhost:9093/api/v2/status | jq '.cluster | {status, peers: [.peers[].name]}'
docker compose exec alertmanager amtool alert query --alertmanager.url=http://localhost:9093 -o extended | head
curl -s localhost:9090/api/v1/status/config | jq -r '.data.yaml' | grep -A3 external_labels
{"status": "disabled", "peers": []} ← single instance, or the cluster did not form
route:
receiver: default
group_by: [alertname, namespace, service] # do not include pod/instance
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
inhibit_rules:
- source_matchers: [severity="critical"]
target_matchers: [severity="warning"]
equal: [alertname, namespace, service]
HA: the two Alertmanagers should gossip with each other via --cluster.peer, and Prometheus should list both as targets (do not put them behind a load balancer with only one address); use alert_relabel_configs to drop the replica label before sending alerts (the Operator handles this automatically prometheus_replica).
count(ALERTS{alertstate="firing"}),alertmanager_notifications_total rate.See Lesson 2 Module 3 · Lesson 6 Module 2 high availability · Lesson 7 Module 6 alerts not firing or alert storms.
Choose step by step based on the symptom to reach a conclusion and the matching issue numbers; click a button to jump to the details.
~/promlab. Use for i in $(seq 200); do curl -s localhost:5000/ >/dev/null; done first to generate some request data.q='myapp_http_requests_total / on(method) myapp_http_requests_total' curl -s localhost:9090/api/v1/query --data-urlencode "query=$q" | jq -r '.error'
found duplicate series for the match group {method="GET"} on the right hand-side of the operation: [...];many-to-many matching not allowed: matching labels must be unique on one sideYou need at least two different route/status series under the GET method; if there is only one, visit a few more different paths (including a 404 path).
q='myapp_http_requests_total / on(method) group_left() sum by (method) (myapp_http_requests_total)' curl -s localhost:9090/api/v1/query --data-urlencode "query=$q" | jq -r '.data.result[] | "\(.metric.route) \(.metric.status) \(.value[1])"'
/ 200 0.93 /nope 404 0.07
for le in 5 5.0; do
n=$(curl -s localhost:9090/api/v1/query --data-urlencode "query=myapp_http_request_duration_seconds_bucket{le=\"$le\"}" | jq '.data.result | length')
echo "le=\"$le\" -> $n series"
donele="5" -> 0 series le="5.0" -> 4 series
grep -rnE 'le="[0-9]+"' prometheus/rules/, changing each one to float notation, then promtool check rules.cat > prometheus/rules/lab8.yml <<'EOF'
groups:
- name: lab8
interval: 15s
rules:
- alert: Lab8RedisDown
expr: myapp_redis_up == 0
for: 1m
- alert: Lab8RedisExporterGone
expr: up{job="redis"} == 0 or absent(up{job="redis"})
for: 1m
EOF
docker compose exec prometheus promtool check rules /etc/prometheus/rules/lab8.yml && curl -s -X POST localhost:9090/-/reload
docker compose stop redis redis-exporter
for t in 20 60 100; do sleep 40; curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | select(.labels.alertname|startswith("Lab8")) | "\(.labels.alertname) \(.state)"'; echo ---; doneLab8RedisDown pending Lab8RedisExporterGone pending --- Lab8RedisDown firing Lab8RedisExporterGone firing ---
The rule file path must fall within the matching scope of rule_files (Lesson 2 uses /etc/prometheus/rules/*.yml). After myapp detects that Redis is unavailable, myapp_redis_up goes to 0; if your myapp implementation differs, go by the actual results you observe.
docker compose start redis redis-exporter; rm prometheus/rules/lab8.yml; curl -s -X POST localhost:9090/-/reloadsed -i '0,/receiver: /s/receiver: .*/receiver: teams-prod/' alertmanager/alertmanager.yml docker compose exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml
Checking '/etc/alertmanager/alertmanager.yml' FAILED: undefined receiver "teams-prod" used in route
cp lab8/alertmanager.yml.orig alertmanager/alertmanager.yml docker compose exec alertmanager amtool config routes test --config.file=/etc/alertmanager/alertmanager.yml severity=critical alertname=MyappHighErrorRate curl -s -X POST localhost:9093/-/reload
default
The videos above may be based on Prometheus 2.x; for le normalization and left-open right-closed ranges, follow this lesson and the official migration guide. No verified video systematically covering "alert not received" troubleshooting was found; the storyboard is as follows:
absent() alerts fire; compare the two./api/v1/alertmanagers empty and the log Error sending alerts.amtool check-config and amtool config routes test, wrap-up./api/datasources/uid/<uid>/health and the Grafana logs to locate "panel has no data".ama-metrics → Azure Monitor workspace → Managed Grafana (managed identity + Monitoring Data Reader); on EKS, managed collector / ADOT / Prometheus → SigV4 remote write → AMP → AMG (IAM Identity Center/SAML sign-in + IAM role to read the data).Filter by keywords (for example localhost,DS_,provisioned,origin,ama-metrics,403,429) to filter; click a row to jump.
Post "http://localhost:9090/api/v1/query": dial tcp [::1]:9090: connect: connection refused - There was an error returned querying the Prometheus API.
Symptom: Opening http://localhost:9090 in a browser works fine, but testing the same URL in Grafana fails.
Root cause: The Prometheus data source works by default in Server (proxy) mode: queries are sent from the Grafana backend. When Grafana runs in a container,localhost refers to the Grafana container itself. In Compose, use the service name http://prometheus:9090; in Kubernetes use the Service DNS (http://kps-kube-prometheus-stack-prometheus.monitoring:9090, use the actual name).
docker compose exec grafana wget -qO- http://prometheus:9090/-/ready curl -s -u admin:admin localhost:3000/api/datasources | jq -r '.[] | "\(.uid) \(.name) \(.url)"' curl -s -u admin:admin localhost:3000/api/datasources/uid/prometheus/health | jq
Prometheus Server is Ready.
prometheus Prometheus http://localhost:9090
{"message": "Post \"http://localhost:9090/api/v1/query\": dial tcp [::1]:9090: connect: connection refused …", "status": "ERROR"}
# grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
uid: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 15s # = Prometheus's scrape_interval; affects $__rate_interval (#15)
uid, and have dashboard JSON reference the uid rather than the name.See Lesson 1 Module 6 Grafana architecture: data sources, dashboards and panels.
Failed to upgrade legacy queries Datasource ${DS_PROMETHEUS} was not found
Dashboard import failed: datasource input "DS_PROMETHEUS" references UID "…" which was not found
Symptom: A dashboard JSON downloaded from grafana.com, or exported from another Grafana with "Export for sharing externally", is placed into Grafana via a provisioning file or the API: all panels error out and variable dropdowns are empty.
Root cause: A dashboard in the "shared externally" format writes the data source as a placeholder ${DS_PROMETHEUS}, and declares it in __inputs . Only the UI Import flow shows a "select data source" prompt and replaces the placeholder; provisioning and /api/dashboards/db do not replace it.
grep -o '"\${DS_[A-Z_]*}"' grafana/dashboards/node-exporter-full.json | sort | uniq -c
jq '.__inputs' grafana/dashboards/node-exporter-full.json
112 "${DS_PROMETHEUS}"
[{"name":"DS_PROMETHEUS","label":"Prometheus","type":"datasource","pluginId":"prometheus"}]
# Option A: replace the placeholder with a fixed uid before provisioning
sed -i 's/\${DS_PROMETHEUS}/prometheus/g' grafana/dashboards/node-exporter-full.json
# Option B: define a variable of type datasource in the dashboard (name: datasource) and have panels reference ${datasource}
# Option C: use /api/dashboards/import with inputs (equivalent to UI import)
__inputs only for dashboards shared externally.\${DS_, and fail if it is found.Grafana panel: No data
Prometheus Graph: sum(rate(myapp_http_requests_total{route=~"/api/.*"}[5m])) → has values
Root causes (by frequency):
=~"$route" is expanded into (/api/a|/api/b), regex special characters in the path (.,+,?) are not escaped; or All's custom value is .* written as = rather than =~.$__interval is very large, or when it is short, [$__interval] is less than 2 scrape intervals (#15); use $__rate_interval.${datasource} variable's current value is wrong.Panel menu → Inspect → Query: check the requests Grafana actually sends (the expanded PromQL,start/end/step) and the raw response; paste the expanded PromQL back into Prometheus to run it.
docker compose logs grafana 2>&1 | grep -iE "level=error.*(query|datasource)" | tail -3 date -u; docker compose exec prometheus date -u # are the clocks consistent?
sum(rate(myapp_http_requests_total{route=~"$route"}[$__rate_interval]))
# variable definition: Query = label_values(myapp_http_requests_total, route); tick Multi-value and Include All, leave Custom all value empty (Grafana generates and escapes the regex)
timeInterval matches the real scrape_interval; use $__rate_interval consistently.See Lesson 1 Module 7 variables and the RED method · Lesson 7 Module 7 Grafana troubleshooting.
Cannot save provisioned dashboard
Symptom: The on-call engineer fixed a panel in the UI but saving failed; or they used "Save as", so the version in Git drifts further and further from production, and the next deploy overwrites the changes.
Root cause: Dashboards loaded from provisioning files are authoritative as files, and UI edits are blocked by default (allowUiUpdates: false). Even if UI edits are allowed, the next Grafana restart or file change overwrites them with the file contents.
cat grafana/provisioning/dashboards/*.yml
curl -s -u admin:admin "localhost:3000/api/dashboards/uid/myapp-red" | jq '.meta | {provisioned, provisionedExternalId}'
{"provisioned": true, "provisionedExternalId": "myapp-red.json"}
grafana/dashboards/ → deploy.allowUiUpdates: true for convenient debugging, but remember that "the file is still authoritative".apiVersion: 1
providers:
- name: myapp
folder: myapp
type: file
allowUiUpdates: false
updateIntervalSeconds: 30
options: {path: /var/lib/grafana/dashboards, foldersFromFilesStructure: true}
uid is fixed,id set to null, to avoid multi-instance conflicts.origin not allowed
Symptom: Grafana sits behind Nginx/Ingress/Application Gateway; the login page opens, but logging in or saving a dashboard returns 403 origin not allowed; or after login it redirects to localhost:3000.
Root cause: Grafana runs a CSRF check on state-changing requests: the Origin sent by the browser must match the address Grafana believes it has ([server] root_url/domain, or the Host forwarded by the proxy). The reverse proxy rewrote Host without setting root_url, or TLS is terminated at the proxy and Grafana thinks it is http, so they do not match.
docker compose exec grafana sh -c 'env | grep GF_SERVER' curl -sI https://grafana.example.com/login | grep -i location kubectl -n monitoring logs deploy/kps-grafana -c grafana | grep -i "origin not allowed" | tail -2
[server] domain = grafana.example.com root_url = https://grafana.example.com/ ; for a sub-path deployment: https://example.com/grafana/ and set serve_from_sub_path = true [security] csrf_trusted_origins = sso.example.com ; add only if cross-origin sources really exist
Nginx must forward proxy_set_header Host $host; (WebSocket/Live also needs the Upgrade header).
grafana.grafana.ini.server.root_url ; review the Ingress together with root_url.See Lesson 7 Module 7.
level=error … msg="…" error="database is locked"
Symptom: To get high availability, Grafana was scaled to 2 replicas sharing one grafana.db on a PVC; afterwards saving dashboards fails intermittently, users are randomly logged out, and the same Grafana Alerting alert is sent twice.
Root cause: SQLite is a single-file database, not suited to concurrent writes from multiple processes (especially over cross-node network storage); lock contention causes database is locked; sessions are stored locally, so they drop when the load balancer switches. Each Grafana Alerting replica evaluates the rules and sends notifications; if no HA cluster is configured ([unified_alerting] ha_peers), notifications are duplicated.
[database]
type = postgres
host = grafana-db.postgres.database.azure.com:5432
name = grafana
user = grafana
password = $__file{/etc/secrets/grafana-db-password}
ssl_mode = require
[unified_alerting]
ha_peers = grafana-headless.monitoring.svc.cluster.local:9094
ha_listen_address = ${POD_IP}:9094
[FIRING:37] DatasourceNoData (myapp-alerts) [FIRING:12] DatasourceError (myapp-alerts) error=… context deadline exceeded
Root cause: When a Grafana-managed alert rule's query returns no data or the query errors, it is handled according to the rule's "No data and error handling" policy: by default it enters the NoData/Error state and generates DatasourceNoData/DatasourceError alerts. One Prometheus restart, network blip or query timeout makes all rules alert together; a metric rename (#22) leaves rules in NoData for a long time.
Alerting → Alert rules → rule details → State history; check the Grafana logs for ngalert related errors; verify in Explore with the same query and time range.
docker compose logs grafana 2>&1 | grep -i "ngalert" | grep -iE "error|nodata" | tail -5
See Lesson 2 Module 5 Grafana Alerting and unified alerting.
$ kubectl -n kube-system get cm | grep ama-metrics ama-metrics-settings-configmap 1 3d ama-metrics-prometheus-config 1 10m ← just created, but no myapp metrics can be found in the Azure Monitor workspace
Root cause: The Azure Monitor managed Prometheus metrics add-on only reads the ConfigMap with the fixed name: cluster-level targets use the kube-system under ama-metrics-prometheus-config (scraped by the ReplicaSet collector), node-level targets use ama-metrics-prometheus-config-node (scraped by the DaemonSet), and Windows nodes have a separate ama-metrics-prometheus-config-node-windows; the scrape config must be placed under the key named prometheus-config in data. A wrong name, namespace or key is silently ignored; if the config has a syntax error, the config-reader container log shows it.
kubectl get pods -n kube-system | grep ama-metrics kubectl logs -n kube-system <ama-metrics-operator-targets-pod> -c config-reader kubectl logs -n kube-system <ama-metrics-pod> -c prometheus-collector | tail -20 # each ama-metrics pod has a Prometheus agent UI (9090) kubectl port-forward -n kube-system <ama-metrics-pod> 9090 # browser: 127.0.0.1:9090/config, /service-discovery, /targets
kind: ConfigMap
apiVersion: v1
metadata:
name: ama-metrics-prometheus-config
namespace: kube-system
data:
prometheus-config: |-
scrape_configs:
- job_name: myapp
kubernetes_sd_configs: [{role: pod, namespaces: {names: [myapp]}}]
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
regex: myapp
action: keep
You can first validate the config with the promconfigvalidator tool provided in the Azure docs (see lesson 3). After applying, the ama-metrics Pods restart to load the new config; the official note that "the restart count matches the number of ConfigMap changes" is normal.
See Lesson 3 Module 3 scrape config: ConfigMap, PodMonitor and ServiceMonitor.
$ kubectl apply -f servicemonitor.yaml servicemonitor.monitoring.coreos.com/myapp created ← assumes the Prometheus Operator CRDs are installed in the cluster (myapp does not appear in ama-metrics' /targets) # if the cluster does not have this CRD, you get: error: resource mapping not found for name: "myapp" namespace: "myapp" from "servicemonitor.yaml": no matches for kind "ServiceMonitor" in version "monitoring.coreos.com/v1"
Root cause: The Azure managed Prometheus add-on uses its own CRD group azmonitoring.coreos.com/v1 (PodMonitor, ServiceMonitor), to avoid conflicts with a self-hosted Prometheus Operator in the cluster; it does not read monitoring.coreos.com objects. When migrating from kps to the managed service, reusing the old YAML directly will not work.
kubectl get crd | grep -E 'azmonitoring|monitoring.coreos.com' kubectl get servicemonitors.azmonitoring.coreos.com -A kubectl logs -n kube-system <ama-metrics-operator-targets-pod> -c targetallocator | tail
podmonitors.azmonitoring.coreos.com 2026-… servicemonitors.azmonitoring.coreos.com 2026-… No resources found
apiVersion: azmonitoring.coreos.com/v1
kind: ServiceMonitor
metadata: {name: myapp, namespace: myapp}
spec:
selector: {matchLabels: {app: myapp}}
endpoints: [{port: http, path: /metrics, interval: 30s}]
apiVersion into values (one for self-hosted kps and one for the managed service).release: kps selector logic — you do not need that label.See Lesson 3 Module 3.
403 Forbidden … does not have authorization to perform action 'Microsoft.Monitor/accounts/data/metrics/read' …
Symptom: An Azure Monitor workspace (Prometheus) data source was added in Managed Grafana; the test fails or the panel shows 403, while the Azure Monitor (platform metrics) data source works normally.
Root cause: Managed Grafana accesses data using its managed identity (system-assigned or user-assigned) or an app registration. When creating the workspace, the portal by default assigns the system managed identity the subscription-level Monitoring Reader— it can read Azure Monitor metrics and logs, but querying Prometheus data in an Azure Monitor workspace requires Monitoring Data Reader (the official docs stress this). Also, if the creator lacks permission to assign roles, the default role assignment is skipped; a user's own role in Grafana (Grafana Admin/Editor/Viewer) and their data access permission are two different things.
GID=$(az grafana show -n amg-prom-lab -g rg-prom-lab --query identity.principalId -o tsv) AMW=$(az monitor account show -n amw-prom-lab -g rg-prom-lab --query id -o tsv) az role assignment list --assignee "$GID" --all -o table
Principal Role Scope … Monitoring Reader /subscriptions/…
az role assignment create --assignee-object-id "$GID" --assignee-principal-type ServicePrincipal \ --role "Monitoring Data Reader" --scope "$AMW" # or: az aks update … --grafana-resource-id configures this automatically via the CLI when linking (see lesson 3 and the official docs)
See Lesson 3 Module 4 Azure Managed Grafana: identity, permissions and data sources.
kube_pod_container_status_restarts_total → present kube_deployment_spec_strategy_rollingupdate_max_surge → missing container_fs_reads_bytes_total → missing (present in a self-hosted kps)
Root cause: When managed Prometheus is enabled,the minimal ingestion profile is on by default: default targets (kubelet, cAdvisor, kube-state-metrics, node-exporter, etc.) ingest only the metrics used by the default dashboards, recording rules and alerts, to control ingestion volume and cost. In the newer config schema (v2) this setting lives separately under cluster-metrics and controlplane-metrics , under the minimal-ingestion-profile; the older schema (v1) uses minimalingestionprofile = true|false.
kubectl -n kube-system get cm ama-metrics-settings-configmap -o yaml | grep -nE 'minimal|keep-list|keep_list' | head kubectl -n kube-system port-forward <ama-metrics-pod> 9090 # see the actual relabel/keep rules at 127.0.0.1:9090/config
Keep the minimal config and add keep list per target (collect only the extra metrics you need); turn off the minimal config only when you really need all metrics. Field names follow the current ConfigMap template (Microsoft provides a downloadable template).
# download the official ama-metrics-settings-configmap template → add a regex to the keep list of the relevant target, for example # kubestate = "kube_deployment_spec_strategy_rollingupdate_max_surge|kube_.*_labels" kubectl apply -f ama-metrics-settings-configmap.yaml
msg="non-recoverable error" … err="server returned HTTP status 403 Forbidden: {\"message\":\"User: arn:aws:sts::111122223333:assumed-role/prom-lab-amp-ingest/… is not authorized to perform: aps:RemoteWrite on resource: arn:aws:aps:ca-central-1:111122223333:workspace/ws-… \"}"
msg="non-recoverable error" … err="server returned HTTP status 403 Forbidden: {\"message\":\"Missing Authentication Token\"}"
Symptom: A self-hosted Prometheus (or kps) on EKS is configured with AMP's remote_write URL and data never gets written; or after the AMG workspace is upgraded from Grafana 10 to 12, the original "Prometheus type + SigV4" data source errors out.
Root cause: Both the AMP write and query APIs require AWS SigV4 signing: Prometheus must configure a remote_write in sigv4 block, and the Pod must obtain, via IRSA or EKS Pod Identity, a role with aps:RemoteWrite permission (the region and workspace ARN must match). No sigv4 block → Missing Authentication Token; insufficient role permissions → not authorized to perform: aps:RemoteWrite. On the query side, the AWS docs state that starting with Grafana 12 on AMG, the Core Prometheus plugin removed SigV4 authentication, and AMP data sources automatically migrate to the Amazon Managed Service for Prometheus plugin; self-hosted Grafana 12+ also needs to switch to that plugin.
kubectl -n monitoring get sa -o yaml | grep -E 'eks.amazonaws.com/role-arn' ; aws eks list-pod-identity-associations --cluster-name prom-lab --region ca-central-1 kubectl -n monitoring exec prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus -- env | grep -E 'AWS_(ROLE_ARN|WEB_IDENTITY|CONTAINER_CREDENTIALS)' aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:role/prom-lab-amp-ingest --action-names aps:RemoteWrite --query 'EvaluationResults[].EvalDecision'
rate(prometheus_remote_storage_samples_failed_total[5m]) prometheus_remote_storage_highest_timestamp_in_seconds - ignoring(remote_name, url) group_right prometheus_remote_storage_queue_highest_sent_timestamp_seconds
# kps values (the remoteWrite of the Prometheus CR)
prometheus:
serviceAccount:
annotations: {eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/prom-lab-amp-ingest}
prometheusSpec:
remoteWrite:
- url: https://aps-workspaces.ca-central-1.amazonaws.com/workspaces/ws-…/api/v1/remote_write
sigv4: {region: ca-central-1}
aps:RemoteWrite, and the Grafana role gets only query-type permissions.err="server returned HTTP status 429 Too Many Requests: ingestion rate limit (6666.666666666667) exceeded while adding 499 samples and 0 metadata" err="server returned HTTP status 429 Too Many Requests: user=…_ws-…: per-user series limit (local limit: 0 global limit: 3000000 actual local limit: 500000) exceeded" err="server returned HTTP status 400 Bad Request: … per-user series limit of 10000000 exceeded, …"
Symptom: After launching a new service or turning on all metrics of an exporter, the AMP / Azure Monitor workspace shows gaps in its data; the Prometheus remote write queue backs up (#46). On Azure, the workspace's Metrics show Active Time Series % Utilization or Events Per Minute Ingested % Utilization approaching or exceeding 100%.
Root cause: The managed service has per-workspace active series and ingestion rate quotas (AMP also has an API TPS limit per rate); exceeding them leads to throttling (429) or rejection (400). AMP's active-series quota adjusts automatically within a range based on the last 30 minutes of usage, but sudden spikes are still rejected. The root cause is usually a cardinality spike (#39).
# on the sending Prometheus (the three queries recommended by the AWS docs)
prometheus_tsdb_head_series
rate(prometheus_tsdb_head_samples_appended_total[5m])
sort_desc(count by (__name__) ({__name__!=""}))
# Azure: in the workspace's Metrics, check Active Time Series % Utilization / Events Per Minute Ingested % Utilization az monitor metrics list --resource "$AMW" --metric "ActiveTimeSeriesPercentUtilization" -o table # use the metric name shown in the portal
write_relabel_configs to drop the spiking metrics/labels (this only affects the remote side; local data is kept).remote_write:
- url: …
write_relabel_configs:
- source_labels: [__name__]
regex: "apiserver_request_duration_seconds_bucket|etcd_.*"
action: drop
cluster + __replica__ external label scheme); otherwise duplicate samples also consume quota (#47).See Lesson 3 Module 8 · Lesson 4 Module 8 cost, cleanup and self-test.
Choose step by step based on the symptom to reach the conclusion and the matching issue numbers.
~/promlab Grafana (the admin password follows the one set in lesson 1; shown as admin:admin below). Lab 3-D needs the Azure resources from lesson 3 and incurs cost, so you can just read it.cd ~/promlab cp grafana/provisioning/datasources/prometheus.yml lab8/ds.yml.orig # file name follows lesson 1 sed -i 's#url: http://prometheus:9090#url: http://localhost:9090#' grafana/provisioning/datasources/prometheus.yml docker compose restart grafana && sleep 10 curl -s -u admin:admin localhost:3000/api/datasources/uid/prometheus/health | jq -r '.status, .message'
ERROR Post "http://localhost:9090/api/v1/query": dial tcp [::1]:9090: connect: connection refused …
If the data source uid is not prometheus, first curl -s -u admin:admin localhost:3000/api/datasources | jq check it.
cp lab8/ds.yml.orig grafana/provisioning/datasources/prometheus.yml && docker compose restart grafana, then health returns OK.cat > lab8/shared.json <<'EOF'
{"dashboard":{"uid":"lab8-shared","title":"lab8 shared","panels":[{"type":"timeseries","title":"up",
"datasource":{"type":"prometheus","uid":"${DS_PROMETHEUS}"},
"targets":[{"expr":"up","refId":"A","datasource":{"type":"prometheus","uid":"${DS_PROMETHEUS}"}}],
"gridPos":{"h":8,"w":12,"x":0,"y":0}}]},"overwrite":true}
EOF
curl -s -u admin:admin -H 'Content-Type: application/json' -X POST localhost:3000/api/dashboards/db -d @lab8/shared.json | jq -r .statussuccess
Open localhost:3000/d/lab8-shared, and the panels report that the data source cannot be found (the error wording varies by version).
sed -i 's/\${DS_PROMETHEUS}/prometheus/g' lab8/shared.json
curl -s -u admin:admin -H 'Content-Type: application/json' -X POST localhost:3000/api/dashboards/db -d @lab8/shared.json | jq -r .statuscurl -s -u admin:admin -X DELETE localhost:3000/api/dashboards/uid/lab8-sharedls grafana/dashboards/ # provisioned dashboards from lesson 1, e.g. myapp-red.json
DUID=$(jq -r .uid grafana/dashboards/myapp-red.json) # do not name the variable UID: in bash it is a read-only variable
curl -s -u admin:admin localhost:3000/api/dashboards/uid/$DUID | jq '.meta.provisioned'
curl -s -u admin:admin localhost:3000/api/dashboards/uid/$DUID | jq '{dashboard: .dashboard, overwrite: true}' \
| curl -s -u admin:admin -H 'Content-Type: application/json' -X POST localhost:3000/api/dashboards/db -d @- | jq -r '.message'true Cannot save provisioned dashboard
grafana/dashboards/myapp-red.json → wait updateIntervalSeconds or restart Grafana → the version number increases.az aks get-credentials -g rg-prom-lab -n aks-prom-lab kubectl get pods -n kube-system | grep ama-metrics kubectl get cm -n kube-system | grep ama-metrics kubectl get crd | grep azmonitoring
ama-metrics-5f7c…-x2k4p 2/2 Running ama-metrics-ksm-… 1/1 Running ama-metrics-node-… 2/2 Running ama-metrics-operator-targets-… 2/2 Running ama-metrics-settings-configmap 1 3d podmonitors.azmonitoring.coreos.com servicemonitors.azmonitoring.coreos.com
Pod names and container counts follow the actual output.
P=$(kubectl get pods -n kube-system -o name | grep ama-metrics-operator-targets | head -1) kubectl logs -n kube-system $P -c config-reader | tail -20 GID=$(az grafana show -n amg-prom-lab -g rg-prom-lab --query identity.principalId -o tsv) az role assignment list --assignee "$GID" --all --query "[].roleDefinitionName" -o tsv
az group delete -n rg-prom-lab --yes --no-wait deletes all lab resources).Storyboard (no verified video specifically covering Grafana reverse-proxy / provisioning errors was found):
${DS_PROMETHEUS} a dashboard, demonstrating the difference between UI Import and provisioning.az role assignment list and aws iam simulate-principal-policy./tsdb-status and prometheus_tsdb_* metrics to find the culprit label.Filter by keywords (for example series,OOM,lock,11,000,retrying,exported_,holt) to filter; click a row to jump.
prometheus_tsdb_head_series 312k → 3.1M process_resident_memory_bytes 2.1 GiB → 14 GiB (then OOMKilled, see #40) /tsdb-status page "Top 10 label names with high memory usage": user_id, path, trace_id
Root cause: Each unique label combination is a separate time series resident in memory in the head block (index + current chunk). Putting values of this kind,unbounded values into labels makes the series count grow linearly with traffic; series that are constantly created and removed ("churn", e.g. Pod names change on every release) also bloat the head and index. In myapp's case, the route label, if written as request.path a raw URL instead of a route template, you will see /api/orders/10001,/api/orders/10002……
curl -s localhost:9090/api/v1/status/tsdb | jq '.data | {headStats, top_metrics: .seriesCountByMetricName[:5], top_labels: .labelValueCountByLabelName[:5]}'
topk(10, count by (__name__) ({__name__=~".+"})) # heavy; run with care in production, prefer /tsdb-status
count(count by (route) (myapp_http_requests_total)) # how many values a label has
topk(5, scrape_series_added) # which target is creating new series recently
rate(prometheus_tsdb_head_series_created_total[5m]) # churn
{"headStats":{"numSeries":3104221,…},
"top_metrics":[{"name":"myapp_http_requests_total","value":2810455}, …],
"top_labels":[{"name":"route","value":2809117}, …]}
metric_relabel_configs (labeldrop to drop unbounded labels, or drop to drop the whole metric), and set sample_limit (#7).request.url_rule.rule (route template) as the route label; put ID-type information in logs or traces (link them via exemplars when needed). metric_relabel_configs:
- action: labeldrop
regex: user_id|trace_id
- source_labels: [__name__, route]
regex: myapp_http_requests_total;/api/orders/[0-9]+
target_label: route
replacement: /api/orders/<id>
prometheus_tsdb_head_series > some threshold and deriv(prometheus_tsdb_head_series[1h]) abnormal growth; for each job's scrape_series_added build a topk panel.See Lesson 7 Module 3 Cardinality explosion: label design and limits.
level=INFO source=head.go:… msg="Replaying WAL, this may take a while"
level=INFO source=head.go:… msg="WAL segment loaded" segment=412 maxSegment=980 duration=…
$ kubectl -n monitoring describe pod prometheus-kps-kube-prometheus-stack-prometheus-0 | grep -A3 "Last State"
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
Symptom: A cardinality spike (#39) or one huge query gets Prometheus OOMKilled; after the restart it must first replay the WAL before it can serve. During replay all active series are rebuilt in memory, memory exceeds the limit again, and it gets stuck in CrashLoopBackOff with the readiness probe failing all the time.
Root cause: The WAL holds all samples from roughly the last 2–3 hours (not yet written to blocks); the memory needed for replay ≈ the head's memory before the crash. If the high-cardinality data that caused the OOM is still in the WAL, a plain restart cannot heal it. Prometheus 3 automatically sets GOMEMLIMIT to the container memory limit (per the official migration guide), so GC is more aggressive, but it cannot make a head that needs more memory than the limit fit within it.
kubectl -n monitoring logs prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus --previous | grep -E "WAL|head" | tail -5 kubectl -n monitoring exec prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus -- du -sh /prometheus/wal /prometheus/chunks_head
18.2G /prometheus/wal ← much larger than usual 2.1G /prometheus/chunks_head
wal/ (along with chunks_head/) directories, then restart.resources, and the Operator rolls the StatefulSet.process_resident_memory_bytes / prometheus_tsdb_head_series to calculate the actual value for your environment.--query.max-samples,--query.timeout,--query.max-concurrency; Grafana slow queries should go through recording rules (#45).sample_limit; in large clusters, split into several Prometheus servers by function or namespace (functional sharding).See Lesson 7 Module 5 TSDB internals: head block, WAL, compaction and disk.
level=ERROR … component=tsdb msg="compaction failed" err="… write /prometheus/01JCX…tmp-for-creation/chunks/000001: no space left on device" level=ERROR … msg="… WAL …" err="write /prometheus/wal/00000981: no space left on device"
Symptom: PVC usage at 100%; Prometheus is still running but new data writes fail and queries error out, or it fails to start.
Root cause: Only time-based retention is set (the kps default is retention: 10d), with no size-based retention; after cardinality grows (#39) or the number of scrape targets increases, 10 days of data exceeds the PVC. Compaction needs extra temporary space (old blocks are deleted only after the new block is written), so when the disk is nearly full, compaction fails first, blocks pile up, and it becomes a vicious cycle.
kubectl -n monitoring exec prometheus-…-0 -c prometheus -- df -h /prometheus kubectl -n monitoring exec prometheus-…-0 -c prometheus -- sh -c 'du -sh /prometheus/* | sort -h | tail'
prometheus_tsdb_storage_blocks_bytes
prometheus_tsdb_compactions_failed_total
predict_linear(kubelet_volume_stats_available_bytes{persistentvolumeclaim=~"prometheus-.*"}[6h], 24*3600) < 0
allowVolumeExpansion , change the size directly).--storage.tsdb.retention.size/.time the command-line flags are marked DEPRECATED; writing them to the config file is recommended:# prometheus.yml (3.16)
storage:
tsdb:
retention:
time: 15d
size: 45GB # leave headroom for compaction and WAL, roughly 80–85% of the volume size
# kps / Operator: Prometheus CR
prometheus:
prometheusSpec:
retention: 15d
retentionSize: 45GB
prometheus_tsdb_compactions_failed_total growth (kps ships with KubePersistentVolumeFillingUp and similar rules).See Lesson 2 Module 7 storage, retention and resource planning.
level=ERROR source=main.go:… msg="Fatal error" err="opening storage failed: lock DB directory: resource temporarily unavailable"
Symptom: In Compose, Prometheus was scaled from docker compose up --scale prometheus=2 to several replicas; or in Kubernetes, Prometheus was changed from a StatefulSet to a Deployment using RollingUpdate, so the old Pod still holds the same volume while the new Pod starts; or an NFS/shared volume is mounted by two instances.
Root cause: The TSDB creates lock file in the data directory and takes an exclusive lock (flock), to stop two processes from writing the same TSDB at once, which would directly corrupt the data. "resource temporarily unavailable" means another process already holds the lock.
docker ps --filter volume=$(docker volume ls -q | grep -i prom | head -1) --format '{{.Names}}'
kubectl -n monitoring get pods -o wide | grep prometheus
strategy: Recreate.--storage.tsdb.no-lockfile Only use this when you are 100% sure there is no concurrent access (for example in some read-only debugging scenarios); do not use it to "fix" this error.level=ERROR … msg="Fatal error" err="opening storage failed: … corrupted block 01JCXQ8K…: …" level=WARN … component=tsdb msg="Encountered WAL read error, attempting repair" err="…"
Symptom: After a node power loss, a cloud disk fault or a forced Pod deletion, Prometheus fails to start or prints WAL repair logs on startup.
Root cause: When the last WAL segment is truncated mid-write, Prometheus repairs it automatically (truncating back to the last complete record) and carries on, losing at most a few seconds of data; but if a persisted block (meta.json,index,chunks) is corrupted, opening the database fails and it needs manual handling.
docker compose run --rm --entrypoint promtool prometheus tsdb list /prometheus | head ls -la /prometheus/01JCXQ8K*/ # does meta.json exist, and is its size 0? docker compose run --rm --entrypoint promtool prometheus tsdb analyze /prometheus 01JCXQ8K…
kubectl delete pod --force --grace-period=0 to delete Prometheus's data.See Lesson 7 Module 5.
{"status":"error","errorType":"bad_data","error":"exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)"}
Symptom: An in-house script or a Grafana panel (with a very small Min interval, e.g. 1s) errors when querying 7 days of data.
Root cause: The number of points in a range query = (end − start) / step, and the Prometheus HTTP API hard-limits it to 11,000 points per series (the source comment says this is enough for 1 week at 60s resolution or 1 year at 1h resolution). 7 days / 1s step = 604,800 points.
step=60.$__interval; keep Max data points at its default.curl -s localhost:9090/api/v1/query_range --data-urlencode 'query=up' \ --data-urlencode "start=$(date -d '-7 days' +%s)" --data-urlencode "end=$(date +%s)" --data-urlencode 'step=60' | jq -r .status
See Lesson 7 Module 4.
{"status":"error","errorType":"timeout","error":"query timed out in expression evaluation"}
Symptom: At 9 a.m. everyone opens the "whole-cluster overview" dashboard at once; Prometheus CPU maxes out and queries time out (default --query.timeout=2m), and alerting rule evaluation gets delayed (prometheus_rule_group_last_duration_seconds exceeds the interval,prometheus_rule_group_iterations_missed_total grows).
Root cause: Expensive queries: unfiltered regexes ({__name__=~".+"},job=~".*") applied to high-cardinality metrics histogram_quantile and then aggregated over several labels, long ranges with small steps, dozens of panels × a dozen-plus queries each, and Grafana auto-refresh every 5s. All queries and rule evaluations share the same Prometheus process.
# turn on the query log (global section of prometheus.yml) and find the slowest queries global: query_log_file: /prometheus/query.log
docker compose exec prometheus sh -c "tail -200 /prometheus/query.log" | jq -r '[.stats.timings.evalTotalTime, .params.query] | @tsv' | sort -rn | head
histogram_quantile(0.9, sum by (le, slice) (rate(prometheus_engine_query_duration_seconds_bucket[5m]))) rate(prometheus_rule_group_iterations_missed_total[10m])
level:metric:operations).iterations_missed growth (kps ships with PrometheusRuleFailures and PrometheusMissingRuleEvaluations).level=WARN source=queue_manager.go:… component=remote remote_name=… url=https://…/api/v1/remote_write msg="Failed to send batch, retrying" err="Post \"https://…/api/v1/remote_write\": context deadline exceeded"
Symptom: Grafana queries against Thanos/Mimir/AMP lag by tens of minutes or even hours, while the local Prometheus is fine; the wal/ on Prometheus's disk keeps growing (remote write reads from the WAL, and when it falls behind the WAL cannot be truncated).
Root cause: remote write sends in parallel through shards; when the rate is not enough it automatically adds shards, up to max_shards (default 50). The bottleneck may be receiver throttling (429, #38), high network latency, batches that are too small (max_samples_per_send default 2000), a slow receiver, or recoverable errors causing endless retries. If the lag exceeds the WAL truncation window, data is dropped.
# how many seconds behind (the official recommended query) prometheus_remote_storage_highest_timestamp_in_seconds - ignoring(remote_name, url) group_right prometheus_remote_storage_queue_highest_sent_timestamp_seconds prometheus_remote_storage_shards vs prometheus_remote_storage_shards_max rate(prometheus_remote_storage_samples_retried_total[5m]) rate(prometheus_remote_storage_samples_failed_total[5m]) rate(prometheus_remote_storage_samples_dropped_total[5m])
remote_write:
- url: https://mimir.example.com/api/v1/push
queue_config:
max_shards: 100 # only raise it when shards are already maxed out
max_samples_per_send: 5000 # increase batch size to reduce the number of requests
capacity: 20000 # usually 2–4 times max_samples_per_send
write_relabel_configs: # send only the data the remote side needs
- source_labels: [__name__]
regex: "go_.*|process_.*"
action: drop
PrometheusRemoteWriteBehind) and samples_failed_total growth.protobuf_message: io.prometheus.write.v2.Request) reduces bandwidth but requires receiver support; check the official docs for current status.sum(rate(myapp_http_requests_total[5m])) → local Prometheus: 120 req/s; Thanos Query: 240 req/s
count(up{job="myapp"}) → 4 (there are actually only 2 Pods)
Root cause: The two HA Prometheus replicas scrape the same targets, each producing its own copy of the data. They must have external labels that differ only in the replica label external_labels (for example replica: a/b or the Operator's prometheus_replica), and deduplicate on the query side by that label: Thanos Query uses --query.replica-label=replica, Mimir uses the HA tracker on the write side (cluster + __replica__ label) to accept data from only one replica. Forgetting to configure deduplication, or having other differences in the two replicas' external labels (for example, one carries a region), causes the data to be treated as two separate datasets.
count by (prometheus_replica) (up{job="myapp"})
count by (replica, cluster) (up)
kubectl -n monitoring get deploy thanos-query -o yaml | grep -- '--query.replica-label'
# Prometheus (the two replicas differ only in replica)
global:
external_labels: {cluster: lab, replica: a}
# Thanos Query
args: ["query", "--query.replica-label=replica", "--query.replica-label=prometheus_replica", "--endpoint=…"]
count(up{job="X"}) should equal the number of target instances.See Lesson 6 Modules 2 and 3, long-term storage: Thanos and Grafana Mimir.
server returned HTTP status 400 Bad Request: … per-user series limit of 150000 exceeded … (err-mimir-max-series-per-user) … server returned HTTP status 400 Bad Request: … the sample has been rejected because another sample with a more recent timestamp has already been ingested … (err-mimir-sample-out-of-order) …
Symptom: On a multi-tenant Mimir platform, one team's data suddenly goes partly missing; the sending Prometheus logs show many 4xx errors.
Root cause:
-ingester.max-global-series-per-user (runtime config max_global_series_per_user)—almost always a cardinality problem (#39); there is also a per-metric max-series-per-metric limit.# sending side rate(prometheus_remote_storage_samples_failed_total[5m]) # Mimir side (check the Mimir docs for metric names) sum by (user, reason) (rate(cortex_discarded_samples_total[5m]))
accept_ha_samples + cluster/__replica__ label); fix duplicate targets; if you need to accept out-of-order samples, set an out-of-order time window for the tenant.See Lesson 6 Modules 3 and 4, multi-cluster and multi-tenancy.
myapp_http_requests_total{exported_instance="myapp-7d9f…:5000", exported_job="myapp", instance="prom-edge-1:9090", job="federate"}
Root cause: When scraping, if the scraped data already has job,instance labels that conflict with labels Prometheus attaches to the target, the default (honor_labels: false) renames the original labels to exported_job,exported_instance. For federation and Pushgateway scenarios you must use honor_labels: true to keep the upstream labels. Another common problem is a federation scrape with a match[] scope that is too large: one scrape pulls hundreds of thousands of series, which times out (#2) or stores all the raw data again in the central Prometheus.
- job_name: federate
honor_labels: true
metrics_path: /federate
scrape_interval: 60s
scrape_timeout: 50s
params:
'match[]':
- '{__name__=~"job:.*|namespace:.*"}' # federate only the aggregated recording rules
static_configs:
- targets: ["prom-edge-1:9090", "prom-edge-2:9090"]
external_labels: {cluster: …}, so that the source can still be told apart after federation.See Lesson 6 Module 1 monitoring architecture choices: single instance, federation and remote write.
Error loading config (--config.file=/etc/prometheus/prometheus.yml) … err="parsing YAML file /etc/prometheus/prometheus.yml: yaml: unmarshal errors:\n line 31: field scrape_classic_histograms not found in type config.ScrapeConfig" … could not parse expression: 1:1: parse error: unknown function with name "holt_winters"
Root cause (incompatible-change list from the official 3.0 migration guide):
| Change | Symptom | Action |
|---|---|---|
scrape_classic_histograms Renamed to always_scrape_classic_histograms | Config load failure | Renamed |
holt_winters Renamed to double_exponential_smoothing, and requires --enable-feature=promql-experimental-functions | Rule load failure | Renamed + feature flag |
No longer supports the Alertmanager v1 API (requires AM ≥ 0.16 and api_version: v2) | Alerts cannot be sent (#23) | Upgrade AM, update the config |
| Scraping strictly checks Content-Type | old exporters DOWN (#6) | fallback_scrape_protocol |
le/quantile Values normalized to floating point | rules/panels silently empty (#17) | change to le="1.0" |
| Range selectors and lookback are left-open, right-closed | short-window rate and subqueries become empty (#15) | widen the window |
In regexes, . match newlines | relabel/matchers now also match values containing \n values | use this when the old behavior is needed: [^\n] |
| remote write no longer uses HTTP/2 by default | more connections | if needed, enable_http2: true |
| UTF-8 metric and label names are allowed by default | metric names may change | metric_name_validation_scheme: legacy keep the old behavior |
The log format changes to log/slog (time=… level=INFO source=…) | Log parsing / alert rules break | Update the parsing rules in the log pipeline |
Several feature flags are merged into default behavior (e.g. expand-external-labels, in external labels the $var is replaced by environment variables) | External labels containing $ values get rewritten | Use $$ escaping |
# run all configs and rules through the 3.x promtool in CI first docker run --rm -v "$PWD/prometheus:/cfg" --entrypoint promtool prom/prometheus:v3.16.0 check config /cfg/prometheus.yml docker run --rm -v "$PWD/prometheus:/cfg" --entrypoint promtool prom/prometheus:v3.16.0 test rules /cfg/tests/*.yml grep -rnE 'holt_winters|scrape_classic_histograms|api_version: *v1|le="[0-9]+"' prometheus/ grafana/
See Lesson 7 Module 8, mixed fault blind box · official Prometheus 3.0 migration guide.
Drag the number of values for each label to see how many series one metric produces, and the rough effect on head memory. Per-series memory is estimated from empirical values (default 4 KiB, adjustable); calibrate it with your environment's process_resident_memory_bytes / prometheus_tsdb_head_series .
~/promlab. Lab 4-A will make local Prometheus memory grow, so clean up immediately afterwards.cd ~/promlab
docker compose -f compose.yaml -f lab8/compose.lab8.yml --profile card up -d cardgen
cat >> prometheus/prometheus.yml <<'EOF'
- job_name: cardgen
static_configs: [{targets: ["cardgen:8000"]}]
EOF
curl -s -X POST localhost:9090/-/reload
for i in 1 2 3; do sleep 60; curl -s 'localhost:9090/api/v1/query?query=prometheus_tsdb_head_series' | jq -r '.data.result[0].value[1]'; done14873 26911 38804 ← about +12000 per minute (200 new user_ids per second × a scrape every 15 seconds)
curl -s localhost:9090/api/v1/status/tsdb | jq -r '.data.labelValueCountByLabelName[:3][] | "\(.name) \(.value)"'
user_id 36120 __name__ 912 le 15
cat >> prometheus/prometheus.yml <<'EOF'
metric_relabel_configs:
- action: labeldrop
regex: user_id
EOF
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml && curl -s -X POST localhost:9090/-/reload
sleep 60; curl -s 'localhost:9090/api/v1/query?query=scrape_series_added{job="cardgen"}' | jq -r '.data.result[0].value[1]'0
After labeldrop, several samples with identical labels appear within the same scrape; Prometheus keeps only one and logs the duplicates (#12). The real fix must be made at the instrumentation point (remove or aggregate user_id). Series already in the head are cleared from memory after about 2 hours, with compaction.
docker compose -f compose.yaml -f lab8/compose.lab8.yml --profile card rm -sf cardgen, restore prometheus.yml and hot-reload.for step in 1 60; do
curl -s localhost:9090/api/v1/query_range --data-urlencode 'query=up' \
--data-urlencode "start=$(( $(date +%s) - 7*86400 ))" --data-urlencode "end=$(date +%s)" --data-urlencode "step=$step" | jq -r '"step=\('$step') \(.status) \(.error // "")"'
donestep=1 error exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX) step=60 success
VOL=$(docker inspect "$(docker compose ps -q prometheus)" --format '{{range .Mounts}}{{if eq .Destination "/prometheus"}}{{.Name}}{{end}}{{end}}')
echo "volume=$VOL"
docker run --rm -v "$VOL":/prometheus prom/prometheus:v3.16.0 --config.file=/etc/prometheus/prometheus.yml --storage.tsdb.path=/prometheus 2>&1 | grep -m1 -E "lock|Fatal"time=… level=ERROR source=main.go:… msg="Fatal error" err="opening storage failed: lock DB directory: resource temporarily unavailable"
If your compose file uses a bind mount (a host directory) rather than a named volume,Name is empty; use {{.Source}} instead. Keep the image version the same as in lesson 1.
cat >> prometheus/prometheus.yml <<'EOF'
remote_write:
- url: http://fakeexp:8000/api/v1/write # an endpoint that does not accept writes: python http.server returns 501 for POST
name: blackhole
EOF
docker compose exec prometheus promtool check config /etc/prometheus/prometheus.yml && curl -s -X POST localhost:9090/-/reload
sleep 60; docker compose logs prometheus 2>&1 | grep -E "remote_name=blackhole" | tail -2… component=remote remote_name=blackhole … msg="non-recoverable error" … err="server returned HTTP status 501 Unsupported method ('POST'): …"501 is a 5xx, so Prometheus retries it as a recoverable error (the log reads Failed to send batch, retrying) or treats it as unrecoverable, depending on how the version classifies status codes; check the actual log. Either way, the "seconds behind" value below keeps growing, or the samples are counted as failed.
q='prometheus_remote_storage_highest_timestamp_in_seconds - ignoring(remote_name, url) group_right prometheus_remote_storage_queue_highest_sent_timestamp_seconds' curl -s localhost:9090/api/v1/query --data-urlencode "query=$q" | jq -r '.data.result[] | "\(.metric.remote_name) behind=\(.value[1])s"' curl -s 'localhost:9090/api/v1/query?query=prometheus_remote_storage_samples_failed_total' | jq -r '.data.result[0].value[1]'
The PromCon 2018/2019 talks are based on Prometheus 2.x; the concepts still apply, but check the 3.x docs for limit parameter names. Storyboard (remote write backlog):
Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.
Prometheus is a CNCF-graduated open-source monitoring system and time-series database: it periodically scrapes metrics from targets over HTTP /metrics , stores them in a local TSDB, queries them with PromQL, and uses rules to generate alerts and hand them to Alertmanager. Benefits of the pull model: the monitoring side controls the pace and the target list,up the metrics naturally show whether a target is alive, the target side is simple to implement (it only needs to expose one HTTP endpoint), and it is easy to debug locally with curl.
remote_write (sending),--web.enable-remote-write-receiver and --web.enable-otlp-receiver (receiving).scrape_configs:
- job_name: myapp
scrape_interval: 15s
static_configs: [{targets: ["myapp:5000"]}]
Mention that "the monitoring system should be more reliable and simpler than the systems it monitors"; Prometheus's single binary, local storage and lack of external dependencies are designed exactly for this; leave long-term storage and the global view to Thanos/Mimir.
"Pull is always better than push" — the trade-off should be explained according to the scenario.
See Lesson 1 Module 1.
Counter Only increases (resets to zero on restart); use rate()/increase() to see the rate, e.g. total requests; Gauge instantaneous values that can go up or down, e.g. memory or queue length; Histogram puts observations into predefined buckets (_bucket{le},_sum,_count), the server uses histogram_quantile() to compute quantiles, and can be aggregated across instances; Summary computes quantiles on the client, which is accurate but cannot be aggregated across instances.
| Histogram | Summary | |
|---|---|---|
| Where quantiles are computed | Server side (at query time) | Client side |
| Aggregatable | Yes (sum by le) | No (averaging quantiles is meaningless) |
| Accuracy | Limited by bucket layout | Configurable error |
| Cost | One series per bucket | One series per quantile + client CPU |
from prometheus_client import Counter, Histogram, Gauge
REQS = Counter("myapp_http_requests_total", "requests", ["method", "route", "status"])
LAT = Histogram("myapp_http_request_duration_seconds", "latency", ["route"],
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))
REDIS_UP = Gauge("myapp_redis_up", "redis reachable", multiprocess_mode="max")
scrape_native_histograms config option; from 3.9 the feature flag is a no-op and the feature is stable (scraping must be explicitly enabled).Point out the naming convention: a counter ends with _total , and the unit goes in the name (_seconds,_bytes), using base units.
"Use a gauge to record request counts and then delta()" — negative values appear when the process restarts, and the counter reset handling is lost.
See Lesson 1 Module 2.
The core is Prometheus server (service discovery, scraping, TSDB, PromQL engine, rule evaluation, HTTP API/UI). Around it: exporter/client libraries expose metrics; Alertmanager receives alerts, groups, inhibits, silences and routes them to notification channels; Grafana visualization; Pushgateway handles batch jobs; Thanos/Mimir (or a managed service) provides HA querying and long-term storage.
--agent): only scraping + remote write, with no local queries or rules; suited to edge sites or many clusters pushing data to a central place.Proactively draw the data flow (scrape → storage → query/rules → alerts) and the control flow (service discovery), and mark the single point: the local disk of a single Prometheus.
Calling Grafana a "monitoring system", or believing Alertmanager computes the alert conditions (the computation happens in the Prometheus rules).
See Lesson 1 Module 1.
Each time series is uniquely identified by a metric name plus a set of labels (key/value), for example myapp_http_requests_total{method="GET",route="/",status="200"}; a series is a stream of samples of (timestamp, float64 value). Cardinality (cardinality) is the number of series, equal to the product of the number of values each label can take. Cardinality directly determines memory, disk and query cost.
__name__ label; Prometheus 3 allows UTF-8 metric/label names (queries use the {"my.metric", …} quoted syntax).job,instance are attached by the scrape; external_labels are attached only when interacting with external systems (remote write, federation, alerts)./tsdb-status,prometheus_tsdb_head_series.Mention that churn (series constantly being created and removed) also has a cost, for example when Pod names change on every release.
"The more labels the better, for easier querying".
Service discovery produces a target with __meta_* labels → relabel_configs decides whether to keep or drop it, and the final address and labels → each scrape_interval gets one HTTP GET (timeout scrape_timeout) → check status code and Content-Type → parse text/OpenMetrics/protobuf → metric_relabel_configs → check sample/label limits → append to the head and write to the WAL → write up and scrape_* metrics.
up == 0 scrape_duration_seconds > 5 scrape_samples_post_metric_relabeling > 10000
Mention the X-Prometheus-Scrape-Timeout-Seconds request header and the staleness mechanism.
"A failed scrape keeps the last value" — in fact all samples of this scrape are discarded and a stale marker is written.
See Lesson 1 Module 3.
relabel_configs Applies to targets before scraping (service discovery labels → whether to scrape, which address to scrape, which labels to attach); metric_relabel_configs applies to every sample after scraping (dropping metrics, deleting labels, rewriting label values), before storage. There are also write_relabel_configs (before remote write sends) and alert_relabel_configs (before alerts are sent).
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
regex: "true"
action: keep
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
metric_relabel_configs:
- source_labels: [__name__]
regex: go_gc_.*
action: drop
- action: labeldrop
regex: user_id
replace (default),keep,drop,keepequal/dropequal,hashmod (sharding),labelmap,labeldrop,labelkeep,lowercase/uppercase.^…$); in Prometheus 3, . also match newlines.__ are deleted after relabeling (__address__,__metrics_path__,__scheme__,__param_* are used to control scraping).Give an example of using hashmod for scrape sharding; mention sample_limit is checked after metric relabel (#7).
In relabel_configs , dropping metrics by __name__ — at this point there is no metric name yet, so it has no effect.
See Lesson 1 Module 3.
Pushgateway is only suitable for service-level short-lived batch jobs (for example a nightly backup job): push results to Pushgateway before the job ends, and Prometheus scrapes them later. It is not suited to turning ordinary services into push-based ones: it is a single point of failure, it never expires old data automatically, and it loses the up health semantics (up) of the pushers; it also concentrates all pushers' series on a single target.
cat <<EOF | curl --data-binary @- http://pushgateway:9091/metrics/job/nightly_backup/instance/db1 # TYPE backup_last_success_timestamp_seconds gauge backup_last_success_timestamp_seconds $(date +%s) backup_duration_seconds 312 EOF
honor_labels: true, otherwise the pushed job/instance is renamed to exported_* (#49).time() - backup_last_success_timestamp_seconds > 26*3600.Point out that for monitoring batch jobs the most important thing is the last successful time, not in-job process metrics.
"Use Pushgateway for every service behind a firewall" — use agent mode + remote write instead.
See Lesson 1 Module 3.
An exporter is a program that translates the state of a third-party system (Linux, Redis, MySQL, network devices) into the Prometheus metric format; examples are node_exporter (v1.12.1), redis_exporter, and blackbox_exporter (probes HTTP/TCP/ICMP/DNS, v0.29.1). A good exporter reads the current state synchronously at scrape time (it does not cache stale data unless collection is expensive), does not aggregate, follows metric naming conventions, and provides *_up a metric indicating whether it can connect to the monitored system; use one exporter per instance (or the multi-target pattern).
collect() scrape), rather than looping in the background to set set() gauges.X-Prometheus-Scrape-Timeout-Seconds rule, or collect in the background, cache the results, and expose the collection timestamp.__param_target, so only one exporter is deployed.- job_name: blackbox-http
metrics_path: /probe
params: {module: [http_2xx]}
static_configs: [{targets: ["http://myapp:5000/healthz"]}]
relabel_configs:
- {source_labels: [__address__], target_label: __param_target}
- {source_labels: [__param_target], target_label: instance}
- {target_label: __address__, replacement: blackbox-exporter:9115}
Mention the exporter port-assignment convention (the default port list maintained on the official wiki) and security (exporters may expose sensitive information and need network isolation, TLS or authentication; see the web config of exporter-toolkit).
"Compute averages in the exporter before exposing them" — this loses the raw information; aggregate in PromQL instead.
See Lesson 1 Module 3 · Lesson 5 Module 7 black-box monitoring.
New samples are first written to the in-memory head block, and are also appended to the WAL (write-ahead log, used for crash recovery); chunks that fill up in the head are mmapped to disk (chunks_head/) to save memory. About every 2 hours, the older data in the head is persisted as an immutable 2h block (index + chunks + meta.json + tombstones), and the WAL is truncated along with it. In the background, compaction merges small blocks into larger ones (up to 10% of the retention period or 31 days, whichever is smaller),retention and retention deletes the oldest whole blocks by time or size.
/api/v1/admin/tsdb/delete_series first writes a tombstone; the data is actually removed during compaction (requires --web.enable-admin-api).out_of_order_time_window accepts out-of-order samples within a window, written to a separate OOO head and WBL.storage.tsdb.retention (time/size/percentage); the old command-line flags are marked DEPRECATED.Mention the risk of WAL replay after an OOM (#40), and that the WAL grows when remote write reads from it and falls behind (#46).
"Prometheus writes to disk once per sample", or "retention deletes individual samples".
See Lesson 7 Module 5.
Prometheus HA = Two (or more) completely identical independent replicas, each scraping, storing and evaluating rules on its own; their external_labels data differs only in the replica label, and the query side (Thanos Query, the Mimir HA tracker, managed services) deduplicates. Alertmanager HA means multiple instances share silences and notification logs via gossip (--cluster.peer), and Prometheus sends each alert to all instances, and the cluster deduplicates so that only one notification goes out.
replicas: 2 automatically adds prometheus_replica external labels, and removes them before sending alerts.alerting:
alertmanagers:
- static_configs:
- targets: ["alertmanager-0:9093", "alertmanager-1:9093", "alertmanager-2:9093"]
Point out the common causes of duplicate alerts: replica external labels not removed, and Alertmanager not clustered (#25).
"Prometheus primary/standby + shared NFS".
See Lesson 6 Module 2.
Prometheus is responsible for scraping, storage, querying and rule evaluation; Alertmanager is responsible for alert deduplication, grouping, inhibition, silences and notification routing; Grafana is responsible for visualization (and optionally Grafana Alerting), and it does not store metric data, but only stores metadata such as dashboards, data sources, users and alert rules (SQLite/PostgreSQL/MySQL).
Mention that Grafana HA needs an external database and alerting HA peers (#31).
"Grafana pulls data from Prometheus and stores it".
New UI; UTF-8 metric/label names; OTLP reception (--web.enable-otlp-receiver); Remote-Write 2.0 protocol support; native histograms moving toward stable (from 3.9 the feature flag has no effect; enable them with scrape_native_histograms ); automatic setting of GOMEMLIMIT/GOMAXPROCS from the container limit. Incompatible changes: strict Content-Type checking on scrape,le/quantile normalized to floats, range selectors left-open right-closed, regex . matching newlines,holt_winters renamed, Alertmanager v1 API removed, config options renamed, logs switched to slog format.
The symptoms and fixes for each incompatible change are in the table in #50. Upgrade strategy: first upgrade to 2.55.x to clear deprecation warnings → use the 3.x promtool in CI to check configs and rule tests → scan rules/dashboards for integer le and holt_winters → upgrade HA replicas one at a time and compare key queries.
{"http.server.duration", method="GET"}; when the old behavior is needed, use metric_name_validation_scheme: legacy.Being able to explain how "left-open, right-closed" affects foo[1m:1m] shows you have actually read the migration guide.
"3.0 is just a UI revamp, so just upgrade".
See #6, #15, #17 and #50 in this lesson.
OpenTelemetry (OTel) is the open standard and SDK/Collector for collecting and transporting telemetry (traces, metrics, logs); Prometheus is the metric storage and query system. They complement each other: an application can instrument with the OTel SDK and push via OTLP push to Prometheus (the native OTLP receiver in 3.x), or the OTel Collector's Prometheus receiver can scrape existing exporters and send the data on to a backend via remote write / OTLP.
service.name), and dot-separated naming; Prometheus needs cumulative temporality and flattened labels. Prometheus 3's UTF-8 support and OTLP conversion config (otlp block, promoting resource attributes and name translation strategies, reduce naming conflicts; check the official docs for the exact options.target_info series by default; they can be promoted to labels through configuration, or joined in queries.prometheus --web.enable-otlp-receiver # receiving endpoint /api/v1/otlp/v1/metrics
Mention exemplars: attaching a trace ID to histogram samples, so you can jump from a Grafana metric graph to the trace.
"OTel will replace Prometheus" — OTel is not a storage/query system.
See Lesson 6 Module 6, OpenTelemetry and its relationship with Prometheus.
The team has 200 VMs and one AKS cluster, and some services are already containerized; alerting relies on Zabbix triggers. Give an assessment and migration recommendations.
Developers propose that each job push its metrics to Pushgateway with labels including task_id. How would you assess this? Give an alternative design.
task_id Unbounded → cardinality explosion; Pushgateway never expires → series accumulate without limit; single point of failure.batch_task_duration_seconds (histogram, by task_type),batch_tasks_total{task_type,result},batch_last_success_timestamp_seconds{task_type}; per-job details go to logs/traces.No verified video specifically about "Prometheus interview questions" with reliable content was found; it is recommended to record yourself in a mock interview and play it back.
Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.
rate(x[5m]): within the window, the average per-second growth rate, with counter resets handled and extrapolated to the window boundaries; suited to alerts and recording rules; irate(x[5m]): uses only the last two samples to compute an instantaneous rate; responsive but jumpy, suitable only for high-resolution troubleshooting graphs; increase(x[1h]) = rate(x[1h]) × 3600, the total increase within the window (syntactic sugar; after extrapolation it may be a decimal).
sum by (route) (rate(myapp_http_requests_total[5m])) # QPS
sum(increase(myapp_http_requests_total{status=~"5.."}[1h])) # number of 5xx in the last hour (approximate)
max by (instance) (irate(node_network_receive_bytes_total[1m])) # troubleshoot spikes
deriv(),delta(),*_over_time.Mention using $__rate_interval in Grafana.
"irate is more precise, so it is better".
See Lesson 1 Module 4.
Instant vector: each series has one value at a given time (up); Range vector: all samples of each series within a time window (up[5m]), which can only be passed to functions (rate, *_over_time). For an instant query, Prometheus looks backward from the query time for the nearest sample, looking back at most lookback delta (default 5 minutes); when a series disappears, Prometheus writes stale marker, so the query stops returning it immediately, instead of continuing to return the old value for 5 minutes.
--query.lookback-delta Adjustable; increase it when the scrape interval exceeds 5 minutes, otherwise the graph shows gaps.max_over_time(rate(x[5m])[1h:1m]): evaluates the inner expression every minute over the last hour to get a range vector; it is expensive, so replace it with a recording rule in the long run.Explain why a 15-minute scrape interval is an anti-pattern in Prometheus (both lookback and rate windows are affected).
"An instant query only returns samples exactly at that moment".
rate walks through the samples in the window; when it sees a value drop, it treats it as a reset and adds back the value from before the drop (i.e. it assumes the counter restarts from 0). It then divides the increase from the first to the last sample by their time difference, and extrapolates to the whole window: since samples rarely fall exactly on the window boundaries, not extrapolating would systematically underestimate. Extrapolation has a limit: if the first sample is more than 1.1× the average interval away from the window start, it only extrapolates half an average interval; and it never extrapolates to a point where the counter would be below 0.
increase() decimals appear; the increase of a low-frequency counter may exceed the actual number of events.promql-extended-range-selectors (visible in the v3.16 source code) that gives range selectors different semantics, such as no extrapolation; check the official docs for the exact syntax and status; production alerts should still rely on rate() mainly.Proactively mention resets() for detecting frequent restarts.
"rate is (last − first) / window".
See Lesson 1 Module 4(recommended video: PromLabs "Understanding Counter Rates and Increases in PromQL").
histogram_quantile(0.99, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m]))): first compute the rate of each bucket and aggregate it by le (plus the dimensions you want to keep); then find which bucket holds the 99th percentile among the cumulative buckets, and linearly interpolate within that bucket.
le; coarse bucket layout causes error (keep buckets near the SLO threshold); NaN when there is no traffic; beyond the largest finite bucket it can only return that boundary (#18); in Prometheus 3, le values are normalized to floats (#17).rate(_sum[5m]) / rate(_count[5m]).sum(rate(_bucket{le="0.25"}[5m])) / sum(rate(_count[5m])).histogram_quantile(0.99, sum(rate(x[5m]))) no need for le, with higher precision; histogram_fraction() computes the ratio over a time range.Note that summary cannot be aggregated, so multi-replica services should choose histogram.
avg(histogram_quantile(0.99, …)).
See Lesson 1 Module 5.
A binary operation matches by default all labels (except __name__) one-to-one. on(a,b) matches using only the specified labels, and ignoring(c) ignores the specified labels. When one side has several series matching one series on the other side, use group_left (the left side is the "many" side) or group_right, and the parentheses list the labels to carry over from the "one" side.
# attach the node name to Pod CPU (kube_pod_info is an info metric whose value is 1)
sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))
* on (namespace, pod) group_left (node) kube_pod_info
# error rate: aggregate both sides to the same labels, then divide directly
sum by (route) (rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum by (route) (rate(myapp_http_requests_total[5m]))
found duplicate series for the match group (#13).and/or/unless are many-to-many, and often used for filtering (… and on(route) rate(..._count[5m]) > 0.1).x > bool 5 Returns 0/1 instead of filtering.Mention the experimental info() function in Prometheus 3, which simplifies info-metric joins.
Treating group_left as SQL's LEFT JOIN (it does not keep unmatched left-side series).
See Lesson 1 Module 5.
A recording rule runs PromQL at interval intervals, writes the results as new series, and is used to: speed up expensive queries (dashboards, long ranges), provide stable input for alerts, and roll up across levels (federation transfers only aggregated results). The official naming convention is level:metric:operations, for example route:myapp_http_requests:rate5m.
groups:
- name: myapp.rules
interval: 30s
rules:
- record: route:myapp_http_requests:rate5m
expr: sum by (route) (rate(myapp_http_requests_total[5m]))
- record: route:myapp_http_errors:ratio_rate5m
expr: |
sum by (route) (rate(myapp_http_requests_total{status=~"5.."}[5m]))
/ sum by (route) (rate(myapp_http_requests_total[5m]))
concurrent-rule-eval).for (#20).promtool tsdb create-blocks-from rules to backfill.Mention that the multi-window recording rules for SLOs (rate5m, rate30m, rate1h, rate6h…) are the foundation of burn-rate alerts (Q45).
"Recording rules are just aliases for queries".
See Lesson 2 Module 1.
Each evaluation cycle, the rule runs the expression: series with results enter pending; once the condition has held for the for duration, they become firing and are sent to Alertmanager (per resend_delay interval); when the expression no longer returns the series, it becomes inactive, and Prometheus sends a endsAt with the resolved attached. keep_firing_for Lets the alert keep firing for a while after the condition disappears, reducing flapping.
- alert: MyappHighErrorRate
expr: route:myapp_http_errors:ratio_rate5m > 0.05
for: 5m
keep_firing_for: 10m
labels: {severity: critical, team: shop}
annotations:
summary: "{{ $labels.route }} error rate {{ $value | humanizePercentage }}"
runbook_url: https://runbooks.example.com/myapp/high-error-rate
$value the value into labels (every change in value would create a new alert).ALERTS and ALERTS_FOR_STATE, and is restored after a restart.Every alert carries runbook_url and severity, and states what severity means (whether it needs to wake someone up immediately).
"for is the interval at which the alert is re-sent" — that is Alertmanager's repeat_interval.
See Lesson 2 Module 2.
Routing tree: alerts start at the root route and are matched downwards by matchers (by default stop at the first match unless continue: true is set), which determines the receiver; Grouping: alerts with identical group_by labels are merged into one notification,group_wait group_wait (first wait),group_interval group_interval (interval when new alerts join the group),repeat_interval repeat_interval (reminders when nothing has changed); Inhibition: when a source alert is firing, target alerts that match and whose equal labels are identical are silenced; Silences: temporarily mute alerts matching the matchers for a period of time (maintenance windows).
route:
receiver: default
group_by: [alertname, namespace]
routes:
- matchers: [severity="critical"]
receiver: pagerduty
continue: true
- matchers: [team="shop"]
receiver: teams-shop
inhibit_rules:
- source_matchers: [alertname="NodeDown"]
target_matchers: [severity=~"warning|critical"]
equal: [instance]
time_intervals:
- name: offhours
time_intervals: [{weekdays: ["saturday", "sunday"]}]
mute_time_intervals/active_time_intervals Implement routing by time period.amtool config routes test; view: amtool silence query.Mention that overly fine grouping causes alert storms, and that an HA setup that is not clustered causes duplicates (#25).
"Alertmanager recalculates the alert conditions".
See Lesson 2 Module 3.
Only send "wake someone up" alerts for user-visible symptoms (error rate, latency, availability, SLO burn); cause-type signals (high CPU, a single Pod restarting) go to dashboards or low-priority tickets. Every alert must be actionable, have a runbook and a clear owner; use grouping, inhibition, sensible for durations and burn rates to reduce noise; regularly review the alerts' "useful rate".
predict_linear) to generate tickets.Cite Google SRE's view: "every page should feel necessary".
"Turn on every alert the exporters ship with, better too many than too few".
When the monitoring system itself goes down, it cannot alert on its own failure, so you need: ① Prometheus monitoring each other, or another system monitoring it (up, config reloads, rule evaluation failures, notification failures, TSDB compaction, remote write lag); ② one always firing Watchdog alert, continuously sent to an external "dead man's switch" service (for example a PagerDuty/Opsgenie heartbeat, or Healthchecks); once heartbeats stop arriving, the external service raises the alarm, which covers the case where the whole chain is broken.
- alert: Watchdog
expr: vector(1)
labels: {severity: none}
annotations: {summary: "alert-chain heartbeat, do not silence"}
# Alertmanager routing: matchers [alertname="Watchdog"] → heartbeat receiver, repeat_interval: 1m
prometheus_config_last_reload_successful,prometheus_rule_evaluation_failures_total,prometheus_notifications_errors_total,alertmanager_notifications_failed_total,prometheus_tsdb_compactions_failed_total, remote write lag in seconds./api/health, or the cloud service's built-in health checks.Mention deploying a small meta-monitoring Prometheus across regions or clouds.
"Prometheus is very stable, so there is no need to monitor it".
See Lesson 2 Module 8.
Alerts only fire for series returned by the expression, so when a metric disappears the alert silently "resolves" (#22). absent(v) When v is empty, it returns one series with value 1, used for alerts such as "a metric / job does not exist"; absent_over_time(v[10m]) checks whether there has been no data for a period of time.
absent(up{job="myapp"}) # the whole job disappears (SD or config problem)
up{job="myapp"} == 0 # instance exists but the scrape fails
absent_over_time(myapp_http_requests_total[15m]) # business metric disappears (renamed, instrumentation removed)
sum(rate(x[5m])) or vector(0) # make panels / calculations get 0 when there is no data
absent() Labels can only be inferred from the equality matchers in the selector; regex matchers do not appear in the result.up alerts.Point out that or vector(0) loses labels, so be careful when using it in alerts.
"PromQL returns 0 when a metric is empty".
See Lesson 2 Module 2.
Use promtool: check config/check rules for syntax and semantic checks; test rules for unit tests — in test files, use input_series to construct time series, alert_rule_test to assert the alert at a given time and its labels/annotations, and promql_expr_test to assert expression results. For Alertmanager, use amtool check-config and amtool config routes test.
rule_files: [../rules/myapp.yml]
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'myapp_http_requests_total{route="/api",status="500"}'
values: '0+10x15'
- series: 'myapp_http_requests_total{route="/api",status="200"}'
values: '0+90x15'
alert_rule_test:
- eval_time: 12m
alertname: MyappHighErrorRate
exp_alerts:
- exp_labels: {severity: critical, team: shop, route: /api}
promtool test rules tests/myapp_test.yml # success prints SUCCESS; failure prints FAILED with the exp/got difference
${DS_ (#27), Grafonnet/Terraform plan, and API smoke tests on the key queries.Mention the values expansion syntax (0+10x15,_ for missing values,stale).
"Trigger it manually in production and see what happens".
myapp exposes myapp_http_requests_total{method,route,status} and myapp_http_request_duration_seconds. Write the PromQL for the three panels Rate, Errors and Duration, and the two alerts "error rate" and "P99 latency".
sum by (route) (rate(myapp_http_requests_total[$__rate_interval]))
sum by (route) (rate(myapp_http_requests_total{status=~"5.."}[$__rate_interval])) / sum by (route) (rate(myapp_http_requests_total[$__rate_interval]))
histogram_quantile(0.99, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[$__rate_interval])))[5m],for: 5m; the P99 alert adds a request-volume filter to avoid NaN / low-traffic false positives (#18); attach a runbook.absent(myapp_http_requests_total) and up{job="myapp"} == 0.You take over alert governance; what do you do in the first month?
keep_firing_for/longer windows to flapping alerts.Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.
A Helm chart (verified in this lesson as 93.3.0) that packages the Prometheus Operator (v0.95.2) and its CRDs, the Prometheus and Alertmanager instances managed by the Operator, Grafana (subchart, default 13.3.1), kube-state-metrics, node-exporter (DaemonSet), and a full set of Kubernetes-specific ServiceMonitors, PrometheusRules (from kubernetes-mixin) and dashboards.
*SelectorNilUsesHelmValues: true (selects only release: kps, #9); the admin API is disabled.helm upgrade ; for a major upgrade, upgrade the CRDs first as the chart documentation describes.helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --version 93.3.0 -f values-kind.yaml
Mention that the Grafana subchart has moved to the grafana-community repository (OCI).
"kps is just a Helm chart for Prometheus".
See Lesson 5 Module 1.
The Operator watches the CRDs (Prometheus, Alertmanager, ServiceMonitor, PodMonitor, Probe, ScrapeConfig, PrometheusRule, AlertmanagerConfig). For each Prometheus CR, it uses selectors to collect the matching monitoring objects,generates prometheus.yaml (gzipped into a Secret) and rule ConfigMaps, and manages the StatefulSet; the config-reloader sidecar in the Pod detects file changes and calls Prometheus's reload endpoint.
RECONCILED/AVAILABLE).kubectl get prometheus the CR's status conditions, Operator logs, the generated Secret content, config-reloader logs, and the Prometheus /config page.additionalScrapeConfigs or the ScrapeConfig CRD.Mention that the Operator automatically handles the replica label prometheus_replica, sharding shards (hashmod).
"The Operator sends ServiceMonitors directly to Prometheus".
ServiceMonitor: selects backend Pods through a Service (EndpointSlice); the most common; PodMonitor: workloads with no Service (DaemonSet, sidecar, Job); Probe: black-box probing (URLs/Ingress) with blackbox_exporter; ScrapeConfig: static targets, targets outside the cluster, and other SDs (file/HTTP/cloud), replacing additionalScrapeConfigs.
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata: {name: myapp, namespace: myapp, labels: {release: kps}}
spec:
selector: {matchLabels: {app.kubernetes.io/name: myapp}}
podMetricsEndpoints: [{port: http, path: /metrics}]
azmonitoring.coreos.com group's PodMonitor/ServiceMonitor (#34).port It must be the port name; or use targetPort.Mention that sampleLimit,metricRelabelings can be set per application on these objects.
"PodMonitor is an exporter for processes inside a Pod".
cAdvisor (embedded in the kubelet,/metrics/cadvisor): actual container resource usage (container_cpu_usage_seconds_total,container_memory_working_set_bytes); kubelet /metrics: kubelet's own stats and volume stats; kube-state-metrics: generates "desired/status" metrics from API objects (replica counts, Pod phases, restart counts, resource requests/limits); node-exporter: node operating-system metrics; metrics-server: provides only the latest in-memory resource usage for kubectl top and HPA; it is not a Prometheus data source.
# memory usage / limit (container level)
sum by (namespace, pod) (container_memory_working_set_bytes{container!=""})
/ sum by (namespace, pod) (kube_pod_container_resource_limits{resource="memory"})
# CPU throttling
rate(container_cpu_cfs_throttled_periods_total[5m]) / rate(container_cpu_cfs_periods_total[5m])
container=""/POD series are Pod/cgroup aggregates; filter them when aggregating to avoid double counting.kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}.Explain that metrics-server and Prometheus do not replace each other (the K8s lesson already covers HPA).
"kube-state-metrics collects CPU usage".
node (one target per node, kubelet address),service (one per Service port, suited to black-box probing),pod (one per container port),endpoints/endpointslice (each backend behind a Service; the most common for application scraping),ingress (black-box probing). Each role provides __meta_kubernetes_* labels, used with relabeling to filter and label targets.
endpointslice, and watch out for RBAC (#10).namespaces and selectors .kubernetes_sd_configs:
- role: endpointslice
namespaces: {names: [myapp]}
selectors: [{role: endpointslice, label: "app.kubernetes.io/name=myapp"}]
Mention that the Operator's serviceDiscoveryRole can switch between Endpoints and EndpointSlice (check the Operator docs).
"Use role: service to scrape application metrics" (you only get one Service VIP, load-balanced to a random Pod).
See Lesson 7 Module 2.
① the application exposes /metrics (RED metrics, bounded labels); ② name the Service port (name: http); ③ create a ServiceMonitor (with release: kps, or the azmonitoring version for managed services); ④ confirm up on /targets; ⑤ submit recording rules, alerts (PrometheusRule) and dashboards (ConfigMap or Git); ⑥ set sampleLimit and SLOs.
grafana_dashboard: "1" label.up,scrape_samples_scraped, an absent alert, and a dashboard screenshot.Propose "monitoring-ready" as part of the go-live checklist.
"Edit the Prometheus config file directly to add a static target".
See Lesson 5 Module 2.
On AKS, run az aks update --enable-azure-monitor-metrics to deploy the metrics add-on (kube-system in ama-metrics ReplicaSet,ama-metrics-node DaemonSet,ama-metrics-ksm,ama-metrics-operator-targets). It scrapes in Prometheus agent mode / as an OTel Collector and writes to the Azure Monitor workspace via data collection rules (DCR) and endpoints (DCE); queries use a PromQL-compatible API consumed by Azure Managed Grafana or the Azure portal; rules are hosted as Prometheus rule group resources.
ama-metrics-settings-configmap (default targets, minimal ingestion profile #36),ama-metrics-prometheus-config (cluster-level custom scrape configs),ama-metrics-prometheus-config-node,azmonitoring.coreos.com CRDs (#33, #34).MA_<workspace>_<location>_managed resource group (names cannot be changed; watch the Azure Policy naming rules).az aks update -g rg-prom-lab -n aks-prom-lab --enable-azure-monitor-metrics \ --azure-monitor-workspace-resource-id "$AMW" --grafana-resource-id "$AMG"
Know the troubleshooting entry point: the Prometheus agent UI on port 9090 of each ama-metrics Pod.
"Managed Prometheus means Azure installs kps in your cluster for you".
See Lesson 3 Module 2.
Two layers: who can use Grafana— Microsoft Entra ID users/groups are mapped to Grafana roles through Azure RBAC roles Grafana Admin / Editor / Viewer (and Limited Viewer); what data Grafana can read— the Azure roles of the workspace's managed identity (or app registration) on the data resources: platform metrics/logs use Monitoring Reader, and Prometheus data in an Azure Monitor workspace requires Monitoring Data Reader (#35).
Stress that "sign-in identity ≠ data access identity" (Figure 3-1).
"Assigning Monitoring Reader to a user lets them see Prometheus data in Grafana".
See Lesson 3 Module 4.
Collection: the AMP managed collector (agentless, server-side scraping of EKS), ADOT Collector, or self-hosted Prometheus (agent mode) → via SigV4-signed remote write to the AMP workspace (requires aps:RemoteWrite, with credentials from IRSA or EKS Pod Identity). Storage and query: AMP is a Prometheus-compatible managed backend that supports rule groups and a managed Alertmanager (notifying via SNS). Visualization: AMG, where users sign in through IAM Identity Center or SAML , and the workspace uses an IAM role to read from AMP; from Grafana 12 onward, use the AMP-specific plugin instead of Core Prometheus + SigV4 (#37). AMG supports Grafana 9, 10, 12 and 13.
State the format of the remote write endpoint https://aps-workspaces.<region>.amazonaws.com/workspaces/<id>/api/v1/remote_write.
"AMG signs in with an IAM username and password".
See Lesson 4.
Managed: no need to run storage, HA, scaling, upgrades or long-term retention; good integration with cloud identity and networking; pay-as-you-go. The costs are quota limits, feature and version lag, poorer controllability (for example, how scrape config is applied and different CRD groups), cost growing linearly with cardinality, and cloud lock-in. Self-hosted: most flexible and cost-controllable (especially with high cardinality), but the team must be able to operate Thanos/Mimir and similar systems.
| Dimension | Managed (AMW/AMP) | Self-hosted kps + Thanos/Mimir |
|---|---|---|
| Operations | Low | High |
| Cost model | Per sample/series; grows with cardinality | Compute + object storage + people |
| Flexibility | Limited (quotas, configuration entry points) | Fully controllable |
| Multi-cloud | One per cloud | Unified |
| Compliance | Data is in the cloud service | Location is your choice |
rate(prometheus_tsdb_head_samples_appended_total[5m]) and head series multiplied by the price.Do cardinality governance before migrating; otherwise the managed bill exposes every bad instrumentation.
"Managed is always cheaper".
Deploy collection close to each cluster (kps or a Prometheus agent), and use external_labels: {cluster: …} labels to identify the source; the global view has three options: remote write push to a central store (Mimir / AMP / Azure Monitor),Thanos Thanos (sidecar + object storage + global Query),federation (aggregated metrics only). Evaluate alerts as close to the data as possible, and evaluate global alerts centrally.
X-Scope-OrgID to separate tenants (#48).cluster variable.Point out that the cluster label must be named consistently across all clusters, otherwise queries and alert routing become a mess.
"One Prometheus scrapes all Pods across all clusters".
Rules: keep PrometheusRule / rule files in Git and run promtool in CI. Grafana: provisioning files (data sources, dashboards, alerts), the Terraform Grafana provider (suited to managed Grafana and to organizations, folders and permissions), Grafonnet (jsonnet to generate dashboards), and Grafana 13's Git Sync (submit PRs directly from UI changes; check the official docs for feature status). In Kubernetes: dashboard ConfigMaps + sidecar, or the Grafana Operator.
${DS_…} (#27), and a read-only production Grafana (#29).grafana_folder,grafana_dashboard,grafana_data_source,grafana_rule_group,grafana_contact_point (already covered in the Terraform course).resource "grafana_dashboard" "myapp_red" {
folder = grafana_folder.myapp.uid
config_json = file("${path.module}/dashboards/myapp-red.json")
}
Check query cost when reviewing dashboards (#45).
"Periodically backing up grafana.db is versioning".
HPA only uses the Kubernetes metrics API: CPU/memory come from metrics-server (metrics.k8s.io); custom metrics need an adapter that exposes PromQL results as custom.metrics.k8s.io/external.metrics.k8s.io; commonly used are prometheus-adapter or KEDA (the Prometheus scaler, which takes PromQL directly).
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: {name: myapp, namespace: myapp}
spec:
scaleTargetRef: {name: myapp}
minReplicaCount: 2
maxReplicaCount: 10
triggers:
- type: prometheus
metadata:
serverAddress: http://kps-kube-prometheus-stack-prometheus.monitoring:9090
query: sum(rate(myapp_http_requests_total{namespace="myapp"}[2m]))
threshold: "50"
replicas, to avoid conflicts.Scaling by per-replica QPS or queue length is closer to the business than CPU.
"HPA reads Prometheus directly".
See Kubernetes 8 hours(metrics-server and HPA).
Requirements: a global dashboard, per-team isolation, 13 months of retention, and a limited budget.
cluster,team; evaluate alerts close to the data.List the migration checklist.
azmonitoring.coreos.com (#34); ConfigMap scraping (#33).le/ metric-name differences.Give the troubleshooting steps.
Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.
Discovery: /tsdb-status (series counts per metric and per label),prometheus_tsdb_head_series trends,scrape_series_added topk, churn (prometheus_tsdb_head_series_created_total). Control is done in three layers: at the source (instrumentation review, bounded labels, route templates), at collection (metric_relabel_configs drop / labeldrop sample_limit, sample_limit label_limit), and at the remote side (write_relabel_configs/ per-tenant limits in managed services or Mimir).
curl -s localhost:9090/api/v1/status/tsdb | jq '.data.seriesCountByMetricName[:10]'
Give quantitative rules: a single metric with more than 10,000 series needs review; a single target with more than 50,000 samples triggers an alert.
"Adding memory is enough".
See this lesson's #39 · Lesson 7 Module 3.
Two inputs: active series (determine memory) and samples ingested per second (determine CPU and disk). Disk ≈ retention seconds × samples per second × 1–2 bytes + WAL; memory ≈ active series × per-series memory (empirically a few KB, calibrated with process_resident_memory_bytes / prometheus_tsdb_head_series ) + query overhead, then keep 50–100% headroom.
prometheus_tsdb_head_series rate(prometheus_tsdb_head_samples_appended_total[5m]) process_resident_memory_bytes / prometheus_tsdb_head_series
--query.max-samples, and the number of concurrent queries.Turn capacity metrics into a dashboard and predict_linear alert on them.
Estimating by the number of targets rather than by series count.
See Lesson 2 Module 7.
Thanos (v0.42.5): add a sidecar next to an existing Prometheus to upload 2h blocks to object storage; the Store Gateway reads object storage, Query fans out and deduplicates, and the Compactor compacts and downsamples; the Receive component can also accept remote write. Mimir (3.2.5): a horizontally scaled, natively multi-tenant cluster that accepts remote write (distributor, ingester, store-gateway, querier, query-frontend, compactor, etc.); its data also ultimately lives in object storage.
| Thanos (sidecar mode) | Mimir | |
|---|---|---|
| Writes | Prometheus writes locally; the sidecar uploads | remote write push |
| Multi-tenancy | Limited (supported by Receive) | Native (X-Scope-OrgID, per-tenant limits) |
| Invasiveness | Low; adopt gradually | Requires running a distributed system |
| Recent data | queries each Prometheus | ingester |
| Downsampling | Supported | Check the official docs |
Choose based on the organization: many independent Prometheus instances with reachable networks → Thanos; a platform team offering multi-tenant SaaS → Mimir.
"Thanos is the clustered version of Prometheus".
See Lesson 6 Module 3.
Prometheus reads new samples from the WAL and, after write_relabel_configs filtering, puts them into sharded queues; each shard sends batches (max_samples_per_send) as protobuf + snappy requests, and adjusts the number of min_shards.. max_shards (default max 50) according to the backlog; recoverable errors (5xx/429/network) are retried with exponential backoff, while 4xx are dropped.
protobuf_message: io.prometheus.write.v2.Request, reduces bandwidth, carries metadata and created timestamps); check receiver support in the docs.Describe the deduplication approach for HA dual writes (#47).
"remote write reads from TSDB blocks and uploads them" (that is the Thanos sidecar).
See Lesson 6 Module 1.
Federation: the central Prometheus scrapes the /federate of lower layers, suited to rolling up only a few aggregated recording rules (hierarchical monitoring); remote write remote write: push all or part of the raw data to central storage, suited to centralized querying and long-term retention; Thanos sidecar Thanos: data stays at the edge plus object storage and is fanned out at query time; suited to existing large numbers of Prometheus instances that need long-term storage.
honor_labels (#49), scrape timeouts, and duplicated storage of raw data.Draw the data flow of all three.
"Use federation to pull all metrics into the center".
See Lesson 6 Module 1.
SLI: a quantitative measure of user experience (share of good requests, share with latency < 300ms); SLO: the target for an SLI over a time window (99.9% over 30 days); error budget = 1 − SLO (over 30 days, 0.1% bad requests is allowed, about 43 minutes of full unavailability). The budget balances release speed against reliability: with budget to spare, releases can go faster; when it runs out, freeze releases and prioritize stability.
- record: slo:myapp_availability:ratio_rate5m
expr: |
sum(rate(myapp_http_requests_total{status!~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m]))
- record: slo:myapp_latency:ratio_rate5m
expr: |
sum(rate(myapp_http_request_duration_seconds_bucket{le="0.25"}[5m])) / sum(rate(myapp_http_request_duration_seconds_count[5m]))
le="0.25" is safe as written, while le="1" has to be written as le="1.0" (#17).Distinguish SLA (contract, compensation) from SLO (internal target, which should be stricter than the SLA).
"An SLO means keeping CPU below 80%".
burn rate = actual error rate / error budget ratio (1 − SLO). A burn rate of 1 means the budget is exactly exhausted at the end of the window. The Google SRE Workbook recommends: consuming 2% of the budget within 1 hour→ page → burn rate = 0.02 × 30 days / 1 hour = 14.4; consuming 5% within 6 hours → 6; 10% within 3 days → 1 (ticket). Each alert checks both a long window and a short window (1/12 of the long one): the long window ensures significance, and the short window lets the alert clear quickly after recovery.
- alert: MyappErrorBudgetBurnFast
expr: |
(1 - slo:myapp_availability:ratio_rate1h) > (14.4 * 0.001)
and
(1 - slo:myapp_availability:ratio_rate5m) > (14.4 * 0.001)
labels: {severity: critical}
- alert: MyappErrorBudgetBurnSlow
expr: |
(1 - slo:myapp_availability:ratio_rate6h) > (6 * 0.001)
and
(1 - slo:myapp_availability:ratio_rate30m) > (6 * 0.001)
labels: {severity: critical}
Be able to derive the calculation of 14.4, rather than memorizing the number.
"Alert when the error rate > 0.1% lasts 5 minutes".
See Lesson 6 Module 5.
Measure first (query_log_file,stats=all, the Grafana Query inspector), then optimize: reduce the series involved (add exact selectors, avoid bare regexes), precompute with recording rules, shrink the time range or increase the step, avoid expensive subqueries, split large dashboards and lower the refresh rate; at larger scale, use query-frontend sharding and caching (Thanos/Mimir).
{job="myapp", route=~"/api/.*"} is better than {route=~".*api.*"}.topk,count by full-series scans are expensive; /tsdb-status is cheaper.iterations_missed, #45).Establish a "query only recording rules" standard for long-range panels.
"Raise --query.timeout".
See Lesson 7 Module 4.
Collect close to each region/cluster (Prometheus or an agent, HA with two replicas, sharded by function),external_labels with region/cluster; remote write to a central multi-tenant store (Mimir, or a managed service), with tenant = team; alerts in two layers (local infrastructure alerts + central SLO/global alerts); the Alertmanager cluster routes by team; Grafana uses team folders and permissions; monitoring as code; meta-monitoring deployed independently.
Give a phased rollout plan and acceptance metrics (coverage, alert usefulness rate, query P95).
"One giant Prometheus scrapes everything".
Separate the "collection side" from the "query side": check the prometheus_tsdb_head_series and scrape_series_added for a sudden jump before the OOM (a release introduced high cardinality, #39), and the queries running at the same time (query_log_file, Grafana dashboard traffic peaks, a scheduled report). Then stop the bleeding (drop labels / limit queries / temporarily add memory so the WAL replay completes, #40), and finally fix the root cause (fix instrumentation, recording rules, sample_limit, sharding).
/tsdb-status Find the top metrics and labels; compare against release records.prometheus_engine_queries concurrency.--query.max-samples,--query.max-concurrency, per job sample_limit.Mention Prometheus 3's automatic GOMEMLIMIT, and the periodic memory fluctuations during compaction (every 2 hours).
"Just double the memory limit".
See #39, #40 and #45 in this lesson.
Find the first abnormality from left to right along the alert chain (Figure 2-1): are the rules loaded → does the expression return a result during the outage (is the metric gone #22, is the window too short #15, le normalization #17) → is the for period too long, or reset by flapping (#21) → did Prometheus send successfully (#23) → Alertmanager routing / inhibition / silences (did someone leave a silence?) → did the receiver fail (#24). Improvements: absent/up alerts, a Watchdog heartbeat, rule unit tests, notification-failure alerts.
ALERTS{alertname="MyappHighErrorRate"}[1h] # was it pending/firing during the outage?
prometheus_rule_evaluation_failures_total
prometheus_notifications_errors_total
alertmanager_notifications_failed_total
amtool silence query --alertmanager.url=http://alertmanager:9093 amtool config routes test --config.file=alertmanager.yml alertname=MyappHighErrorRate severity=critical
In the post-incident review, produce an "alert coverage test": use promtool to reproduce the input series of this outage.
Changing the Alertmanager config directly without first confirming whether the alert was firing.
See the Module 2 decision tree.
Cost ≈ number of series × sample frequency × retention (managed services bill directly per sample/series). Ranked by return: ① drop metrics nobody uses (compare against dashboard, alert and recording-rule references; tools such as mimirtool analyze or Grafana's unused-metrics analysis, depending on the actual tool) ② govern high-cardinality labels ③ adjust scrape intervals (change non-critical jobs from 15s to 60s) ④ tiered retention and downsampling ⑤ enable the minimal ingestion profile + keep list on managed services (#36) ⑥ show costs by team (showback) to create constraints.
Turn the "unused metrics" analysis into a monthly automated report.
"Just switch to cheaper storage". If the data volume is not governed, costs will climb again whatever the storage.
Filter by keyword (for example deadline,labelset,Grafana,ama-metrics,WAL). Click a number to jump to the details in the corresponding module.
First read the question and recall the answer yourself, then expand to compare with the one-line key point; the detailed answers are in the "Interview question details" of the corresponding module.
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.health!="up") | "\(.labels.job) \(.lastError)"' curl -s localhost:9090/api/v1/targets?state=dropped | jq '.data.droppedTargets | length' promtool check config prometheus.yml curl -s -X POST localhost:9090/-/reload curl -sI http://target:port/metrics | grep -i content-type
up == 0 scrape_duration_seconds > 5 scrape_samples_post_metric_relabeling count_over_time(x[1m]) # number of samples in the window count by (instance) (x) > 1 # check for duplicates before matching prometheus_config_last_reload_successful == 0
promtool check rules rules/*.yml
promtool test rules tests/*.yml
curl -s localhost:9090/api/v1/alerts | jq '.data.alerts[] | {a: .labels.alertname, s: .state}'
curl -s localhost:9090/api/v1/alertmanagers | jq .data
amtool check-config alertmanager.yml
amtool config routes test --config.file=alertmanager.yml severity=critical
amtool silence querycurl -s localhost:9090/api/v1/status/tsdb | jq '.data.headStats' promtool tsdb list /prometheus du -sh /prometheus/wal /prometheus/chunks_head # PromQL prometheus_tsdb_head_series rate(prometheus_tsdb_head_samples_appended_total[5m]) prometheus_remote_storage_highest_timestamp_in_seconds - ignoring(remote_name, url) group_right prometheus_remote_storage_queue_highest_sent_timestamp_seconds
curl -s -u admin:PASS localhost:3000/api/health
curl -s -u admin:PASS localhost:3000/api/datasources | jq -r '.[] | "\(.uid) \(.url)"'
curl -s -u admin:PASS localhost:3000/api/datasources/uid/UID/health
grep -o '"\${DS_[A-Z_]*}"' dashboard.json | sort -u
# Panel menu → Inspect → Querykubectl get pods -n kube-system | grep ama-metrics kubectl logs -n kube-system POD -c config-reader kubectl port-forward -n kube-system POD 9090 kubectl get crd | grep azmonitoring az role assignment list --assignee GRAFANA_MI --all -o table aws iam simulate-principal-policy --policy-source-arn ROLE --action-names aps:RemoteWrite
Each scenario combines several issues from Section A. Write down your first diagnostic command and your judgment first, then expand the answer.
legacy-exporter: received unsupported Content-Type "text/html" and no fallback_scrape_protocol specified for target
slo.yml: sum(rate(myapp_http_request_duration_seconds_bucket{le="1"}[5m])) / …
subquery: max_over_time(rate(myapp_http_requests_total[1m])[1h:1m])
Answer: Three Prometheus 3 incompatible changes stack up: strict Content-Type (#6) → fallback_scrape_protocol; le="1" normalization (#17) → le="1.0", and the SLO alerts go "silently" quiet because the expression is empty (#22); left-open, right-closed makes [1m] subqueries return no data (#15) → widen the window. Improvement: before upgrading, run rule tests with the 3.x promtool and scan for integer le (#50).
Last State: Terminated Reason: OOMKilled
msg="Replaying WAL, this may take a while"
/tsdb-status: the route label has 2.8M values; scrape_series_added{job="orders"} stays above 5000
Answer: The orders service writes raw URLs into the route label (#39); the head grows until it OOMs, and WAL replay OOMs again (#40). Stop the bleeding: add to the orders job metric_relabel_configs a rewrite of the route label, plus sample_limit (#7), temporarily add memory to finish the replay (or move the WAL away after backing it up). Root fix: instrument with route templates; add a head-series alert.
KubeControllerManagerDown, KubeSchedulerDown, etcdInsufficientMembers, TargetDown(kube-proxy) Get "https://172.18.0.2:10257/metrics": dial tcp 172.18.0.2:10257: connect: connection refused $ kubectl -n myapp get servicemonitor myapp --show-labels myapp app.kubernetes.io/name=myapp
Answer: The control-plane components only listen on 127.0.0.1 (#8) → set the kind config to open the address, or turn them off in the values; the ServiceMonitor is missing release: kps (#9) → add the label, and confirm the port name and the Service selector.
$ curl -s localhost:9090/api/v1/alertmanagers | jq '.data.activeAlertmanagers | length' 1 alertmanager log: msg="Notify failed" … err="teams/msteamsv2[0]: notify retry canceled due to unrecoverable error after 1 attempts: unexpected status code 400 …" alertmanager_config_last_reload_successful 0
Answer: The Prometheus → AM link is fine (#23 ruled out); the Teams webhook returns 400 (#24): the URL has expired or the payload template is wrong; in addition, the most recent config reload failed, so the old config is still running (amtool check-config). Fix the webhook and the config; add alertmanager_notifications_failed_total and reload-failure alerts, and add a second receiver for critical alerts.
error="database is locked" Two Pods mount the same PVC: /var/lib/grafana/grafana.db (another panel) Cannot save provisioned dashboard
Answer: SQLite does not support multiple replicas (#31) → PostgreSQL + Grafana Alerting HA peers; session storage is shared through the database; "Cannot save provisioned dashboard" is the designed behavior of provisioning (#29), so change it through the Git flow.
servicemonitor.monitoring.coreos.com/myapp created kube_deployment_spec_strategy_rollingupdate_max_surge → no data Grafana MI role: Monitoring Reader (subscription level)
Answer: The CRD group should be azmonitoring.coreos.com (#34); the minimal ingestion config does not include that KSM metric → keep list (#36); querying the AMW requires Monitoring Data Reader (#35).
server returned HTTP status 403 Forbidden: {"message":"Missing Authentication Token"}
(after the fix) server returned HTTP status 429 Too Many Requests: ingestion rate limit (…) exceeded …
prometheus-0 and prometheus-1 both write to the same workspace, and external_labels only has cluster
Answer: The sigv4 block is missing (#37); the two replicas have no HA deduplication, which doubles the samples and exhausts the quota (#38, #47) → configure the replica external labels and the AMP deduplication scheme; use write_relabel_configs to reduce the volume sent; apply for more quota if needed.
query timed out in expression evaluation exceeded maximum resolution of 11,000 points per timeseries (from a panel with Min interval=1s) rate(prometheus_rule_group_iterations_missed_total[10m]) > 0
Answer: Heavy dashboard queries take CPU, and rule evaluation misses its cycles (#45); one panel's step is too small (#44). Fix: recording rules + long-range panels that only query recording rules, adjust Min interval, limit concurrency and refresh; alert on iterations_missed; use a query frontend at larger scale.
2-minute countdown for each question: answer aloud first (you may write the key points in the text box), then expand the reference answer and self-rate "answered / partial / didn't know". At the end the round score is shown, along with cumulative mastery by module. Self-assessment results are saved in this browser.
| Topic | Conclusions used in this lesson | Sources (accessed 2026-11-15) |
|---|---|---|
| Versions | Prometheus v3.16.0 (2026-11-05), Alertmanager v0.35.0 (2026-11-09), Grafana v13.3.1 (2026-11-10), node_exporter v1.12.1, blackbox_exporter v0.29.1, Prometheus Operator v0.95.2, kps 93.3.0 (2026-11-13), Thanos v0.42.5, Mimir 3.2.5, ADOT Collector v0.51.0, client_python v0.26.0 | Each project's GitHub Releases; kps Chart.yaml/values.yaml (tag kube-prometheus-stack-93.3.0) |
| Prometheus 3 migration | Strict Content-Type, fallback_scrape_protocol, le/quantile normalization, left-open right-closed, regex newline matching, holt_winters rename, AM v1 removal, always_scrape_classic_histograms, remote write HTTP/2 off by default, UTF-8, slog, auto GOMEMLIMIT | Prometheus 3.0 migration guide(v3.16.0 docs/migration.md) |
| Prometheus error messages | server returned HTTP status; received unsupported Content-Type …; sample limit exceeded; label_limit exceeded; body size limit exceeded; target_limit exceeded; Error on ingesting samples with different value but same timestamp; found duplicate series for the match group …; vector cannot contain metrics with the same labelset; query processing would load too many samples into memory; query timed out in expression evaluation; ranges only allowed for vector selectors; unknown function with name; could not parse expression; loading groups failed; error loading rules, previous rule set restored; Error sending alerts; exceeded maximum resolution of 11,000 points; opening storage failed: lock DB directory; corrupted block; Replaying WAL; Encountered WAL read error, attempting repair; compaction failed; Failed to send batch, retrying; scrape timeout greater than scrape interval …; Lifecycle API is not enabled. | prometheus/prometheus v3.16.0 source: scrape/, model/textparse/, promql/, model/rulefmt/, rules/, notifier/, web/, tsdb/, storage/remote/, cmd/prometheus/, config/ |
| 3.16 retention | --storage.tsdb.retention.time/.size marked DEPRECATED; config file recommended storage.tsdb.retention (time/size/percentage) | v3.16.0 cmd/prometheus/main.go, config/config.go |
| Alertmanager | Notify failed / Notify attempt failed, will retry later / notify retry canceled …; undefined receiver … used in route; root route must specify a default receiver | prometheus/alertmanager v0.35.0 notify/retry_stage.go, config/config.go |
| Grafana | Cannot save provisioned dashboard; origin not allowed; Failed to upgrade legacy queries + Datasource ${…} was not found; Dashboard import failed: datasource input …; database is locked (SQLite) | grafana/grafana v13.3.1 source: pkg/services/dashboards/errors.go, pkg/middleware/csrf/csrf.go, public/app/features/… |
| Azure managed Prometheus | ama-metrics Pods and containers, ama-metrics-prometheus-config(-node), prometheus-config key, azmonitoring.coreos.com CRD, minimal ingestion config (v2 schema), limits (511/1023/63), % Utilization metrics, 9090 agent UI | Troubleshoot · CRD · Minimal profile · Enable |
| Azure Managed Grafana | Essential cannot be newly created, full deprecation on 2027-03-31; Standard X1/X2; Monitoring Reader assigned by default, Prometheus data needs Monitoring Data Reader | Overview · Permissions |
| AMP / AMG | 429/400 error examples and three capacity queries; HA deduplication; AMG supports Grafana 9/10/12/13; from Grafana 12 the Core Prometheus plugin removes SigV4 and auto-migrates to the AMP plugin; sign-in via IAM Identity Center or SAML | AMP troubleshooting · AMG versions · AMP data source · AMG auth |
| Mimir | meaning and common causes of err-mimir-max-series-per-user and err-mimir-sample-out-of-order | Mimir runbooks(from the mimir-3.2.5 source) |
| SLO | Multi-window multi-burn-rate (14.4 / 6 / 1) | Google SRE Workbook: Alerting on SLOs |
All videos were checked on 2026-11-15 via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) for title and channel; oEmbed does not return duration or publish date, so these are not listed. Verified: PromLabs “Don't Make These 6 Prometheus Monitoring Mistakes…” (NEMsO1qeI1s), “Understanding Counter Rates and Increases in PromQL…” (7uy_yovtyqw), “Understanding Prometheus Histograms…” (yYbXak-1hew), “Understanding Prometheus Metric Types…” (fhx0ehppMGM); TechWorld with Nana “How Prometheus Monitoring works…” (h4Sl21AKiDg), “Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1” (QoDqxm7ybLc); Anton Putra “Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor…” (HOmdYtsB950), “Thanos (Multi Cluster Prometheus) Tutorial…” (feHSU0BMcco); Anais Urlichs “Full Tutorial: AlertManager Set up and PrometheusRules” (HwB2oWUdoT4); Grafana “Grafana Dashboard Debugging and Performance” (rY2iLs1Modo), “Introducing Grafana Mimir” (ej9y3KILV8g); Azure Kubernetes Service (AKS) “AKS Labs: Observability with Managed Prometheus and Managed Grafana” (A1Ue-IEpoiA); Houssem Dellai “Azure Managed Prometheus and Grafana for AKS monitoring” (sGWtz_kkKX8); Amazon Web Services “Introduction to Amazon Managed Service for Prometheus…” (lcLZlQpISaw), “Integrating Amazon Managed Service for Prometheus with Amazon Managed Grafana…” (mRVEu8wwfnY); Prometheus Monitoring “PromCon 2018: Bomb Squad…” (MHiXP5QW4_U), “PromCon EU 2019: Containing Your Cardinality” (49BGvC1coG4); USENIX “SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB” (LOZQFT8Dcq0), “LISA18 - SLO Burn…” (idkopV6LR5U); Nobl9 “SLOconf 2023 - How I learned to stop worrying and love burn rates…” (ra0cCmEVKS8). Most of these videos are based on Prometheus 2.x or older Grafana; version differences are resolved in favor of this lesson. For topics with no verified video (Prometheus 3 Content-Type and sample_limit, alert-chain troubleshooting, Grafana provisioning and reverse-proxy errors, remote write backlog), storyboard scripts are provided.
The "Audio" tab uses the browser's built-in Web Speech API and uploads no data. It needs an English (en-US) voice pack installed on the system; without one, read the script directly.
time=… level=… source=… file names and line numbers in logs), multi-layer error wrapping, and parts that come from the Go networking libraries / crypto/tls, client-go, the Kubernetes API, Azure and AWS and change between versions are marked in the entries as "example" or "exact wording may differ".myapp_redis_up to 0 when Redis is unavailable, the /metrics implementation, dashboard file names, the Grafana admin password) follow lessons 1 and 2.info(),promql-extended-range-selectors, and Remote-Write 2.0; the full Mimir error messages; the exact RBAC subresources needed for kubelet scraping; the MIME type python http.server returns for files without an extension, and its status-code classification for POST.process_resident_memory_bytes / prometheus_tsdb_head_series the real values from your environment.