Prometheus & Grafana Hour 9 (optional): 50 production issues + 50 interview questions

Train the first seven lessons into two skills: when you see a target down, an alert that did not fire, a panel showing No data, or a Prometheus OOM, know which command to run first; in an interview, explain in two minutes one scrape, one alert, and what happens to one sample
A: 50 production issuesB: 50 interview questionsPrometheus 3.16 · Alertmanager 0.35 · Grafana 13Verified 2026-11-15
Overall learning goals
  • Given an error message or a symptom, be able to tell which scraping and collection, PromQL/rules/alerts, Grafana and managed cloud services, storage/cardinality/performance/architecture layer it belongs to, and state the first diagnostic command.
  • Understand the mechanism behind each issue: the scrape loop (service discovery → relabel → HTTP GET → Content-Type negotiation → parse → limit checks → append to head/WAL),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.
  • In the ~/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.
  • Be able to answer 50 Prometheus/Grafana interview questions using the structure "30-second answer → principle → code/PromQL → production experience", and handle common follow-ups.
  • Use mock interviews (timed + self-assessment) to measure your mastery rate and find weak modules.

One-hour time allocation

#TimeModuleCore contentAnimations · interactiveLab
0Pre-courseUsage guide and fault lab environmentReuse ~/promlab (Compose) and kind lab + kps; create ~/promlab/lab8 the fault overlay filesEnvironment self-checkStart the fakeexp / cardgen two fault containers
100–08A · Collection, scraping and exportersIssues 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 samplesScrape loop fault simulatorCompose: timeout · Content-Type · sample_limit; kind: ServiceMonitor labels
208–16A · PromQL, rules and alertsIssues 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 treematching errors · le="5.0" · pending→firing · amtool
316–24A · Grafana, managed cloud servicesIssues 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 treedata source · import · provisioning · Azure diagnostic commands
424–30A · Storage, cardinality, performance and architectureIssues 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 pitfallsCardinality and memory estimatorcardgen cardinality explosion · 11,000 points · directory lock · remote write backlog
530–37B · Core concepts and architectureInterview 1–13Mock interview2 scenario questions
637–44B · PromQL and alert designInterview 14–25Mock interview2 scenario questions
744–52B · Kubernetes and cloud monitoringInterview 26–38Mock interview3 scenario questions
852–60B · Scale, SLO and scenario designInterview 39–50Mock interview3 scenario questions
—Post-courseCheat sheet · Comprehensive drill50 "error → first command → fix" entries; 50 recall cards; 8 mixed faults; full mock interviewFull mock interviewFinal quiz, 12 questions

Knowledge coverage matrix

Topicm1m2m3m4m5m6m7m8
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—●—●●●●●

Not covered in this course (where to learn)

  • Prometheus basics, metric types, first dashboard → Lesson 1; recording rules, alerting rules, Alertmanager routing → Lesson 2.
  • Full AKS + Azure Monitor managed Prometheus + Azure Managed Grafana setup → Lesson 3; EKS + AMP + AMG → Lesson 4.
  • kube-prometheus-stack, monitoring as code, promtool testing, blackbox → Lesson 5; HA, Thanos/Mimir, SLO → Lesson 6; troubleshooting methodology and TSDB internals → Lesson 7.
  • Kubernetes' own faults (Pod CrashLoopBackOff, scheduling, networking) → Kubernetes 8 hours Lesson 9; Helm chart install/upgrade errors → Helm Lesson 8. This lesson covers only problems that appear "through the monitoring system".
  • Troubleshooting logs (Loki) and tracing (Tempo/Jaeger) → refer to the official grafana.com documentation; not covered in this course.

How to use this lesson

When troubleshooting (section A)
  • Open the overview of the relevant module, and paste the most distinctive words from the error (for example deadline,Content-Type,many-to-many,DS_PROMETHEUS or 429) into the filter box.
  • Click a table row to jump straight to issue details, and follow "diagnose → compare with output → fix".
  • Not sure which layer it is in? Use the Animation tab's simulator or decision tree.
Before the interview (section B)
  • First read the overview, and pick out the questions you are unsure of by difficulty.
  • Mock interview: random question selection, a 2-minute countdown, answer first and check afterwards, self-rate "answered / partial / don't know"; results are saved in this browser.
  • Answer structure: one-sentence conclusion → principle → PromQL/config → pitfalls you have hit.
Post-course
  • Cheat sheet Suitable for printing and pinning up at your desk.
  • Comprehensive drill: 8 mixed faults + full mock interview (10 out of 50) + final quiz.
  • Every issue links back to the matching section of lessons 1–7, so you can go back and review.

Structure of A / B entries

Section A · 50 production issues

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".

Section B · 50 interview questions

Question → 30-second answer → in-depth answer (principles, code) → common follow-ups → bonus points → common wrong answers. Difficulty:BeginnerIntermediateAdvanced.

Relationship to the previous seven lessons

LessonMost-referenced content in this lesson
Lesson 1 core fundamentalspull model, metric types, scrape config and exporters, myapp instrumentation, rate and aggregation, histogram_quantile, Grafana data sources and variables
Lesson 2 alerting and production readinessrecording rule naming, alerting rule for/labels, Alertmanager routing/grouping/inhibition/silences, notification channels, Grafana Alerting, storage and retention
Lesson 3 Azure · Lesson 4 AWSama-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 codekps, ServiceMonitor/PodMonitor/PrometheusRule selectors, provisioning, Terraform/Grafonnet, promtool test rules, blackbox
Lesson 6 monitoring architecture in practiceHA replicas and the Alertmanager cluster, Thanos/Mimir, multi-cluster multi-tenancy, burn rate, OpenTelemetry
Lesson 7 deep troubleshootingscrape failure investigation, cardinality, slow queries, head/WAL/compaction, alerts not firing or alert storms, Grafana troubleshooting
Version notes This lesson is based on Prometheus 3.x (latest v3.16.0, 2026-11-05),Alertmanager v0.35.0 (2026-11-09),node_exporter v1.12.1,blackbox_exporter v0.29.1,kube-prometheus-stack 93.3.0 (2026-11-13, Prometheus Operator v0.95.2, default Prometheus v3.16.0; the Grafana subchart has moved to 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).

Module 0 · Usage guide and fault lab environment

Pre-course · reuse ~/promlab from lessons 1–2 and the kind cluster lab from lessons 5–7; every fault is injected through a separate file and reverted when you finish
Pre-course, 10–15 minLocal, freeOptional cloud lab, has cost
Learning goals
  • Confirm ~/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.
  • Prepare two "bad exporters": fakeexp (static metrics without the correct Content-Type) and cardgen (to generate high cardinality).
  • Confirm the kind cluster lab has the kps (kube-prometheus-stack) available, for Operator-related issues.

I. Prerequisites

ItemRequirementFrom
Docker Engine + Compose v2docker compose version HealthyDocker lesson
~/promlabservices prometheus (9090),alertmanager (9093),grafana (3000),node-exporter (9100),myapp (5000),redis,redis-exporter (9121)Lesson 1 setup,Lesson 2 extension
myapp metricsmyapp_http_requests_total{method,route,status},myapp_http_request_duration_seconds (buckets 0.005…5),myapp_redis_upLesson 1 Module 3
kind cluster labkps installed on monitoring, with myapp in myapp namespaceLesson 5
Toolscurl,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

II. Self-check of the local environment

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: …)
No reload?/-/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.

III. Fault overlay files (~/promlab/lab8)

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.

IV. Restore rules

# 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

V. Kubernetes environment (Operator labs in modules 1 and 3)

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.

VI. Cost and security

  • Local labs are free. cardgen This makes the local Prometheus memory grow by hundreds of MB within a few minutes; stop and clean up immediately afterwards (module 4).
  • Cloud labs (#33–#38 in module 3) only run while you still keep the resources from lessons 3 and 4. Managed Prometheus is billed per ingested sample and per query, Managed Grafana Standard per instance-hour, and AMG per active user. Check the official pricing pages for prices. When finished, delete the resource group / workspace using the cleanup steps in lessons 3 and 4.
  • Do not put real webhook URLs, Bearer tokens or AWS access keys into the lab files; the keys in the examples are all placeholders.

VII. Self-check checklist

Module 1 · Section A: collection, scraping and exporters (issues 1–12)

00:00 – 08:00 · Twelve ways up=0 happens: network, timeouts, paths, authentication, certificates, Content-Type, limits, control plane, Operator selectors, RBAC, multi-process, duplicate samples
8 min/targets · up · scrape_*12 issues
Learning goals
  • Explain the order of one scrape: service discovery produces targets → 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_*.
  • Given the /api/v1/targets of lastError, you can map it directly to one of the steps above and state the fix.
  • Distinguish "target not present at all" (service discovery / relabel / Operator selector / RBAC) from "target present but up=0" (network / HTTP / parsing / limits).

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".

Universal first stepcurl -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 .
#1 Get "http://myapp:5000/metrics": dial tcp 172.18.0.6:5000: connect: connection refused
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.

Diagnostic command
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)
Fix
# 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"]
Prevention and best practices
  • Services inside containers should always bind 0.0.0.0; health checks and /metrics use the same port, or document it clearly.
  • Create an up == 0 alert for every job (for 5m), and use absent(up{job="myapp"}) (#22) for "the whole job disappeared".
  • In Kubernetes the same applies: a Service's 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.

#2 Get "http://myapp:5000/metrics": context deadline exceeded
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.

Diagnostic command
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
Fix
  • Long-term fix: make the exporter avoid slow operations on the scrape path (periodic background collection, cached results); reduce /metrics size (drop high-cardinality labels, see #39).
  • Temporary: set scrape_interval: 60s + scrape_timeout: 50s, rather than raising the limit globally.
  • Enable compression: Prometheus sends by default 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"]}]
Prevention and best practices
  • Alert: 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).
  • For a custom exporter, follow the principle "read memory only at scrape time"; for slow collection use prometheus_client custom Collector + cache.

See Lesson 7 Module 2 scrape failures: targets down, timeouts and service discovery.

#3 server returned HTTP status 404 Not Found
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).

Diagnostic command
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
Fix
  - 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__
Prevention and best practices
  • In an Operator, explicitly declare the endpoints[].path in ServiceMonitor, instead of relying on the annotation convention.
  • Upgrade myapp to a version with /metrics , and the myapp:1.1 in CI for curl -f /metrics smoke tests.

See Lesson 1 Module 3.

#4 server returned HTTP status 401 Unauthorized (or 403 Forbidden)
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).

Diagnostic command
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
Fix
# 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"]
Prevention and best practices
  • With kps / the Operator, RBAC is generated by the chart; do not delete the ClusterRole by hand. For self-hosted setups, keep the RBAC and the config in the same Git directory.
  • For basic auth / OAuth2 on application endpoints, use the 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.

#5 tls: failed to verify certificate: x509: certificate signed by unknown authority
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).

Diagnostic command
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
Fix
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
Prevention and best practices
  • insecure_skip_verify: true Use only as a temporary measure, and flag it in red during code review.
  • Add the Service DNS names to the certificates, and set server_name in the scrape config.

See Lesson 7 Module 2.

#6 received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target
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.

Diagnostic command
docker compose exec prometheus wget -S -qO /dev/null http://fakeexp:8000/metrics 2>&1 | grep -i content-type
  Content-Type: application/octet-stream
Fix
  - 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).

Prevention and best practices
  • Before upgrading to Prometheus 3, use 2.x's /api/v1/targets to list all targets, and check each one's curl -sI Content-Type.
  • Use the official client libraries for in-house exporters; do not hand-write HTTP responses.

See Lesson 1 Module 3 · migration covered in #50.

#7 sample limit exceeded / label_limit exceeded / body size limit exceeded
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.

Diagnostic command
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
Fix
  • Short term: once you confirm it is "unexpected high cardinality", use metric_relabel_configs to drop the metric or label, so the target recovers first; do not simply raise the limit.
  • Long term: fix the instrumentation (use a route template for route /api/orders/<id>, see #39).
    sample_limit: 20000
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: myapp_debug_.*
        action: drop
Prevention and best practices
  • Set 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".
  • In CI, run a line-count check on /metrics (for example, fail if > 5000 lines).

See Lesson 7 Module 3 Cardinality explosion: label design and limits.

#8 On kind/kubeadm, the targets for kube-controller-manager, kube-scheduler, etcd and kube-proxy are all DOWN (connection refused)
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.

Diagnostic command
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: ""
Fix
# 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}
Prevention and best practices
  • Maintain one kps values override file per cluster type (kind, AKS, EKS); on managed clusters, always turn off control-plane scraping.
  • When opening 0.0.0.0 to listen, use a NetworkPolicy/firewall to restrict access to the monitoring namespace only.

See Lesson 5 Module 1.

#9 A ServiceMonitor was created, but the target does not appear in Prometheus at all (no error)
$ 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":

  1. Prometheus CR's serviceMonitorSelector: kps defaults to serviceMonitorSelectorNilUsesHelmValues: true, which only selects ServiceMonitors carrying the release: kps label.
  2. Prometheus CR's serviceMonitorNamespaceSelector: whether the namespace where the ServiceMonitor lives is selected.
  3. The ServiceMonitor's selector.matchLabels must match the labels of Service (not the Pod's),namespaceSelector must include the namespace where the Service lives.
  4. 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).
Diagnostic command
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.

Fix
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
Prevention and best practices
  • In the application chart's ServiceMonitor template, make the extra labels into values (serviceMonitor.labels), and have the platform team document release: kps.
  • Always name Service ports (name: http), and use port: http in ServiceMonitor.
  • Use kubectl get servicemonitor -A -l '!release' to find "orphans" periodically.

See Lesson 5 Module 2 ServiceMonitor, PodMonitor and PrometheusRule.

#10 failed to list *v1.EndpointSlice: endpointslices.discovery.k8s.io is forbidden: User "system:serviceaccount:monitoring:prometheus" cannot list resource …
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.

Diagnostic command
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
Fix
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"]
Prevention and best practices
  • Alert on prometheus_sd_kubernetes_failures_total (use the actual metric name) or on forbidden messages in the logs.
  • Multi-tenant clusters should let the monitoring SA read only the resources SD needs; nodes/proxy and similar high-privilege permissions are granted only as needed.

See Lesson 7 Module 2 · Lesson 5 Module 1.

#11 myapp_http_requests_total jumps back and forth, and rate() shows huge spikes (gunicorn multi-worker)
$ 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.

Diagnostic command
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"
Fix (consistent with the myapp convention in Lesson 1)
# 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"]
Prevention and best practices
  • In multi-process mode, gauges need to specify multiprocess_mode (e.g. livesum,max); myapp_redis_up use max.
  • The directory must be emptied on every startup, otherwise data from old processes will be aggregated again.
  • Alert on resets() abnormal increases, which can also reveal frequent application restarts.

See Lesson 1 Module 3, Module 8 myapp observability readiness.

#12 msg="Error on ingesting samples with different value but same timestamp" num_dropped=…
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.

Diagnostic command
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
Fix
  • Fix the exporter output (deduplicate textfile files; a custom exporter must not register two Collectors with the same name).
  • Remove the duplicate scrape job, or make sure the instance is unique after relabeling.
  • When the exporter's timestamps are unreliable, set honor_timestamps: false.
Prevention and best practices
  • Alert on rate(prometheus_target_scrapes_sample_duplicate_timestamp_total[5m]) > 0,rate(prometheus_target_scrapes_sample_out_of_order_total[5m]) > 0.
  • The same error shows up on remote write receivers (AMP, Mimir) as out of order / duplicate sample; see #38 and #48.

See Lesson 7 Module 5 TSDB internals.

The seven steps of one scrape, with the typical failure at each step (issue numbers) ① Service discoverystatic / k8s / file ② relabelkeep / drop / rewrite address ③ HTTP GETTCP · TLS · authentication ④ Status code and type200? Content-Type? ⑤ Parse+ metric relabel ⑥ Limit checkssample/label/body ⑦ Appendhead + WAL · up=1 Target does not appear (no error)#9 ServiceMonitor selector#10 SD RBAC forbiddenrelabel dropped it (/service-discovery) up=0, lastError shows a network/HTTP error#1 refused · #2 deadline · #8 127.0.0.1#4 401/403 · #5 x509#3 404 · #6 Content-Type up=0, tripped by a protective mechanism#7 sample_limit / label_limitbody_size_limit · parse errorall samples of the scrape discarded up=1 but the data is wrong#11 multi-process#12 duplicate samples#39 cardinality After each scrape, Prometheus writes these for the target: up, scrape_duration_seconds, scrape_samples_scraped, scrape_samples_post_metric_relabeling, scrape_series_addedTroubleshooting order: /service-discovery (was it dropped?) → lastError on /targets → scrape_* metrics → Prometheus log (WARN-level ingest errors)For Operator setups, add one more step up front: ServiceMonitor → the generated prometheus.yaml.gz Secret → whether config-reloader reloaded successfully
Figure 1-1: first decide whether the target appears at all, then check lastError, and finally check data quality
The four selection checks for a ServiceMonitor (#9): a mismatch at any one of them fails silently Prometheus CRserviceMonitorSelectorrelease: kps+ NamespaceSelector ServiceMonitorlabels: release=kps ①selector.matchLabels ③endpoints.port: http ④ Service (myapp ns)labels: app=myappports: - name: httpport: 5000 EndpointSlicePod IP:5000→ targetrequires RBAC (#10) ② namespaceSelector: the namespace where the ServiceMonitor lives is selected by Prometheus, and the ServiceMonitor's namespaceSelector includes the namespace where the Service lives
Figure 1-2: when a target does not appear in the Operator setup, check items ① → ④ one by one

Scrape loop fault simulator

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).

Pick a fault first, then run the scrape.
$ curl -s localhost:9090/api/v1/targets | jq '.data.activeTargets[0] | {health,lastError}'
Environment Module 0's ~/promlab (including fakeexp) and the kind cluster lab. At the end of each experiment, run the "restore rules".

Lab 1-A: cause a scrape timeout (#2)

Set an impossible timeout on the myapp job:
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/-/reload
Wait 20 seconds, then check:
sleep 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
Comparison: 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.

Restore: cp lab8/prometheus.yml.orig prometheus/prometheus.yml && curl -s -X POST localhost:9090/-/reload

Lab 1-B: Prometheus 3 strict Content-Type checking (#6)

cat >> 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.

Add the fallback protocol:
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
Restore the config and hot-reload.

Lab 1-C: sample_limit circuit breaker (#7)

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
Use metric relabeling to keep only the metrics you need, bringing the sample count below the limit:
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: node_(cpu_seconds_total|memory_MemAvailable_bytes|filesystem_avail_bytes)
        action: keep

Note: sample_limit the limit check looks at the samples counted after relabeling, so this approach lets the target recover to up.

Restore the config and hot-reload.

Lab 1-D: ServiceMonitor missing the release label (#9, kind)

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
Cleanup: kubectl -n myapp delete servicemonitor myapp-lab8

Video lesson (title and channel verified via YouTube oEmbed)

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
English · a Prometheus co-founder on common mistakes (labels and cardinality for #7 and #39, alert design)
▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · pull model and a review of targets and exporters
▶
Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step — Anton Putra
English · ServiceMonitor selectors and port names (for #9)

No 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:

Shot 1 (0:00) Split screen: on the left, the /targets page; on the right, the terminal curl … | jq .lastError. Introduce the seven-step diagram.
Shot 2 (0:40) Start fakeexp; Prometheus 3 reports received unsupported Content-Type; wget -S shows octet-stream; after adding fallback_scrape_protocol it turns green.
Shot 3 (1:40) Set sample_limit: 50 on node-exporter, the target turns red; emphasize "the whole scrape is discarded"; restore with a metric_relabel keep.
Shot 4 (2:30) Summary: target not present → SD / relabel / selector; up=0 → lastError; up=1 but odd data → multi-process / duplicate samples / cardinality.

Official docs

or score 70% or more on the quiz

Module 2 · Section A: PromQL, rules and alerts (issues 13–25)

08:00 – 16:00 · query errors, queries that fail silently, rule loading, alerts that do not fire, Alertmanager that cannot send or sends too much
8 minpromtool · amtool · ALERTS13 issues
Learning goals
  • Distinguish the three kinds of PromQL problems: parse errors (fail for any data),execution errors (many-to-many, same labelset, too many samples; depend on the data),silent errors (return empty or wrong values; the most dangerous).
  • Trace the alert chain: does the expression return a result → for does it hold for the whole for period → can Prometheus send the alert to Alertmanager → Alertmanager routing / inhibition / silences → did the receiver succeed.
  • Know the two ways the Prometheus 3 upgrade can silently break PromQL: 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.

#13 found duplicate series for the match group {…} on the right hand-side of the operation: […];many-to-many matching not allowed: matching labels must be unique on one side
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.

Diagnostic command
count by (instance) (myapp_redis_up) > 1          # find which groups on the "one" side have duplicates
Fix
# 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)
Prevention and best practices
  • The "one" side of a join should always be first 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.
  • Prometheus 3 provides an experimental 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.

#14 vector cannot contain metrics with the same labelset
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.

Diagnostic command
count by (job, instance) ({__name__=~"myapp_http_requests_total|myapp_jobs_total"})
Fix
# 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".

Prevention and best practices
  • Avoid regex matching on the metric name in panels and alerts; __name__ write explicit queries or recording rules per metric name.

See Lesson 1 Module 4 PromQL basics.

#15 rate(myapp_http_requests_total[1m]) is intermittent / No data in Grafana (more noticeable after upgrading to Prometheus 3)
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.

Diagnostic command
count_over_time(myapp_http_requests_total[1m])     # how many samples the window actually contains
prometheus_target_interval_length_seconds{quantile="0.99"}
Fix
  • Rule of thumb: rate window ≥ 4 × scrape interval (15s interval → [1m]; 1m interval → [4m] or [5m]).
  • In Grafana, use $__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).
  • Subquery: foo[1m:1m] change to foo[2m:1m] or a similar window that covers at least two points.
Prevention and best practices
  • Use a unified [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.

#16 parse error: ranges only allowed for vector selectors
{"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.

Fix
# 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)
Prevention and best practices
  • Code review rule: rate(sum( and increase(sum( should always be sent back.
  • A similar parse error is unknown function with name "holt_winters" (renamed in Prometheus 3, see #50).

See Lesson 1 Module 4.

#17 After upgrading to Prometheus 3, SLO alerts and panels based on le="0.5" / le="1" silently stop working
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.

Diagnostic command
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
Fix
  • Recommended: change the references to le="1.0" or le="5.0"; queries across the upgrade point are briefly inaccurate, which is acceptable.
  • Transition: use the official metric_relabel_configs to convert the normalized values back to integers (only for the affected metrics).
  • Root fix: switch to histogram_quantile() or the native histogram's histogram_fraction(), rather than referencing bucket boundary strings directly.
Prevention and best practices
  • Before upgrading, run a le="[0-9]+" scan over the rules and dashboard repositories; run the promtool unit tests on 3.x.
  • For every SLO alert, configure meta-monitoring for "expression returns empty" (#22).

See Lesson 1 Module 5 · migration covered in #50.

#18 histogram_quantile() returns NaN, +Inf or an obviously unreasonable P99
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:

  • NaN: no requests in the window for that series (all bucket rates are 0, so 0/0). Low-traffic routes are very common; this is not a bug.
  • Aggregation dropped 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).
  • +Inf / equal to the largest bucket: more than 99% of requests fall above the last finite bucket (myapp's buckets go up to 5s), so the quantile can only be estimated up to the bucket boundary.
  • Linear interpolation within a bucket: precision is limited by how the buckets are laid out; 0.5–1 boundaries can only be interpolated between.
Diagnostic command
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]))
Fix
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
Prevention and best practices
  • Cover the area around the SLO threshold with buckets (e.g. for a 300ms SLO, have 0.25, 0.3, 0.5); the timeout upper bound needs a bucket too.
  • Consider native histograms (since Prometheus 3.9 the feature flag is a no-op; use scrape_native_histograms to enable scraping) for higher precision, provided the client library and downstream storage both support them.

See Lesson 1 Modules 2 and 5.

#19 query processing would load too many samples into memory in query execution
{"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.

Diagnostic command
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'
Fix
  • Build recording rules (for example namespace:container_cpu_usage_seconds:sum_rate5m), so panels query the recording rules instead of the raw metric.
  • Add selector filters to reduce series; in Grafana, increase the panel's Min interval setting.
  • When long-range large queries are truly needed, use Thanos/Mimir (downsampling, query sharding) instead of blindly raising --query.max-samples.
Prevention and best practices
  • Dashboard standard: panels covering more than 7 days may only query recording rules.
  • Monitor 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.

#20 loading groups failed … could not parse expression … / error loading rules, previous rule set restored
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.

Diagnostic command
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
Fix

Correct by line/column number → promtool check rules passes → reload → confirm prometheus_config_last_reload_successful == 1.

Prevention and best practices
  • Run in CI promtool check config,promtool check rules,promtool test rules (Lesson 5 Module 6).
  • Alert: 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.

#21 An alert stays PENDING on the /alerts page and never reaches FIRING
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.

Diagnostic command
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
Fix
  • Smooth the expression: a longer rate window ([10m]), or apply avg_over_time(...[10m:1m]) before the threshold comparison.
  • Reasonable for: usually 2–10 minutes; for "sustained for 1 hour" semantics, use a longer window rather than a longer for.
  • To prevent flapping between "just fired" and "resolved": keep_firing_for: 5m (supported since Prometheus 2.42).
Prevention and best practices
  • For SLO alerts, multi-window multi-burn-rate (Q45) is more stable and faster than "threshold + long for".
  • After a Prometheus restart, pending/firing state is restored via 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.

#22 The exporter died or a metric was renamed, and the related alerts all "recover" — No data is not 0
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.

Diagnostic command
up{job="redis"}                       # is the exporter itself reachable?
absent(redis_up)                      # has the metric disappeared completely?
count(myapp_http_requests_total) or vector(0)
Fix
- 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)"}
Prevention and best practices
  • Every critical job should have an up == 0 and a absent(up{job="…"}) alert; key business metrics should have an absent() alert.
  • Treat metric renames as breaking changes: dual-write first, and remove the old metric only after the alerts and panels have been migrated.
  • The equivalent in Grafana Alerting is the No Data handling policy (#32).

See Lesson 2 Module 8 production-readiness review and common mistakes.

#23 msg="Error sending alerts" … dial tcp: lookup alertmanager … no such host (or context deadline exceeded)
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.

Diagnostic command
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
Fix
alerting:
  alertmanagers:
    - api_version: v2          # v2 is the default; delete the v1 config
      static_configs:
        - targets: ["alertmanager:9093"]
Prevention and best practices
  • Alerts: prometheus_notifications_alertmanagers_discovered < 1,rate(prometheus_notifications_errors_total[5m]) > 0 (kps ships with PrometheusNotConnectedToAlertmanagers,PrometheusErrorSendingAlertsToAnyAlertmanager).
  • Watchdog/Deadman alert: an always-firing alert sent to an external "dead man's switch" service; if it stops arriving, the whole chain is broken (Q23).

See Lesson 2 Module 3 Alertmanager.

#24 msg="Notify failed" … notify retry canceled … unexpected status code 400 (and undefined receiver "…" used in route)
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).

Diagnostic command
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
Fix
  • Config problems: correct the receiver name → amtool check-config → reload.
  • Integration problems: use curl to call the webhook directly and reproduce the 4xx cause; update the URL/credentials (put them in a *_file referenced Secret).
  • Routing problems: amtool config routes test --config.file=… severity=critical team=shop confirm which receiver the alert is routed to.
Prevention and best practices
  • Alerts: 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.
  • Run amtool check-config and routing tests on alertmanager.yml in CI.

See Lesson 2 Modules 3 and 4 notification channels.

#25 Alert storms and duplicate notifications: one incident sends hundreds of messages, and with HA each alert arrives twice
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:

  • Grouping is too fine:: group_by includes pod,instance and other highly variable labels (or group_by: ['...'] groups by all labels), so each series gets its own notification.
  • HA is not clustered:: the two Alertmanagers do not gossip with each other via --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).
  • Inhibition does not work: the inhibit_rules equal labels on the source and target alerts do not match.
  • Flapping: see #21, missing keep_firing_for.
Diagnostic command
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
Fix
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).

Prevention and best practices
  • Monitor the alert volume itself: count(ALERTS{alertstate="firing"}),alertmanager_notifications_total rate.
  • Alert on symptoms (what users can feel); send cause-type signals to dashboards (Q22).

See Lesson 2 Module 3 · Lesson 6 Module 2 high availability · Lesson 7 Module 6 alerts not firing or alert storms.

From expression to phone: the typical failure in each stage rule loadingpromtool check rules#20 expression evaluationevery evaluation_interval#13–#19 · #22 empty vector pending → firingfor / keep_firing_for#21 send to AM/api/v2/alerts#23 Alertmanagerrouting · grouping · inhibition · silences#24 #25 where the "evidence" for each stage lives prometheus_config_last_reload_successful/api/v1/rules execute the expression in the Graphrule_evaluation_failureslastError on /rules ALERTS{alertstate}ALERTS_FOR_STATEthe /alerts page /api/v1/alertmanagersnotifications_errors_totallog: Error sending alerts amtool alert querynotifications_failed_totalamtool config routes test Rule: troubleshoot from left to right, and stop at the first stage whose "evidence" looks wrong; do not start by changing the Alertmanager config "Not received" caused by silences and inhibition shows as suppressed in the Alertmanager UI
Figure 2-1 the five stages of the alert chain and their evidence
The three kinds of PromQL problems Parse errors (independent of data)ranges only allowed for vector selectorsunknown function with name …unexpected right parenthesis→ promtool / CI catches 100% of them Execution errors (depend on data)many-to-many matching not allowedvector … same labelsettoo many samples · timed out→ unit tests must construct "bad data" Silent errors (the most dangerous)Window too short → empty (#15)le="1" → empty (#17) · NaN (#18)Metric disappears → alert resolved (#22)→ absent() + meta-monitoring
Figure 2-2 the further right, the harder to spot

Interactive troubleshooting decision tree: "alert not received / query result wrong"

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.

Environment Module 0's ~/promlab. Use for i in $(seq 200); do curl -s localhost:5000/ >/dev/null; done first to generate some request data.

Lab 2-A: many-to-many (#13)

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 side

You 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).

Fix: first aggregate one side to the matching labels:
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

Lab 2-B: le label normalization (#17)

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"
done
le="5" -> 0 series
le="5.0" -> 4 series
Scan the rules repository: grep -rnE 'le="[0-9]+"' prometheus/rules/, changing each one to float notation, then promtool check rules.

Lab 2-C: pending → firing and absent() (#21, #22)

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 ---; done
Lab8RedisDown 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.

Restore: docker compose start redis redis-exporter; rm prometheus/rules/lab8.yml; curl -s -X POST localhost:9090/-/reload

Lab 2-D: Alertmanager config validation and routing tests (#24)

sed -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
After restoring, run the routing test:
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

Video lesson (title and channel verified via YouTube oEmbed)

▶
Understanding Counter Rates and Increases in PromQL | Reset Handling, Extrapolation, Edge Cases — Prometheus Monitoring with Julius | PromLabs
English · rate windows, resets and extrapolation (for #15 and #16)
▶
Understanding Prometheus Histograms | Motivation and Concepts, Instrumentation, Querying in PromQL — Prometheus Monitoring with Julius | PromLabs
English · histogram_quantile and le (for #17 and #18)
▶
Full Tutorial: AlertManager Set up and PrometheusRules — Anais Urlichs
English · hands-on Alertmanager and PrometheusRule (for #20–#25)

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:

Shot 1 (0:00) Show the five stages of Figure 2-1, emphasizing "find the first abnormal evidence from left to right".
Shot 2 (0:45) Stop redis-exporter: value-type alerts resolve,absent() alerts fire; compare the two.
Shot 3 (1:40) Set the Alertmanager address wrong and show /api/v1/alertmanagers empty and the log Error sending alerts.
Shot 4 (2:30) amtool check-config and amtool config routes test, wrap-up.

Official docs

or score ≥ 70% on the quiz

Module 3 · Section A: Grafana, managed cloud services (issues 26–38)

16:00 – 24:00 · Grafana data sources / import / provisioning / reverse proxy / HA / Alerting; Azure managed Prometheus and Managed Grafana; AMP and AMG with SigV4, quotas
8 minQuery inspector · ama-metrics · SigV413 issues
Learning goals
  • Remember that the Grafana data source defaults to server-side proxy (access: proxy): the URL is resolved from the perspective of the Grafana process/container, not from the browser.
  • Use Query inspector,/api/datasources/uid/<uid>/health and the Grafana logs to locate "panel has no data".
  • Explain the data and identity flows of managed services: on AKS, 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.

#26 Post "http://localhost:9090/api/v1/query": dial tcp [::1]:9090: connect: connection refused (Grafana data source Save & test fails)
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).

Diagnostic command
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"}
Fix
# 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)
Prevention and best practices
  • Manage data sources with provisioning and pin them uid, and have dashboard JSON reference the uid rather than the name.
  • Do not use Browser (direct) mode: it exposes queries to the browser and is subject to CORS restrictions, and it is no longer recommended in newer versions.

See Lesson 1 Module 6 Grafana architecture: data sources, dashboards and panels.

#27 Failed to upgrade legacy queries Datasource ${DS_PROMETHEUS} was not found
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.

Diagnostic command
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"}]
Fix
# 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)
Prevention and best practices
  • Team dashboards stored in Git use the "not externally shared" format, referencing a fixed uid for each data source; use __inputs only for dashboards shared externally.
  • In CI, grep for \${DS_, and fail if it is found.

See Lesson 5 Module 4 Grafana provisioning.

#28 Panel shows No data, but the same PromQL returns results in Prometheus
Grafana panel: No data
Prometheus Graph: sum(rate(myapp_http_requests_total{route=~"/api/.*"}[5m])) → has values

Root causes (by frequency):

  1. Variable expansion: a multi-select or All variable in =~"$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 =~.
  2. Window too short: when the panel time range is long, $__interval is very large, or when it is short, [$__interval] is less than 2 scrape intervals (#15); use $__rate_interval.
  3. Wrong data source: the panel is bound to another data source (common when importing or copying panels), or the ${datasource} variable's current value is wrong.
  4. Time zone / time range: the data is in the future or the past (container clock skew, remote write delay).
  5. Instant vs Range: a table panel uses a Range query or vice versa, or a Transform filters the data out.
Diagnostic command

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?
Fix
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)
Prevention and best practices
  • Data source timeInterval matches the real scrape_interval; use $__rate_interval consistently.
  • Add "Query inspector screenshot" to the dashboard review checklist.

See Lesson 1 Module 7 variables and the RED method · Lesson 7 Module 7 Grafana troubleshooting.

#29 Cannot save provisioned dashboard
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.

Diagnostic command
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"}
Fix
  • Correct workflow: edit in the UI → Export → JSON (do not tick externally shared) → commit to Git's grafana/dashboards/ → deploy.
  • In the development environment you can set allowUiUpdates: true for convenient debugging, but remember that "the file is still authoritative".
  • Grafana 13 provides Git Sync (check the official docs for its feature status), which lets you submit a PR directly from the UI.
apiVersion: 1
providers:
  - name: myapp
    folder: myapp
    type: file
    allowUiUpdates: false
    updateIntervalSeconds: 30
    options: {path: /var/lib/grafana/dashboards, foldersFromFilesStructure: true}
Prevention and best practices
  • In production Grafana, ordinary users only get Viewer; edits are made in the development instance.
  • The dashboard JSON's uid is fixed,id set to null, to avoid multi-instance conflicts.

See Lesson 5 Modules 4 and 5.

#30 origin not allowed (403 when logging in or saving behind a reverse proxy)
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.

Diagnostic command
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
Fix
[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).

Prevention and best practices
  • Set it uniformly in kps values via grafana.grafana.ini.server.root_url ; review the Ingress together with root_url.

See Lesson 7 Module 7.

#31 database is locked (multiple Grafana replicas sharing SQLite), and duplicate Grafana alert notifications under HA
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.

Fix
[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
Prevention and best practices
  • A single replica with SQLite is only for labs; in production with multiple replicas use PostgreSQL/MySQL and configure HA peers for Grafana Alerting.
  • Or use Azure Managed Grafana / AMG / Grafana Cloud directly and leave HA to the service provider.

See Lesson 6 Module 7 Grafana at scale.

#32 Grafana Alerting suddenly generated many DatasourceNoData / DatasourceError alerts overnight
[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.

Diagnostic command

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
Fix
  • Explicitly set the No data and Error handling for each rule: for rules where "no data is good news" (e.g. error counts), set it to Normal/OK; for rules that "must have data", keep the NoData alert but route it to a lower priority.
  • Cover data-source-level problems with one "data source health" alert, instead of letting 100 rules each raise their own alert.
Prevention and best practices
  • Define each kind of alert in only one place (Prometheus rules / Alertmanager, or Grafana Alerting) to avoid duplicates.
  • Manage Grafana Alerting rules with Terraform/provisioning, and check the No data/Error policy during review.

See Lesson 2 Module 5 Grafana Alerting and unified alerting.

#33 AKS managed Prometheus: custom scrape jobs do not take effect (ama-metrics-prometheus-config has a wrong name or key)
$ 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.

Diagnostic command (from the official troubleshooting steps)
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
Fix
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.

Prevention and best practices
  • Prefer the PodMonitor/ServiceMonitor CRDs (note the API group, see #34); use the ConfigMap only for config that CRDs cannot express.
  • Managed Prometheus has its own limits: label names ≤ 511 characters, label values ≤ 1023 characters, and ≤ 63 labels per series; exceeding them causes the whole job's scrape to fail (up=0).

See Lesson 3 Module 3 scrape config: ConfigMap, PodMonitor and ServiceMonitor.

#34 AKS managed Prometheus: a monitoring.coreos.com ServiceMonitor was applied, but there are no targets at all
$ 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.

Diagnostic command
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
Fix
apiVersion: azmonitoring.coreos.com/v1
kind: ServiceMonitor
metadata: {name: myapp, namespace: myapp}
spec:
  selector: {matchLabels: {app: myapp}}
  endpoints: [{port: http, path: /metrics, interval: 30s}]
Prevention and best practices
  • In the application chart, make the ServiceMonitor's apiVersion into values (one for self-hosted kps and one for the managed service).
  • Note that the managed service does not have kps's release: kps selector logic — you do not need that label.

See Lesson 3 Module 3.

#35 Azure Managed Grafana querying the Azure Monitor workspace returns 403 / no permission
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.

Diagnostic command
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/…
Fix
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)
Prevention and best practices
  • Use IaC (Terraform/Bicep) to create Grafana, the workspace and the role assignments together, scoped as narrowly as the AMW resource.
  • The Essential tier can no longer be created, and existing instances are scheduled for full deprecation on 2027-03-31; always create new ones as Standard (X1/X2).

See Lesson 3 Module 4 Azure Managed Grafana: identity, permissions and data sources.

#36 AKS managed Prometheus: some kube-state-metrics / cAdvisor metrics cannot be found (minimal ingestion config)
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.

Diagnostic command
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
Fix

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
Prevention and best practices
  • Before migrating a self-hosted kps to the managed service, export the list of metric names used by existing dashboards and alerts, and compare it against the keep list.
  • Watch the cost: turning off the minimal config can significantly increase ingestion volume.

See Lesson 3 Module 2 and Module 8 cost.

#37 AMP: server returned HTTP status 403 Forbidden (remote write unsigned / role lacks aps:RemoteWrite); after AMG was upgraded to 12, the SigV4 data source stops working
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.

Diagnostic command
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
Fix
# 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}
Prevention and best practices
  • Prefer the AMP managed collector (scraper): no need to run Prometheus inside the cluster, and permissions are created by the service; but it requires the correct EKS access configuration (see lesson 4 and the official docs).
  • Minimise IAM policies: the write role gets only aps:RemoteWrite, and the Grafana role gets only query-type permissions.

See Lesson 4 Modules 2, 3 and 4.

#38 server returned HTTP status 429 Too Many Requests: ingestion rate limit (…) exceeded / per-user series limit … exceeded (managed service quota)
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).

Diagnostic command
# 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
Fix
  • First stop the bleeding: on the sending side, use write_relabel_configs to drop the spiking metrics/labels (this only affects the remote side; local data is kept).
  • Once you confirm it is normal growth, request a higher quota via Service Quotas (AWS) or a support request (Azure, including the workspace ID, internal ID and region).
remote_write:
  - url: …
    write_relabel_configs:
      - source_labels: [__name__]
        regex: "apiserver_request_duration_seconds_bucket|etcd_.*"
        action: drop
Prevention and best practices
  • Alert on quota utilization (AMP provides CloudWatch usage metrics; Azure workspaces provide the % Utilization metrics).
  • When two HA replicas write to the same workspace, configure deduplication (AMP uses the 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.

Data and identity flows of the managed service (where issues 33–38 occur) Azure AKS · ama-metricsConfigMap #33 · CRD #34minimal ingestion #36 DCR / DCEmanaged identity writesprivate cluster restrictions Azure Monitorworkspace amw-prom-labquota #38 Managed GrafanaMI + MonitoringData Reader #35 AWS EKS · Prometheus/ADOTor the AMP managed collectorIRSA / Pod Identity SigV4 remote writeaps:RemoteWrite403 #37 AMP workspace429 / 400 #38rules + Alertmanager AMGIAM Identity CenterAMP plugin (12+) #37 Blue arrows = write path (collection identity); grey arrows = query path (Grafana identity). Check the permissions of the two paths separately. The identity used to sign in to Grafana (Entra ID / Identity Center) ≠ the identity Grafana uses to read data (managed identity / IAM role)
Figure 3-1 writes and queries are two independent identity chains
One Grafana panel query (which step issues 26–28 occur at) BrowserOrigin check #30 variable interpolation$route · $__rate_interval #28 data source resolutionuid · ${DS_…} #27 Grafana backend proxyaccess the URL from the container's perspective #26 Inspect → Query shows the requests actually sent after steps 2–4; the health API only verifies step 4
Figure 3-2 check the real request in Query inspector first

Interactive troubleshooting decision tree: "panel has no data / metrics not visible in the cloud"

Choose step by step based on the symptom to reach the conclusion and the matching issue numbers.

Environment~/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.

Lab 3-A: the data source uses localhost (#26)

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.

Restore: cp lab8/ds.yml.orig grafana/provisioning/datasources/prometheus.yml && docker compose restart grafana, then health returns OK.

Lab 3-B: ${DS_PROMETHEUS} placeholder (#27)

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 .status
success

Open localhost:3000/d/lab8-shared, and the panels report that the data source cannot be found (the error wording varies by version).

After fixing, re-submit:
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 .status
Cleanup: curl -s -u admin:admin -X DELETE localhost:3000/api/dashboards/uid/lab8-shared

Lab 3-C: Cannot save provisioned dashboard (#29)

ls 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
Correct approach: edit grafana/dashboards/myapp-red.json → wait updateIntervalSeconds or restart Grafana → the version number increases.

Lab 3-D (optional, cloud): AKS managed Prometheus diagnostic checklist (#33–#36)

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
When finished, follow the cleanup steps in lesson 3 (az group delete -n rg-prom-lab --yes --no-wait deletes all lab resources).

Video lesson (title and channel verified via YouTube oEmbed)

▶
Grafana Dashboard Debugging and Performance — Grafana
English · the official channel on dashboard debugging and query checks (for #28)
▶
AKS Labs: Observability with Managed Prometheus and Managed Grafana — Azure Kubernetes Service (AKS)
English · AKS managed Prometheus and Managed Grafana (for #33–#36)
▶
Azure Managed Prometheus and Grafana for AKS monitoring — Houssem Dellai
English · enabling workflow and ConfigMap
▶
Integrating Amazon Managed Service for Prometheus with Amazon Managed Grafana | Amazon Web Services — Amazon Web Services
English · AMP + AMG (for #37); early videos use SigV4 + the Core Prometheus plugin; from Grafana 12 onward, follow the AWS docs

Storyboard (no verified video specifically covering Grafana reverse-proxy / provisioning errors was found):

Shot 1 (0:00) Change the data source URL to localhost, health fails; inside the Grafana container, wget the service name succeeds — "the URL is resolved from Grafana's perspective".
Shot 2 (1:00) Import ${DS_PROMETHEUS} a dashboard, demonstrating the difference between UI Import and provisioning.
Shot 3 (2:00) Managed service diagram 3-1: troubleshoot the write identity and the query identity separately,az role assignment list and aws iam simulate-principal-policy.

Official docs

or score 70% or more on the quiz

Module 4 · Section A: storage, cardinality, performance and architecture (issues 39–50)

24:00 – 30:00 · cardinality explosion, OOM and WAL replay, disk, directory lock, block corruption, 11,000 points, slow queries, remote write backlog, HA deduplication, Mimir limits, federation, Prometheus 3 upgrade
6 min/tsdb-status · head series · WAL12 issues
Learning goals
  • Attribute memory, disk and query-performance problems all to active series × time", and use /tsdb-status and prometheus_tsdb_* metrics to find the culprit label.
  • Understand the lifecycle of the TSDB head (memory, roughly the last 2–3 hours) → WAL (crash recovery) → 2h blocks (disk) → compaction → retention, and the typical failures of each.
  • Know the data problems each of multiple replicas, remote write, Thanos/Mimir and federation introduces (duplicates, out-of-order samples, backlog, label conflicts).

Filter by keywords (for example series,OOM,lock,11,000,retrying,exported_,holt) to filter; click a row to jump.

#39 Cardinality explosion: prometheus_tsdb_head_series grows from 300k to 3M within an hour
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……

Diagnostic command
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}, …]}
Fix
  • Stop the bleeding: for this job, add metric_relabel_configs (labeldrop to drop unbounded labels, or drop to drop the whole metric), and set sample_limit (#7).
  • Root-cause fix: fix the instrumentation: in Flask, use 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>
Prevention and best practices
  • Alerts: 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.
  • Instrumentation review checklist: is every label's set of values bounded? (Rule of thumb: fewer than 10,000 series per metric.)

See Lesson 7 Module 3 Cardinality explosion: label design and limits.

#40 Prometheus restart loop after OOMKilled: msg="Replaying WAL, this may take a while", then killed again
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.

Diagnostic command
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
Fix (ordered from lowest to highest cost)
  1. First stop the source: drop the high-cardinality metrics in the config (#39), and temporarily raise the memory limit so WAL replay can finish; after replay, later compactions gradually release the head.
  2. If you cannot add more memory in the short term and can accept losing roughly the last 2 hours of data: stop Prometheus,back it up, then move away wal/ (along with chunks_head/) directories, then restart.
  3. Operator setup: change the Prometheus CR's resources, and the Operator rolls the StatefulSet.
Prevention and best practices
  • Set memory limits in capacity planning as "active series × per-series memory (a few KB, empirically) × 2 for headroom"; use process_resident_memory_bytes / prometheus_tsdb_head_series to calculate the actual value for your environment.
  • Limit queries: --query.max-samples,--query.timeout,--query.max-concurrency; Grafana slow queries should go through recording rules (#45).
  • On every job, set 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.

#41 no space left on device: disk full, compaction and WAL writes fail
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.

Diagnostic command
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
Fix
  • Expand the PVC (if the StorageClass supports allowVolumeExpansion , change the size directly).
  • Also set size-based retention. In Prometheus 3.16, --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
Prevention and best practices
  • Alerts: the disk is predicted to fill within 24 hours (kubelet_volume_stats or node_filesystem), and prometheus_tsdb_compactions_failed_total growth (kps ships with KubePersistentVolumeFillingUp and similar rules).
  • Hand long-term data to Thanos/Mimir/a managed service; keep only 1–2 weeks locally.

See Lesson 2 Module 7 storage, retention and resource planning.

#42 opening storage failed: lock DB directory: resource temporarily unavailable
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.

Diagnostic command
docker ps --filter volume=$(docker volume ls -q | grep -i prom | head -1) --format '{{.Names}}'
kubectl -n monitoring get pods -o wide | grep prometheus
Fix
  • Make sure only one process uses the directory at a time: use a StatefulSet (each replica gets its own PVC), or a Deployment with strategy: Recreate.
  • The correct way to do HA is to run two independent Prometheus instances, each writing to its own volume, with deduplication on the query side (#47).
  • --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.
Prevention and best practices
  • Do not put the TSDB on network file systems such as NFS/SMB (the official docs explicitly do not support non-POSIX-compliant file systems).

See Lesson 6 Module 2 high availability.

#43 opening storage failed: … corrupted block / WAL corruption (after power loss or node failure)
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.

Diagnostic command
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…
Fix
  1. Stop Prometheus,back up the whole data directory.
  2. Move the failing block directory out of the data directory (you only lose the data that block covers, roughly 2 hours to a few days), then start it again.
  3. If you have a Thanos/object-storage copy or another HA replica, you can query this data from there.
Prevention and best practices
  • Use block storage with write-cache protection; do not use kubectl delete pod --force --grace-period=0 to delete Prometheus's data.
  • HA with two replicas plus long-term storage turns the corruption of a single replica into a tolerable event.

See Lesson 7 Module 5.

#44 exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)
{"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.

Fix
  • Scripts: step ≥ (end − start) / 11000, e.g. for 7 days use at least step=60.
  • Grafana: do not set the panel Min interval too small; let Grafana calculate it from the panel width $__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.

#45 query timed out in expression evaluation: the dashboard takes 30 seconds to open, and Prometheus CPU spikes
{"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.

Diagnostic command
# 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])
Fix
  • Change the heavy queries on the dashboard to recording rules (following the Lesson 2 naming convention level:metric:operations).
  • Grafana: set the panel Min interval ≥ the scrape interval, turn off unnecessary auto-refresh, use query caching (an enterprise/cloud feature; check actual availability), and split large dashboards.
  • At larger scale: query sharding and results caching in Thanos Query Frontend / Mimir.
Prevention and best practices
  • Alerts: rule group evaluation time approaches the interval,iterations_missed growth (kps ships with PrometheusRuleFailures and PrometheusMissingRuleEvaluations).
  • Dashboard code review: ban bare regexes, and ban querying raw metrics directly over ranges longer than 7 days (#19).

See Lesson 7 Module 4 query performance.

#46 msg="Failed to send batch, retrying": remote write backlog, remote data delayed by hours
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.

Diagnostic command
# 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])
Fix
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
Prevention and best practices
  • Alerts: seconds behind > 120 (kps ships with PrometheusRemoteWriteBehind) and samples_failed_total growth.
  • In Prometheus 3, remote write no longer uses HTTP/2 by default (per the migration guide), so multiple shards use multiple TCP connections; when traffic goes through a proxy or gateway, check the connection limits.
  • The Remote-Write 2.0 protocol (protobuf_message: io.prometheus.write.v2.Request) reduces bandwidth but requires receiver support; check the official docs for current status.

See Lesson 6 Modules 1 and 3.

#47 After two HA replicas are connected to Thanos/Grafana, all sum() results double
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.

Diagnostic command
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'
Fix
# 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=…"]
Prevention and best practices
  • In Grafana, confirm that "deduplication" is enabled for the Thanos data source; for AMP/Mimir, confirm the HA deduplication config (AMP docs: use external labels to implement HA deduplication).
  • Acceptance test: 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.

#48 Mimir: err-mimir-max-series-per-user / err-mimir-sample-out-of-order causes missing data
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:

  • max-series-per-user: the number of series in this tenant's memory exceeds -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.
  • sample-out-of-order: common causes listed in the runbook: the same target exposes duplicate series, several targets have identical labels, the Prometheus clock moves backwards,several Prometheus instances push the same metrics but the HA tracker is not configured correctly, series conflict after relabeling, Prometheus and Mimir run the same recording rules; replaying the WAL after a restart re-sends some data, which is normal.
Diagnostic command
# 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]))
Fix
  • Series limit: reduce cardinality first; only if the growth is genuinely normal, raise the limit for this tenant through the runtime config.
  • Out-of-order: configure the HA tracker (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.
Prevention and best practices
  • The platform team gives each tenant a "quota utilization" dashboard and alerts, and explains the limits during onboarding.

See Lesson 6 Modules 3 and 4, multi-cluster and multi-tenancy.

#49 After federation (/federate), exported_job / exported_instance labels appear, and aggregations and alerts no longer match
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.

Fix
  - 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"]
Prevention and best practices
  • Use federation only for hierarchical rollup of aggregated metrics; for a full global view, use Thanos/Mimir/remote write (Q43).
  • Set the upstream Prometheus 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.

#50 On the day of the upgrade to Prometheus 3: field scrape_classic_histograms not found, unknown function with name "holt_winters", Alertmanager v1, regex matching newlines
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):

ChangeSymptomAction
scrape_classic_histograms Renamed to always_scrape_classic_histogramsConfig load failureRenamed
holt_winters Renamed to double_exponential_smoothing, and requires --enable-feature=promql-experimental-functionsRule load failureRenamed + 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-Typeold exporters DOWN (#6)fallback_scrape_protocol
le/quantile Values normalized to floating pointrules/panels silently empty (#17)change to le="1.0"
Range selectors and lookback are left-open, right-closedshort-window rate and subqueries become empty (#15)widen the window
In regexes, . match newlinesrelabel/matchers now also match values containing \n valuesuse this when the old behavior is needed: [^\n]
remote write no longer uses HTTP/2 by defaultmore connectionsif needed, enable_http2: true
UTF-8 metric and label names are allowed by defaultmetric names may changemetric_name_validation_scheme: legacy keep the old behavior
The log format changes to log/slog (time=… level=INFO source=…)Log parsing / alert rules breakUpdate 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 rewrittenUse $$ escaping
Diagnostic command
# 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/
Prevention and best practices
  • First upgrade to the latest 2.55.x to clear the deprecation warnings, then upgrade to 3.x; upgrade HA replicas one at a time and compare query results.
  • A major kps upgrade also brings a major Prometheus version change, so read the chart's UPGRADE notes and CRD changes before upgrading.

See Lesson 7 Module 8, mixed fault blind box · official Prometheus 3.0 migration guide.

The life of one sample (TSDB) and the typical failures at each stage Scrape / rulesnew series → index#39 cardinality Head (memory)last ~2–3h · mmap chunks#40 OOM WALcrash recovery · #40 replay · #43 repair 2h Blockindex + chunks + meta#43 corrupted block Compactionmerged into a larger block#41 disk-full failure Retentiontime / sizeold blocks deleted remote write reads from the WAL and sends#46 backlog · #38 429 · #47 duplicates · #48 out-of-order The whole data directory is protected by a lock file: only one process can use the same directory (#42)Query path: head + blocks → PromQL engine (#19 too many samples · #44 11,000 points · #45 timeout)
Figure 4-1: look at the head for memory issues, at block/compaction/retention for disk issues, and at WAL reads for remote issues

Cardinality and memory estimator

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 .

Series count for a single metric
0
Head series for all metrics (× number of metrics)
0
Estimated head memory
0
Environment~/promlab. Lab 4-A will make local Prometheus memory grow, so clean up immediately afterwards.

Lab 4-A: create and stop a cardinality explosion (#39)

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]'; done
14873
26911
38804        ← about +12000 per minute (200 new user_ids per second × a scrape every 15 seconds)
Locate:
curl -s localhost:9090/api/v1/status/tsdb | jq -r '.data.labelValueCountByLabelName[:3][] | "\(.name) \(.value)"'
user_id 36120
__name__ 912
le 15
Stop the bleeding: drop the unbounded label (this also merges the counter into one series, which is exactly what we want)
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.

Cleanup: docker compose -f compose.yaml -f lab8/compose.lab8.yml --profile card rm -sf cardgen, restore prometheus.yml and hot-reload.

Lab 4-B: the 11,000-point limit (#44)

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 // "")"'
done
step=1 error exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)
step=60 success

Lab 4-C: data directory lock (#42)

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.

Lab 4-D: remote write backlog (#46)

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]'
Cleanup: restore prometheus.yml and hot-reload (remove the remote_write section).

Video lesson (title and channel verified via YouTube oEmbed)

▶
PromCon 2018: Bomb Squad: Containing the Cardinality Explosion — Prometheus Monitoring
English · finding and controlling cardinality explosions (for #39)
▶
PromCon EU 2019: Containing Your Cardinality — Prometheus Monitoring
English · label design and limits
▶
SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB — USENIX
English · head, WAL, block, compaction (for #40–#43)
▶
Thanos (Multi Cluster Prometheus) Tutorial: Global View - Long Term Storage - Kubernetes — Anton Putra
English · Thanos deployment and deduplication (for #47)

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):

Shot 1 (0:00) Figure 4-1: remote write reads from the WAL; when it falls behind, the WAL cannot be truncated.
Shot 2 (0:50) Configure a broken remote_write, and show the logs and the "seconds behind" query growing continuously.
Shot 3 (1:50) Explain the three parameters shards, max_samples_per_send and capacity, and write_relabel_configs.

Official docs

or score 70% or more on the quiz

Module 5 · Section B: core concepts and architecture (interview 1–13)

30:00 – 37:00 · pull model, metric types, architecture components, data model, scrape cycle, relabel, Pushgateway, exporter, TSDB, HA, division of responsibilities, Prometheus 3, OpenTelemetry
7 minpull · TSDB · labels13 questions
Learning goals
  • Explain Prometheus's architecture in one minute: service discovery → scrape → local TSDB → PromQL → rules → Alertmanager → Grafana.
  • Be able to draw one scrape and the lifecycle of one sample in the TSDB on a whiteboard, and name the key config at each step.
  • Be able to answer advanced follow-ups: why pull, why Pushgateway is not recommended, why HA means "two independent replicas", and what Prometheus 3 changed.

Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.

Q1. What is Prometheus? Why use the pull model?Beginner
30-second answer

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.

In-depth answer
  • pull vs push: with pull, service discovery decides which targets should exist, so a disappearing target is noticed (up=0 / absent); under push, "no data received" cannot tell you whether all is fine or the source is down. Pull also stops clients from overwhelming the monitoring system (the server controls the scrape frequency).
  • Cases where pull does not fit: short-lived batch jobs (Pushgateway, Q7), targets behind NAT or firewalls (remote write, agent mode, or OTLP push), and event/log-type data (which is not metrics).
  • Prometheus itself also supports the push direction: 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"]}]
Common follow-ups
  • Is Prometheus suitable for storing logs or billing data? No: it is designed for numeric metrics, tolerates a small amount of data loss, and does not guarantee 100% accuracy.
  • How does the pull model monitor thousands of targets? Service discovery (Kubernetes / cloud / Consul / file_sd), combined with sharding (Q47).
Bonus points

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.

Common wrong answers

"Pull is always better than push" — the trade-off should be explained according to the scenario.

See Lesson 1 Module 1.

Q2. The four metric types: what are the differences between counter, gauge, histogram and summary, and how do you choose?Beginner
30-second answer

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.

In-depth answer
HistogramSummary
Where quantiles are computedServer side (at query time)Client side
AggregatableYes (sum by le)No (averaging quantiles is meaningless)
AccuracyLimited by bucket layoutConfigurable error
CostOne series per bucketOne 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")
Common follow-ups
  • What is a native histogram? One series holds the full distribution with exponential buckets: high precision, few series. Prometheus 3.8 added the 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).
  • Can a counter decrease? No; a decrease is treated as a reset (#11).
Bonus points

Point out the naming convention: a counter ends with _total , and the unit goes in the name (_seconds,_bytes), using base units.

Common wrong answers

"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.

Q3. Draw the architecture of the Prometheus ecosystem and explain the responsibilities of each component.Beginner
30-second answer

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.

In-depth answer
  • Inside Prometheus: discovery manager → scrape manager → storage (head + WAL + blocks) → rule manager → notifier; queries read from storage through the PromQL engine.
  • Alertmanager is a separate process; multiple instances can gossip to form a cluster (Q10).
  • Grafana does not store metrics (Q11); it only sends queries to data sources.
  • Agent mode (--agent): only scraping + remote write, with no local queries or rules; suited to edge sites or many clusters pushing data to a central place.
Common follow-ups
  • Can Prometheus be clustered? The core does not do distributed storage; horizontal scaling relies on functional sharding plus federation / remote write / Thanos / Mimir.
Bonus points

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.

Common wrong answers

Calling Grafana a "monitoring system", or believing Alertmanager computes the alert conditions (the computation happens in the Prometheus rules).

See Lesson 1 Module 1.

Q4. Explain Prometheus's data model and "cardinality".Beginner
30-second answer

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.

In-depth answer
  • A metric name is essentially a __name__ label; Prometheus 3 allows UTF-8 metric/label names (queries use the {"my.metric", …} quoted syntax).
  • target labels job,instance are attached by the scrape; external_labels are attached only when interacting with external systems (remote write, federation, alerts).
  • Cardinality estimate: 3 methods × 20 routes × 5 status codes × 10 Pods = 3000 series; a histogram multiplies that by the number of buckets (12) = 36000.
Common follow-ups
  • Which labels must not be used? Unbounded values: user IDs, order numbers, raw URLs, timestamps, error messages (#39).
  • How do you check the current cardinality?/tsdb-status,prometheus_tsdb_head_series.
Bonus points

Mention that churn (series constantly being created and removed) also has a cost, for example when Pod names change on every release.

Common wrong answers

"The more labels the better, for easier querying".

See Lesson 1 Module 2 · Lesson 7 Module 3.

Q5. What is the full process of one scrape? Where can it fail?Intermediate
30-second answer

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.

In-depth answer
  • For failure points and error messages, see Module 1 Figure 1-1: network (refused/timeout/x509), HTTP (401/404), Content-Type (strict in Prometheus 3), limits (sample_limit discards the whole scrape), append (duplicate/out-of-order samples).
  • Scrape times are jittered / offset (spread out by target hash), so that not all targets are scraped at the same moment.
  • When a target disappears, or a series is no longer present in a scrape, Prometheus writes stale marker, and queries stop returning that series immediately instead of waiting for the 5-minute lookback.
up == 0
scrape_duration_seconds > 5
scrape_samples_post_metric_relabeling > 10000
Common follow-ups
  • How do you debug relabeling? Compare discovered and target labels on the /service-discovery page; use promtool or an online relabeler tool.
Bonus points

Mention the X-Prometheus-Scrape-Timeout-Seconds request header and the staleness mechanism.

Common wrong answers

"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.

Q6. What is the difference between relabel_configs and metric_relabel_configs? Common uses?Intermediate
30-second answer

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).

In-depth answer
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
  • action: replace (default),keep,drop,keepequal/dropequal,hashmod (sharding),labelmap,labeldrop,labelkeep,lowercase/uppercase.
  • Regexes are fully anchored (automatically wrapped with ^…$); in Prometheus 3, . also match newlines.
  • Labels starting with __ are deleted after relabeling (__address__,__metrics_path__,__scheme__,__param_* are used to control scraping).
Common follow-ups
  • Do data dropped by metric_relabel still consume resources? Yes, they still use scrape and parse CPU/network but never enter the TSDB; the best approach is to not expose them at the source.
Bonus points

Give an example of using hashmod for scrape sharding; mention sample_limit is checked after metric relabel (#7).

Common wrong answers

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.

Q7. When is Pushgateway used? Why is it often misused?Intermediate
30-second answer

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.

In-depth answer
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
  • Scraping Pushgateway must use honor_labels: true, otherwise the pushed job/instance is renamed to exported_* (#49).
  • Alert example: time() - backup_last_success_timestamp_seconds > 26*3600.
  • Pushed series never expire; after a job is renamed or retired, DELETE must be done manually.
Common follow-ups
  • Alternatives? node_exporter's textfile collector (the job writes a .prom file), OTLP push to a supported backend, or exposing /metrics while the job runs.
Bonus points

Point out that for monitoring batch jobs the most important thing is the last successful time, not in-job process metrics.

Common wrong answers

"Use Pushgateway for every service behind a firewall" — use agent mode + remote write instead.

See Lesson 1 Module 3.

Q8. What is an exporter? How do you design a good custom exporter?Beginner
30-second answer

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).

In-depth answer
  • Implementation: a custom Collector from the official client library (reads at every collect() scrape), rather than looping in the background to set set() gauges.
  • Slow collection: follow the X-Prometheus-Scrape-Timeout-Seconds rule, or collect in the background, cache the results, and expose the collection timestamp.
  • Multi-target pattern (blackbox, snmp_exporter): Prometheus uses relabeling to put the target into __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}
Common follow-ups
  • What is the difference between an exporter and direct instrumentation? If you can change the code, instrument directly (the metrics are closer to the business); use an exporter for systems you cannot modify.
Bonus points

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).

Common wrong answers

"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.

Q9. Explain the Prometheus TSDB: head block, WAL, block, compaction, retention.Advanced
30-second answer

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.

In-depth answer
  • Compression: timestamps use delta-of-delta, values use XOR (Gorilla), about 1–2 bytes per sample.
  • Inverted index: label → postings list (series IDs), intersected at query time; high-cardinality labels make the index larger.
  • Deletion: /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: out_of_order_time_window accepts out-of-order samples within a window, written to a separate OOO head and WBL.
  • In 3.16, the retention period is recommended to be set in the config file storage.tsdb.retention (time/size/percentage); the old command-line flags are marked DEPRECATED.
Common follow-ups
  • Why does Prometheus not recommend NFS? It needs POSIX file locks and mmap semantics; network file systems can cause corruption (#42, #43).
  • How do you estimate disk? Retention in seconds × ingested samples per second × bytes per sample (1–2).
Bonus points

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).

Common wrong answers

"Prometheus writes to disk once per sample", or "retention deletes individual samples".

See Lesson 7 Module 5.

Q10. How do you make Prometheus and Alertmanager highly available?Intermediate
30-second answer

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.

In-depth answer
  • Why storage cannot be shared: the TSDB directory is locked (#42), and shared storage is itself a single point of failure.
  • The data of the two replicas differs slightly (different scrape times); Thanos deduplication chooses data based on replica priority and time gaps.
  • An Alertmanager cluster is an AP system: during a network partition, notifications may be duplicated (duplicates are preferred over missed alerts).
  • Operator: 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"]
Common follow-ups
  • Is it OK to put a load balancer in front of Prometheus? Queries can be routed "sticky", but the two replicas' data is not fully consistent and graphs will jump around; Thanos Query is the better choice.
Bonus points

Point out the common causes of duplicate alerts: replica external labels not removed, and Alertmanager not clustered (#25).

Common wrong answers

"Prometheus primary/standby + shared NFS".

See Lesson 6 Module 2.

Q11. The responsibility boundaries of Prometheus, Grafana and Alertmanager? Does Grafana store data?Beginner
30-second answer

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).

In-depth answer
  • Grafana sends queries to Prometheus, Mimir, AMP, Azure Monitor and others through data source plugins.
  • Grafana Alerting (unified alerting) can evaluate rules across multiple data sources and has a built-in Alertmanager; it can also send alerts to an external Alertmanager. Define each kind of alert in only one place (#32).
  • Prometheus has its own UI (3.x has a new React UI with PromLens-style query explanations), suitable for debugging but not for dashboards.
Common follow-ups
  • Should alerts go in Prometheus rules or Grafana Alerting? Infrastructure/SLO alerts belong in Prometheus rules (versioned with code, simple HA); cross-data-source alerts or self-service alerts for business teams can use Grafana Alerting.
Bonus points

Mention that Grafana HA needs an external database and alerting HA peers (#31).

Common wrong answers

"Grafana pulls data from Prometheus and stores it".

See Lesson 1 Module 6 · Lesson 2 Module 5.

Q12. What are the important changes in Prometheus 3 compared with 2.x? What should you watch out for when upgrading?Intermediate
30-second answer

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.

In-depth answer

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.

Common follow-ups
  • What is the latest version? v3.16.0 (2026-11-05, verified in this lesson); kube-prometheus-stack 93.3.0 uses it by default.
  • How do I check UTF-8 names?{"http.server.duration", method="GET"}; when the old behavior is needed, use metric_name_validation_scheme: legacy.
Bonus points

Being able to explain how "left-open, right-closed" affects foo[1m:1m] shows you have actually read the migration guide.

Common wrong answers

"3.0 is just a UI revamp, so just upgrade".

See #6, #15, #17 and #50 in this lesson.

Q13. What is the relationship between Prometheus and OpenTelemetry? How do they work together?Intermediate
30-second answer

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.

In-depth answer
  • Differences: OTel uses delta or cumulative temporality, resource attributes (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.
  • Resource attributes go into target_info series by default; they can be promoted to labels through configuration, or joined in queries.
  • AWS ADOT (v0.51.0) is AWS's OTel Collector distribution; it can scrape Prometheus metrics and write them to AMP with SigV4.
prometheus --web.enable-otlp-receiver   # receiving endpoint /api/v1/otlp/v1/metrics
Common follow-ups
  • Do I still need exporters? Yes; the OTel Collector also has receivers such as hostmetrics that can replace some exporters, but the ecosystem maturity differs.
Bonus points

Mention exemplars: attaching a trace ID to histogram samples, so you can jump from a Grafana metric graph to the trace.

Common wrong answers

"OTel will replace Prometheus" — OTel is not a storage/query system.

See Lesson 6 Module 6, OpenTelemetry and its relationship with Prometheus.

Whiteboard diagram: the Prometheus ecosystem (Q1, Q3, Q10, Q11) Service discoveryk8s / cloud / file Targetsmyapp /metricsnode / redis exporterPushgateway (batch jobs) Prometheus server scrape manager (relabel · limits)TSDB: head + WAL + blocksPromQL engine · HTTP API · UIrule manager (recording / alerting)notifier → Alertmanagerremote_write / OTLP receptionHA = two independent replicas (external_labels.replica) Alertmanager ×3gossip clustergrouping · inhibition · silences notificationsTeams / PagerDuty Thanos / Mimiror AMP / Azure Monitorlong-term · global · deduplication Grafanastores metadata onlyquery data sources pull Explanation order: discovery → scrape → storage → query/rules → alerts → visualization → extension (HA / long-term storage)
Figure 5-1: draw and explain as you go; each arrow corresponds to one question

Scenario question 5-1: the team currently uses Zabbix plus in-house scripts, and the manager asks whether to adopt 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.

Key points of the model answer
  • Benefits: cloud-native ecosystem (K8s service discovery, kps, managed services), label-dimension queries, PromQL and SLOs, alerts as code, the Grafana ecosystem.
  • Costs / risks: a shift from "host-centric" to "service-centric" thinking; long-term storage and HA need extra design; the team needs to learn PromQL and cardinality control.
  • Path: ① adopt AKS first (managed Prometheus or kps) ② use node_exporter + file_sd/Azure SD for VMs ③ run critical alerts in parallel for two weeks to compare ④ use Grafana with the Zabbix plugin during the transition ⑤ gradually retire the Zabbix triggers.
  • Acceptance: every service has a RED dashboard and SLO alerts, and meta-monitoring (Watchdog) is in place.

Scenario question 5-2: a batch platform starts thousands of short jobs every 5 minutes and wants to monitor the duration of each job

Developers propose that each job push its metrics to Pushgateway with labels including task_id. How would you assess this? Give an alternative design.

Key points of the model answer
  • Problems: task_id Unbounded → cardinality explosion; Pushgateway never expires → series accumulate without limit; single point of failure.
  • Alternative: a scheduler (a long-running service) exposes aggregated metrics: 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.
  • If you must push: push per job type, overwriting the same group without the job ID; or use OTLP push to a backend that supports delta.
or score 70% or more on the quiz

Module 6 · Section B: PromQL and alert design (interview 14–25)

37:00 – 44:00 · rate/irate/increase, instant and range vectors, extrapolation, histogram, vector matching, recording rules, alert lifecycle, Alertmanager, alert fatigue, meta-monitoring, absent, rule testing
7 minPromQL · rules · Alertmanager12 questions
Learning goals
  • Be able to write on the spot the PromQL for the RED trio, P99 latency, error rate and saturation, and explain the semantics of each function.
  • Be able to explain the lifecycle of an alert from rule to notification, and how to design "few but precise" alerts.
  • Be able to answer advanced follow-ups: rate extrapolation, counter resets, lookback delta vs staleness, and the direction of group_left.

Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.

Q14. What are the differences between rate(), irate() and increase()? When is each used?Beginner
30-second answer

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).

In-depth answer
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
  • All of them can only be used on counters; for gauges use deriv(),delta(),*_over_time.
  • You must "rate first, then sum" (#16). Window ≥ 4 × scrape interval (#15).
Common follow-ups
  • Why is the result of increase not an integer? Extrapolation (Q16).
  • Why not use irate in alerts? It only looks at two points, so an occasional spike can trigger or miss the alert.
Bonus points

Mention using $__rate_interval in Grafana.

Common wrong answers

"irate is more precise, so it is better".

See Lesson 1 Module 4.

Q15. What are instant vectors and range vectors? What are lookback delta and staleness?Intermediate
30-second answer

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.

In-depth answer
  • A range query (Graph) = an instant query executed at each step from start..end.
  • Prometheus 3: ranges and lookback are left-open, right-closed (#15).
  • Cases with no stale marker: data arriving via remote write, samples with explicit timestamps, federation — these expire naturally through lookback.
  • --query.lookback-delta Adjustable; increase it when the scrape interval exceeds 5 minutes, otherwise the graph shows gaps.
Common follow-ups
  • What is a subquery?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.
Bonus points

Explain why a 15-minute scrape interval is an anti-pattern in Prometheus (both lookback and rate windows are affected).

Common wrong answers

"An instant query only returns samples exactly at that moment".

See Lesson 1 Modules 4 and 5.

Q16. How does rate() handle counter resets? Why extrapolate?Advanced
30-second answer

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.

In-depth answer
  • Example: window 60s, samples t=5s:10, t=35s:16, t=50s:2 (reset) → corrected 10, 16, 18; increase 8 over 45s, extrapolated to about 60s ≈ 10.7, then /60.
  • Consequences: increase() decimals appear; the increase of a low-frequency counter may exceed the actual number of events.
  • A client restart loses the increase that was not scraped before the reset — an inherent error of the pull model.
  • Prometheus 3.x added an experimental feature flag 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.
Common follow-ups
  • Why can't you sum first and then rate? A single instance's reset makes the total drop, which gets misjudged as an overall reset (#16).
  • What about the multi-process gunicorn problem? Values jumping back and forth are treated as resets (#11).
Bonus points

Proactively mention resets() for detecting frequent restarts.

Common wrong answers

"rate is (last − first) / window".

See Lesson 1 Module 4(recommended video: PromLabs "Understanding Counter Rates and Increases in PromQL").

Q17. How do you compute P99 latency? What are the principles and pitfalls of histogram_quantile?Intermediate
30-second answer

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.

In-depth answer
  • Pitfalls: aggregation dropped 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).
  • Average latency: rate(_sum[5m]) / rate(_count[5m]).
  • "Share of requests that meet the SLO" is better suited to alerting than quantiles: sum(rate(_bucket{le="0.25"}[5m])) / sum(rate(_count[5m])).
  • native histograms: histogram_quantile(0.99, sum(rate(x[5m]))) no need for le, with higher precision; histogram_fraction() computes the ratio over a time range.
Common follow-ups
  • Can you average the P99 across multiple instances? No, quantiles cannot be averaged; merge the buckets first and then compute.
Bonus points

Note that summary cannot be aggregated, so multi-replica services should choose histogram.

Common wrong answers

avg(histogram_quantile(0.99, …)).

See Lesson 1 Module 5.

Q18. Explain vector matching: on, ignoring, group_left, group_right.Intermediate
30-second answer

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.

In-depth answer
# 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]))
  • The "one" side must be unique, otherwise found duplicate series for the match group (#13).
  • Set operations and/or/unless are many-to-many, and often used for filtering (… and on(route) rate(..._count[5m]) > 0.1).
Common follow-ups
  • Adding bool to comparison operators?x > bool 5 Returns 0/1 instead of filtering.
Bonus points

Mention the experimental info() function in Prometheus 3, which simplifies info-metric joins.

Common wrong answers

Treating group_left as SQL's LEFT JOIN (it does not keep unmatched left-side series).

See Lesson 1 Module 5.

Q19. What is a recording rule? Naming conventions and use cases?Intermediate
30-second answer

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.

In-depth answer
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]))
  • Rules within the same group run in order, so later rules can reference earlier results; groups run in parallel (3.x can enable concurrent-rule-eval).
  • Recording rules themselves also produce series, so do not copy high-cardinality raw metrics 1:1.
  • Recording rules cannot have for (#20).
Common follow-ups
  • Do recording rules have historical data? They only start from creation time; use promtool tsdb create-blocks-from rules to backfill.
Bonus points

Mention that the multi-window recording rules for SLOs (rate5m, rate30m, rate1h, rate6h…) are the foundation of burn-rate alerts (Q45).

Common wrong answers

"Recording rules are just aliases for queries".

See Lesson 2 Module 1.

Q20. The alert rule lifecycle: inactive, pending, firing, resolved; for vs keep_firing_for?Beginner
30-second answer

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.

In-depth answer
- 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
  • The alert's label set = the labels of the expression result + the rule's labels; it determines Alertmanager routing and deduplication.
  • Annotations can use templates, but do not put $value the value into labels (every change in value would create a new alert).
  • State can be seen in ALERTS and ALERTS_FOR_STATE, and is restored after a restart.
Common follow-ups
  • Why does it stay pending forever? See #21.
Bonus points

Every alert carries runbook_url and severity, and states what severity means (whether it needs to wake someone up immediately).

Common wrong answers

"for is the interval at which the alert is re-sent" — that is Alertmanager's repeat_interval.

See Lesson 2 Module 2.

Q21. How do routing, grouping, inhibition and silences work in Alertmanager?Intermediate
30-second answer

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).

In-depth answer
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.
  • Test: amtool config routes test; view: amtool silence query.
Common follow-ups
  • What is the difference between silences and inhibition? Silences are manual and time-based; inhibition is automatic and based on the state of another alert.
Bonus points

Mention that overly fine grouping causes alert storms, and that an HA setup that is not clustered causes duplicates (#25).

Common wrong answers

"Alertmanager recalculates the alert conditions".

See Lesson 2 Module 3.

Q22. How do you design alerts to avoid alert fatigue?Intermediate
30-second answer

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".

In-depth answer
  • Tiers: page (act immediately), ticket (handle during working hours), info (record only).
  • Measure alert quality: pages per week, pages at night, the share that needed no action, MTTA.
  • SLO alerts (Q45) naturally separate "brief spikes" from "sustained budget burn".
  • Use inhibition for dependent alerts (when a node is down, do not report every service on that node).
Common follow-ups
  • Should CPU at 90% trigger an alert? If it does not affect users, do not page; for capacity planning, use forecasting (predict_linear) to generate tickets.
Bonus points

Cite Google SRE's view: "every page should feel necessary".

Common wrong answers

"Turn on every alert the exporters ship with, better too many than too few".

See Lesson 2 Modules 6 and 8.

Q23. How do you monitor the monitoring system itself (meta-monitoring)? What are Watchdog / Deadman's switch?Intermediate
30-second answer

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.

In-depth answer
- 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
  • Key meta-metrics: 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.
  • kps ships with a Watchdog and many self-monitoring rules for Prometheus/Alertmanager.
Common follow-ups
  • Who monitors Grafana? black-box probing /api/health, or the cloud service's built-in health checks.
Bonus points

Mention deploying a small meta-monitoring Prometheus across regions or clouds.

Common wrong answers

"Prometheus is very stable, so there is no need to monitor it".

See Lesson 2 Module 8.

Q24. What is absent() for? How should "no data" be handled?Intermediate
30-second answer

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.

In-depth answer
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.
  • Grafana Alerting corresponds to the "No data handling policy" (#32).
Common follow-ups
  • Should every metric have an absent alert? Only for critical jobs and critical business metrics; pair them with up alerts.
Bonus points

Point out that or vector(0) loses labels, so be careful when using it in alerts.

Common wrong answers

"PromQL returns 0 when a metric is empty".

See Lesson 2 Module 2.

Q25. How do you test alerts and recording rules? How do you ensure quality in CI?Intermediate
30-second answer

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.

In-depth answer
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
  • Tests must cover "bad data": duplicate series (#13), missing metrics (#22), too few samples in the window (#15).
  • Operator: the PrometheusRule admission webhook validates the syntax; in CI, you can extract the spec of a PrometheusRule and test it with promtool.
  • When upgrading the Prometheus version, run all tests with the new promtool (#50).
Common follow-ups
  • How do you test dashboards? JSON lint, grep ${DS_ (#27), Grafonnet/Terraform plan, and API smoke tests on the key queries.
Bonus points

Mention the values expansion syntax (0+10x15,_ for missing values,stale).

Common wrong answers

"Trigger it manually in production and see what happens".

See Lesson 5 Module 6 rule testing: promtool and CI.

Whiteboard diagram: the rate calculation (Q14, Q16) window [5m] (Prometheus 3: left-open, right-closed) 10 16 25 2 (reset) 9 ① correct the reset: 2 → 27, 9 → 34 ② increase = 34 − 10 = 24 ③ extrapolate to the window based on the time the samples cover ④ ÷ 300s irate uses only the last two points: (9 − 2) / Δt (after the reset) · increase = rate × window seconds
Figure 6-1 rate = reset correction + extrapolation + averaging
Alert lifecycle (Q20, Q21) inactive pending firing Alertmanager notification expression returns a resulthold forresendgrouping / inhibition / silences If any evaluation returns empty → pending resets; condition gone → resolved (keep_firing_for can delay this)
Figure 6-2 for is evaluated in Prometheus; grouping and repeats happen in Alertmanager

Scenario question 6-1: write the RED dashboard queries for myapp and two alerts on the spot

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".

Key points of the model answer
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])))
  • Alerts use recording rules + a fixed [5m],for: 5m; the P99 alert adds a request-volume filter to avoid NaN / low-traffic false positives (#18); attach a runbook.
  • Add absent(myapp_http_requests_total) and up{job="myapp"} == 0.

Scenario question 6-2: the on-call engineer complains of being woken up 5 times every night, mostly for things that need no action

You take over alert governance; what do you do in the first month?

Key points of the model answer
  • Export 30 days of alert history (Alertmanager notification logs / PagerDuty), and count per alert name the number of times, whether action was needed, and the handling time.
  • Delete or downgrade alerts that need no action; turn cause-type alerts into tickets; add keep_firing_for/longer windows to flapping alerts.
  • Introduce SLOs + multi-window burn rates to replace threshold alerts; improve inhibition and grouping.
  • Set up alert review: every new alert must have a runbook and an owner; review monthly.
or score 70% or more on the quiz

Module 7 · Section B: Kubernetes and cloud monitoring (interview 26–38)

44:00 – 52:00 · kps, Operator, the ServiceMonitor family, K8s metric sources, SD roles, application onboarding, Azure managed Prometheus, Managed Grafana, AMP/AMG, managed-service trade-offs, multi-cluster, monitoring as code, HPA
8 minOperator · ama-metrics · SigV413 questions
Learning goals
  • Explain the Prometheus Operator reconciliation process, and the path a ServiceMonitor takes from creation to becoming a target.
  • Distinguish the metric sources and uses of cAdvisor, kubelet, kube-state-metrics, node-exporter and metrics-server.
  • Compare the architecture, identity and cost trade-offs of self-hosted kps, Azure managed Prometheus + Managed Grafana, and AMP + AMG.

Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.

Q26. Which components does kube-prometheus-stack include?Beginner
30-second answer

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.

In-depth answer
  • Key default values: Prometheus retains data for 10d; *SelectorNilUsesHelmValues: true (selects only release: kps, #9); the admin API is disabled.
  • Managed clusters must turn off control-plane scraping (#8).
  • CRDs are not upgraded with 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
Common follow-ups
  • What is the difference between kps and kube-prometheus (jsonnet)? Same source; kps is the Helm-packaged version.
Bonus points

Mention that the Grafana subchart has moved to the grafana-community repository (OCI).

Common wrong answers

"kps is just a Helm chart for Prometheus".

See Lesson 5 Module 1.

Q27. How does the Prometheus Operator work?Intermediate
30-second answer

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.

In-depth answer
  • Reconciliation loop: watch → select → generate config → compare hash → update Secret/StatefulSet → write status back to the CR (RECONCILED/AVAILABLE).
  • Troubleshooting: kubectl get prometheus the CR's status conditions, Operator logs, the generated Secret content, config-reloader logs, and the Prometheus /config page.
  • The PrometheusRule admission webhook validates PromQL syntax at apply time.
Common follow-ups
  • Why can't you edit prometheus.yml directly? It gets overwritten by the Operator; use additionalScrapeConfigs or the ScrapeConfig CRD.
Bonus points

Mention that the Operator automatically handles the replica label prometheus_replica, sharding shards (hashmod).

Common wrong answers

"The Operator sends ServiceMonitors directly to Prometheus".

See Lesson 5 Modules 1 and 2.

Q28. When should ServiceMonitor, PodMonitor, Probe and ScrapeConfig each be used?Intermediate
30-second answer

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.

In-depth answer
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}]
  • All of them are constrained by the corresponding selector and namespaceSelector of the Prometheus CR (#9).
  • Azure managed services use the azmonitoring.coreos.com group's PodMonitor/ServiceMonitor (#34).
Common follow-ups
  • Is it OK to write the ServiceMonitor port as a number?port It must be the port name; or use targetPort.
Bonus points

Mention that sampleLimit,metricRelabelings can be set per application on these objects.

Common wrong answers

"PodMonitor is an exporter for processes inside a Pod".

See Lesson 5 Modules 2 and 7.

Q29. What are the differences between cAdvisor, kubelet, kube-state-metrics, node-exporter and metrics-server?Intermediate
30-second answer

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.

In-depth answer
# 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])
  • cAdvisor's container=""/POD series are Pod/cgroup aggregates; filter them when aggregating to avoid double counting.
  • OOMKilled check: working_set close to the limit + kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}.
Common follow-ups
  • Why use working_set rather than usage? The OOM killer and kubelet eviction are based on the working set.
Bonus points

Explain that metrics-server and Prometheus do not replace each other (the K8s lesson already covers HPA).

Common wrong answers

"kube-state-metrics collects CPU usage".

See Kubernetes 8 hours · Lesson 5 Module 1.

Q30. Which roles does kubernetes_sd_configs have? What are their labels and use cases?Intermediate
30-second answer

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.

In-depth answer
  • The Endpoints API is marked as deprecated; the recommended choice is endpointslice, and watch out for RBAC (#10).
  • In large clusters, the SD watches themselves consume API server and Prometheus memory; narrow the scope using namespaces and selectors .
  • The Operator's ServiceMonitor generates the endpoints/endpointslice role configuration.
kubernetes_sd_configs:
  - role: endpointslice
    namespaces: {names: [myapp]}
    selectors: [{role: endpointslice, label: "app.kubernetes.io/name=myapp"}]
Common follow-ups
  • Can Prometheus outside the cluster use this? Yes, configure api_server and credentials, but Pod IPs must be routable.
Bonus points

Mention that the Operator's serviceDiscoveryRole can switch between Endpoints and EndpointSlice (check the Operator docs).

Common wrong answers

"Use role: service to scrape application metrics" (you only get one Service VIP, load-balanced to a random Pod).

See Lesson 7 Module 2.

Q31. What are the full steps to onboard a new application to monitoring in Kubernetes?Beginner
30-second answer

① 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.

In-depth answer
  • Put the ServiceMonitor, PrometheusRule and dashboards in the application's Helm chart so they ship with the application version.
  • The Grafana sidecar in kps loads ConfigMap dashboards that carry the grafana_dashboard: "1" label.
  • Acceptance: up,scrape_samples_scraped, an absent alert, and a dashboard screenshot.
Common follow-ups
  • A multi-process Python application? multiprocess mode (#11).
Bonus points

Propose "monitoring-ready" as part of the go-live checklist.

Common wrong answers

"Edit the Prometheus config file directly to add a static target".

See Lesson 5 Module 2.

Q32. What is the architecture of Azure Monitor managed Prometheus?Intermediate
30-second answer

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.

In-depth answer
  • Configuration: 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).
  • Limits: label name/value lengths and labels per series; the workspace has quotas on active series and ingestion rate (#38).
  • Creating the workspace automatically creates DCR/DCE in the 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"
Common follow-ups
  • Private AKS clusters? Additional Private Link configuration is required, and some scenarios are limited; check the official docs.
Bonus points

Know the troubleshooting entry point: the Prometheus agent UI on port 9090 of each ama-metrics Pod.

Common wrong answers

"Managed Prometheus means Azure installs kps in your cluster for you".

See Lesson 3 Module 2.

Q33. What is the identity and permission model of Azure Managed Grafana?Intermediate
30-second answer

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).

In-depth answer
  • Tiers: the Essential tier can no longer be created and is scheduled for full deprecation on 2027-03-31; Standard (X1/X2; X2 supports more alert rules) provides an SLA, private endpoints, alerting, SMTP and reporting.
  • Service accounts / API keys are used for automation (the Terraform Grafana provider).
  • Grafana Enterprise is an optional add-on to Standard.
Common follow-ups
  • Are there other options? Azure Monitor also has a built-in Grafana experience ("Grafana in Azure Monitor"); check the official docs for the differences from Managed Grafana.
Bonus points

Stress that "sign-in identity ≠ data access identity" (Figure 3-1).

Common wrong answers

"Assigning Monitoring Reader to a user lets them see Prometheus data in Grafana".

See Lesson 3 Module 4.

Q34. What is the architecture and authentication of AMP + AMG?Intermediate
30-second answer

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.

In-depth answer
  • Quotas: active series, ingestion rate, request TPS (#38); monitor with CloudWatch usage metrics.
  • HA deduplication: the two replicas use the external-label scheme (#47).
  • Cost: billed by ingested samples, storage and query samples; AMG is billed per active editor/viewer. Check the official pricing.
Common follow-ups
  • How do you choose between the managed collector and ADOT? The collector saves operations work but has limited configuration flexibility; ADOT can also handle traces and logs.
Bonus points

State the format of the remote write endpoint https://aps-workspaces.<region>.amazonaws.com/workspaces/<id>/api/v1/remote_write.

Common wrong answers

"AMG signs in with an IAM username and password".

See Lesson 4.

Q35. How do you choose between managed Prometheus/Grafana and a self-hosted kps?Advanced
30-second answer

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.

In-depth answer
DimensionManaged (AMW/AMP)Self-hosted kps + Thanos/Mimir
OperationsLowHigh
Cost modelPer sample/series; grows with cardinalityCompute + object storage + people
FlexibilityLimited (quotas, configuration entry points)Fully controllable
Multi-cloudOne per cloudUnified
ComplianceData is in the cloud serviceLocation is your choice
  • Common mix: in-cluster Prometheus agent/collector + managed storage + managed or self-hosted Grafana.
Common follow-ups
  • How do you estimate managed cost? Use the existing Prometheus's rate(prometheus_tsdb_head_samples_appended_total[5m]) and head series multiplied by the price.
Bonus points

Do cardinality governance before migrating; otherwise the managed bill exposes every bad instrumentation.

Common wrong answers

"Managed is always cheaper".

See Lesson 3 Module 1 · Lesson 4 Module 1.

Q36. How do you monitor multiple Kubernetes clusters in a unified way?Intermediate
30-second answer

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.

In-depth answer
  • remote write: centralized and simple to query; bandwidth and central capacity are the costs.
  • Thanos sidecar: data stays local plus object storage, fanned out at query time; cluster networks must be reachable.
  • Multi-tenancy: Mimir uses X-Scope-OrgID to separate tenants (#48).
  • In Grafana, switch between them with a cluster variable.
Common follow-ups
  • What if the central system goes down? Each cluster's local Prometheus still keeps short-term data and local alerts.
Bonus points

Point out that the cluster label must be named consistently across all clusters, otherwise queries and alert routing become a mess.

Common wrong answers

"One Prometheus scrapes all Pods across all clusters".

See Lesson 6 Modules 1 and 4.

Q37. How do you do "monitoring as code": versioning dashboards, data sources and alerts?Intermediate
30-second answer

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.

In-depth answer
  • Fixed uid, remove ${DS_…} (#27), and a read-only production Grafana (#29).
  • Terraform example resources: 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")
}
Common follow-ups
  • How do UI changes flow back? Export the JSON and commit it, or use Git Sync.
Bonus points

Check query cost when reviewing dashboards (#45).

Common wrong answers

"Periodically backing up grafana.db is versioning".

See Lesson 5 Modules 4 and 5.

Q38. How do you drive HPA scaling with Prometheus metrics?Intermediate
30-second answer

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).

In-depth answer
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"
  • Note: when Prometheus is unavailable, scaling stops working, so set a sensible fallback; queries should be cheap, with short but stable windows.
  • In HPA setups, Helm/GitOps must not render replicas, to avoid conflicts.
Common follow-ups
  • Can managed Prometheus be used? KEDA supports authenticated Prometheus endpoints (Azure workspaces and AMP need the matching authentication); follow the KEDA docs.
Bonus points

Scaling by per-replica QPS or queue length is closer to the business than CPU.

Common wrong answers

"HPA reads Prometheus directly".

See Kubernetes 8 hours(metrics-server and HPA).

Whiteboard diagram: Operator reconciliation (Q27) ServiceMonitorPodMonitor · Rulerelease: kps Operatorselector matchinggenerate config Secretprometheus.yaml.gz+ rule ConfigMaps Pod: prometheusconfig-reloader → /-/reloadStatefulSet (managed by the Operator) TargetsEndpointSlice → Pod IP Troubleshooting order: CR status → Operator logs → Secret content → reloader logs → /config → /targets
Figure 7-1 the five steps from ServiceMonitor to target

Scenario question 7-1: a company with 6 AKS clusters wants to set up unified monitoring

Requirements: a global dashboard, per-team isolation, 13 months of retention, and a limited budget.

Key points of the model answer
  • Option A (managed): enable managed Prometheus on each cluster, writing to an Azure Monitor workspace per environment; Managed Grafana Standard; check the official docs for retention and cost; start with a minimal ingestion config + keep list.
  • Option B (self-hosted): a Prometheus agent per cluster → a central Mimir (multi-tenant, with one tenant per team), with object storage retaining 13 months.
  • Compare: operations staffing vs series-count cost; team isolation (workspace/tenant + Grafana folder permissions).
  • Unified labels cluster,team; evaluate alerts close to the data.

Scenario question 7-2: migrating from kps to Azure managed Prometheus

List the migration checklist.

Key points of the model answer
  • Change the ServiceMonitor to azmonitoring.coreos.com (#34); ConfigMap scraping (#33).
  • Compare against the default minimal ingestion, and add the keep list (#36).
  • PrometheusRule → Prometheus rule group resources; Alertmanager routes → Action Groups.
  • Change the Grafana data source to AMW and grant the identity Monitoring Data Reader (#35); check dashboards for the le/ metric-name differences.
  • Run both in parallel for 2 weeks and compare key queries, then turn off kps.

Scenario question 7-3: AMP data on EKS is often delayed or missing

Give the troubleshooting steps.

Key points of the model answer
  • Sending side: remote write seconds behind, failed/retried/dropped (#46), and 403/429/400 in the logs.
  • 403 → SigV4 / IRSA / region (#37); 429/400 → quota and cardinality (#38); out-of-order / duplicates → HA deduplication (#47).
  • AMP side: CloudWatch usage metrics; query side: the AMG plugin and the time range.
or score 70% or more on the quiz

Module 8 · Section B: scaling, SLOs and scenario design (interview 39–50)

52:00 – 60:00 · cardinality control, capacity planning, Thanos vs Mimir, remote write tuning, federation, SLOs and error budgets, burn rate, query optimization, four system-design / troubleshooting scenarios
8 minSLO · burn rate · Thanos/Mimir12 questions
Learning goals
  • Be able to estimate a Prometheus's memory and disk needs, and propose a cardinality governance plan.
  • Be able to write multi-window multi-burn-rate alerts, and explain where the thresholds 14.4 / 6 / 1 come from.
  • Be able to work through a "design a monitoring platform" or "troubleshoot Prometheus OOM / alert not sent" scenario question within 10 minutes.

Skim the questions and their focus points first, and mark the ones you are unsure of; click a row to jump to the details.

Q39. How do you find and control high cardinality?Advanced
30-second answer

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).

In-depth answer
  • Common culprits: raw URLs, user/order/trace IDs, error messages, Pod UIDs, too many histogram buckets × high-cardinality labels.
  • A histogram's series count = label combinations × (number of buckets + 2); consider native histograms or fewer buckets.
  • Governance process: dashboards list "series count per job" with an owner; services that exceed their quota are first cut off by sample_limit (#7), which forces a fix.
curl -s localhost:9090/api/v1/status/tsdb | jq '.data.seriesCountByMetricName[:10]'
Common follow-ups
  • What if you need a per-user dimension? Use logs, traces, an analytics database, or exemplars.
Bonus points

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.

Common wrong answers

"Adding memory is enough".

See this lesson's #39 · Lesson 7 Module 3.

Q40. How do you do capacity planning for Prometheus (memory, CPU, disk)?Advanced
30-second answer

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.

In-depth answer
prometheus_tsdb_head_series
rate(prometheus_tsdb_head_samples_appended_total[5m])
process_resident_memory_bytes / prometheus_tsdb_head_series
  • Example: 1 million series at a 15s interval → about 67k samples/second; 15 days ≈ 6.7e4 × 1.3e6 s × 1.5 B ≈ 130 GB.
  • Query memory is calculated separately: --query.max-samples, and the number of concurrent queries.
  • Beyond a single machine: functional sharding (by team/namespace), hashmod sharding, agent + remote storage.
Common follow-ups
  • Does GOMEMLIMIT help? In Prometheus 3 it is set automatically to the container limit, reducing GC-driven peaks, but it does not replace capacity planning.
Bonus points

Turn capacity metrics into a dashboard and predict_linear alert on them.

Common wrong answers

Estimating by the number of targets rather than by series count.

See Lesson 2 Module 7.

Q41. What are the architectural differences between Thanos and Grafana Mimir, and how do you choose?Advanced
30-second answer

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.

In-depth answer
Thanos (sidecar mode)Mimir
WritesPrometheus writes locally; the sidecar uploadsremote write push
Multi-tenancyLimited (supported by Receive)Native (X-Scope-OrgID, per-tenant limits)
InvasivenessLow; adopt graduallyRequires running a distributed system
Recent dataqueries each Prometheusingester
DownsamplingSupportedCheck the official docs
Common follow-ups
  • Are there other options? VictoriaMetrics, Cortex, managed services (AMP evolved from Cortex; check the AWS docs for specifics).
Bonus points

Choose based on the organization: many independent Prometheus instances with reachable networks → Thanos; a platform team offering multi-tenant SaaS → Mimir.

Common wrong answers

"Thanos is the clustered version of Prometheus".

See Lesson 6 Module 3.

Q42. How does remote write work, and how do you tune it?Advanced
30-second answer

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.

In-depth answer
  • Key metrics: seconds behind (#46), shards vs shards_max, samples_failed / retried / dropped.
  • Tuning order: first reduce the volume sent (write relabel) → increase batch size → add shards → check the receiver and network.
  • Prometheus 3: remote write no longer uses HTTP/2 by default; Remote-Write 2.0 is supported (protobuf_message: io.prometheus.write.v2.Request, reduces bandwidth, carries metadata and created timestamps); check receiver support in the docs.
  • Agent mode keeps only the WAL, suitable for pure forwarding.
Common follow-ups
  • What happens if the remote side is unavailable for a long time? WAL retention is limited; data is lost once it is exceeded, and the local disk grows because of the WAL.
Bonus points

Describe the deduplication approach for HA dual writes (#47).

Common wrong answers

"remote write reads from TSDB blocks and uploads them" (that is the Thanos sidecar).

See Lesson 6 Module 1.

Q43. How do you choose among federation, remote write and Thanos for a global view?Intermediate
30-second answer

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.

In-depth answer
  • Federation pitfalls: honor_labels (#49), scrape timeouts, and duplicated storage of raw data.
  • remote write pitfalls: bandwidth, backlog (#46), quotas (#38).
  • Thanos pitfalls: slow query fan-out, deduplication configuration (#47), object storage costs.
Common follow-ups
  • Where should alerts go? Alerts that can be evaluated at the edge stay there; global alerts go to the center (Thanos Ruler / Mimir ruler / managed rules).
Bonus points

Draw the data flow of all three.

Common wrong answers

"Use federation to pull all metrics into the center".

See Lesson 6 Module 1.

Q44. Explain SLI, SLO and error budget, and define an SLO for myapp.Intermediate
30-second answer

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.

In-depth answer
- 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]))
  • Measure the SLI from the user side where possible (load balancer / ingress), with application-side measurement as a supplement.
  • Tools: Sloth, Pyrra and the OpenSLO spec can generate rules (check each project's docs).
  • Note that in Prometheus 3, le="0.25" is safe as written, while le="1" has to be written as le="1.0" (#17).
Common follow-ups
  • What SLO should you set? Base it on historical data and business needs; do not start at 99.99%.
Bonus points

Distinguish SLA (contract, compensation) from SLO (internal target, which should be stricter than the SLA).

Common wrong answers

"An SLO means keeping CPU below 80%".

See Lesson 6 Module 5 SLOs and error budgets.

Q45. What is a multi-window multi-burn-rate alert? Where do the thresholds 14.4 and 6 come from?Advanced
30-second answer

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.

In-depth answer
- 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}
  • Recording rules for the 5m / 30m / 1h / 6h (and 3d) windows need to be precomputed.
  • Advantages: large outages alert within minutes, small but sustained problems are still found, and there is less flapping.
Common follow-ups
  • Low-traffic services? When there are too few requests in the window, the ratio is unstable; merge services, use synthetic traffic, or lengthen the window.
Bonus points

Be able to derive the calculation of 14.4, rather than memorizing the number.

Common wrong answers

"Alert when the error rate > 0.1% lasts 5 minutes".

See Lesson 6 Module 5.

Q46. How do you optimize slow PromQL and slow dashboards?Intermediate
30-second answer

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).

In-depth answer
  • Narrow the selection first with equality matchers: {job="myapp", route=~"/api/.*"} is better than {route=~".*api.*"}.
  • topk,count by full-series scans are expensive; /tsdb-status is cheaper.
  • Slow alerting-rule evaluation hurts alert timeliness (iterations_missed, #45).
Common follow-ups
  • Grafana's Max data points? It determines the step; do not set Min interval too small (#44).
Bonus points

Establish a "query only recording rules" standard for long-range panels.

Common wrong answers

"Raise --query.timeout".

See Lesson 7 Module 4.

Q47. Scenario: design a monitoring platform for 1,000 nodes, 3 regions and 20 teams.Advanced
30-second answer

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.

In-depth answer
  • Capacity: estimate series first (1,000 nodes × node_exporter ~1,000 series = 1 million, plus K8s and applications), then determine the number of shards (Q40).
  • Governance: a series quota per team, sample_limit, onboarding documents, label conventions (team, service, env).
  • Reliability: during a regional failure, local alerts still fire; central storage spans multiple AZs; the Watchdog heartbeat goes to an external service.
  • Cost: tiered retention policy (raw data 15 days, downsampled 13 months).
Common follow-ups
  • What about a network partition? remote write buffers within the WAL retention period, and local alerts are unaffected.
Bonus points

Give a phased rollout plan and acceptance metrics (coverage, alert usefulness rate, query P95).

Common wrong answers

"One giant Prometheus scrapes everything".

See Lesson 6 Module 8 comprehensive architecture review.

Q48. Scenario: a production Prometheus OOMs every afternoon. How do you investigate?Advanced
30-second answer

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).

In-depth answer
  1. Use another Prometheus or meta-monitoring to see the curve before the crash (the history remains in the TSDB after the restart).
  2. /tsdb-status Find the top metrics and labels; compare against release records.
  3. Query side: large queries from the query log just before the OOM,prometheus_engine_queries concurrency.
  4. Configure guardrails: --query.max-samples,--query.max-concurrency, per job sample_limit.
  5. Review: add head-series alerts and a cardinality review.
Common follow-ups
  • Why does it not even come back up after a restart? WAL replay (#40).
Bonus points

Mention Prometheus 3's automatic GOMEMLIMIT, and the periodic memory fluctuations during compaction (every 2 hours).

Common wrong answers

"Just double the memory limit".

See #39, #40 and #45 in this lesson.

Q49. Scenario: a service went down for 20 minutes at night, but no alert was received. How do you investigate and improve?Intermediate
30-second answer

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.

In-depth answer
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
Common follow-ups
  • What if the monitoring system itself also went down? An external dead man's switch (Q23).
Bonus points

In the post-incident review, produce an "alert coverage test": use promtool to reproduce the input series of this outage.

Common wrong answers

Changing the Alertmanager config directly without first confirming whether the alert was firing.

See the Module 2 decision tree.

Q50. Scenario: monitoring costs tripled within a year. How do you optimize?Advanced
30-second answer

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.

In-depth answer
  • Measure first: dashboards of series count and sample rate per job / team.
  • remote write sends only the data that needs long-term retention (write_relabel_configs).
  • Trim histogram buckets or switch to native histograms.
  • Verify: dashboards and alerts are unaffected before and after the optimization (promtool tests + query comparison).
Common follow-ups
  • Just shorten retention directly? You can, but confirm it against compliance and capacity-planning requirements.
Bonus points

Turn the "unused metrics" analysis into a monthly automated report.

Common wrong answers

"Just switch to cheaper storage". If the data volume is not governed, costs will climb again whatever the storage.

See Lesson 3 Module 8 · Lesson 4 Module 8.

Whiteboard diagram: multi-window multi-burn-rate (Q45, SLO 99.9%, 30 days) fast burn → page1h window AND 5m windowburn rate > 14.4 (1h consumes 2% of the budget)error rate > 1.44% medium burn → page6h window AND 30m windowburn rate > 6 (6h consumes 5% of the budget)error rate > 0.6% slow burn → ticket3d window AND 6h windowburn rate > 1 (3d consumes 10% of the budget)error rate > 0.1% burn rate = error rate / (1 − SLO); 14.4 = 2% × 720h / 1h; 6 = 5% × 720h / 6h Long window = significance (no alert from a single spike); short window = quick clearing after recovery Depends on recording rules: slo:…:ratio_rate5m / 30m / 1h / 6h / 3d
Figure 8-1: three tiers of alerts cover "large outages reported quickly, small problems not missed"

Scenario question 8-1: design the SLOs and alerts for shop (podinfo api + nginx web + postgres)

Key points of the model answer
  • User journeys: browse products (web → api), place orders (api → postgres). SLIs: success rate and latency (share under < 500ms) at the nginx entry point.
  • SLOs: availability 99.5% / 30 days, latency 95% / 30 days.
  • Alerts: multi-window burn rate (Q45); dependency signals (postgres connection count, replication lag) only go to dashboards or tickets.
  • Dashboards: SLO overview (remaining budget), RED, USE.

Scenario question 8-2: a single Prometheus with 4 million series is getting slower to query, and 64 GB of memory is still not enough

Key points of the model answer
  • First govern: use /tsdb-status to find the top metrics, drop unused metrics (Q50), and fix high cardinality (Q39).
  • Split: shard by function (infrastructure / applications / K8s control plane), or hashmod sharding + Thanos Query to aggregate.
  • Long term: remote write to Mimir, and keep only 2–7 days locally.
  • Queries: recording rules + query-frontend caching.

Scenario question 8-3: the boss requires "99.99% availability for all services and zero false-positive alerts"

Key points of the model answer
  • Explain what 99.99% means (about 4.3 minutes of budget over 30 days) and its cost (multi-region, automatic failover, release process).
  • Set SLOs in tiers by service; use an error-budget policy to constrain releases.
  • "Zero false positives" is unrealistic: use burn rates to trade off precision against recall, and review quarterly.
or score 70% or more on the quiz

Problem cheat sheet + interview flashcards

50 "error → first diagnostic command → common fix" entries · 50 one-line key-point cards · printable
Post-course

A · cheat sheet for 50 production issues

Filter by keyword (for example deadline,labelset,Grafana,ama-metrics,WAL). Click a number to jump to the details in the corresponding module.

B · recall cards for 50 interview questions

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.

General command card

Scraping and targets

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

PromQL self-check

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

Alert chain

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 query

TSDB and capacity

curl -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

Grafana

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 → Query

Cloud managed

kubectl 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

Comprehensive drill + mock interview

8 mixed fault scenarios (read the symptoms first, judge for yourself, then expand the answers) · full mock interview drawing 10 random questions out of 50 · final quiz
Post-course ≈ 40 minutes

I. Comprehensive fault drills

Each scenario combines several issues from Section A. Write down your first diagnostic command and your judgment first, then expand the answer.

Scenario 1: The day after upgrading to Prometheus 3, half the panels on the SLO dashboard are empty, one old exporter turns red, and all alerts look normal (no alerts fired at all)
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).

Scenario 2: After a new service went live, Prometheus restarts every 40 minutes
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.

Scenario 3: On kind, kps was just installed and the alerts page is all red, yet the ServiceMonitor created for myapp has no target
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.

Scenario 4: The alert is FIRING in Prometheus, but the Teams channel has no messages at all
$ 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.

Scenario 5: After the on-call engineer scaled Grafana to 2 replicas, users are frequently logged out, dashboard saves fail, and each Grafana alert is received twice
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.

Scenario 6: After migrating from kps to AKS managed Prometheus, myapp metrics and some KSM metrics disappear, and the Managed Grafana panels return 403
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).

Scenario 7: The Prometheus on EKS writing to AMP initially could not write at all; after the fix, gaps appeared, and sum values in Grafana doubled
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.

Scenario 8: At 9 a.m. the "global overview" dashboard will not open, and a batch of alerts is delayed by 10 minutes
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.

II. Full mock interview (10 questions drawn at random from 50)

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.

III. Open-ended self-test (6 questions)

  1. Draw the seven steps of one scrape, and mark which step each of #1–#12 occurs at.
  2. Explain why "No data is not 0", and write three rules for myapp that prevent alerts from going blind.
  3. List the checklist for the Prometheus 3 upgrade (at least 8 items), and explain which of them can fail silently.
  4. Compare Azure managed Prometheus and AMP in terms of collection method, CRDs, identity and quotas.
  5. Estimate the memory and disk needs of a Prometheus with 2 million active series, a 15s scrape interval and 15 days of retention.
  6. Design SLOs and multi-window burn-rate alerts for shop, and write the recording rules and alerting rules.

IV. Final quiz (12 questions)

Sources and version notes

Verified 2026-11-15 · version baseline: Prometheus v3.16.0 · Alertmanager v0.35.0 · Grafana 13.3.1 · kube-prometheus-stack 93.3.0

Official docs and source code

TopicConclusions used in this lessonSources (accessed 2026-11-15)
VersionsPrometheus 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.0Each project's GitHub Releases; kps Chart.yaml/values.yaml (tag kube-prometheus-stack-93.3.0)
Prometheus 3 migrationStrict 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 GOMEMLIMITPrometheus 3.0 migration guide(v3.16.0 docs/migration.md)
Prometheus error messagesserver 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
AlertmanagerNotify failed / Notify attempt failed, will retry later / notify retry canceled …; undefined receiver … used in route; root route must specify a default receiverprometheus/alertmanager v0.35.0 notify/retry_stage.go, config/config.go
GrafanaCannot 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 Prometheusama-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 UITroubleshoot · CRD · Minimal profile · Enable
Azure Managed GrafanaEssential cannot be newly created, full deprecation on 2027-03-31; Standard X1/X2; Monitoring Reader assigned by default, Prometheus data needs Monitoring Data ReaderOverview · Permissions
AMP / AMG429/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 SAMLAMP troubleshooting · AMG versions · AMP data source · AMG auth
Mimirmeaning and common causes of err-mimir-max-series-per-user and err-mimir-sample-out-of-orderMimir runbooks(from the mimir-3.2.5 source)
SLOMulti-window multi-burn-rate (14.4 / 6 / 1)Google SRE Workbook: Alerting on SLOs

Video verification notes

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.

Audio notes

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.

Known limitations

  • The error strings for Prometheus, Alertmanager and Grafana themselves have been checked against the source code of the versions above; the outer log format (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".
  • All "expected output examples" are illustrative: IPs, Pod names, series counts, times and IDs differ in your environment; the reproduction labs were written from the official docs and source code and have not been run in this environment. The specifics of myapp (whether it sets myapp_redis_up to 0 when Redis is unavailable, the /metrics implementation, dashboard file names, the Grafana admin password) follow lessons 1 and 2.
  • Details handled conservatively (follow the official docs): the exact wording of the Azure Managed Grafana 403 hint when querying the AMW; field names of the keep list in ama-metrics-settings-configmap (these change with schema v1/v2); the EKS access configuration for the AMP managed collector; the pricing of AMP / Azure Monitor / Managed Grafana / AMG; the feature status of Grafana Git Sync and query caching; the maturity of Prometheus 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.
  • The per-series memory of "a few KB" is an empirical value; the cardinality estimator's default of 4 KiB is for demonstration only, so calibrate with process_resident_memory_bytes / prometheus_tsdb_head_series the real values from your environment.
  • The self-assessment records of the mock interview are stored only in this browser's localStorage and are lost when site data is cleared.