Prometheus & Grafana Hour 7: Deep Troubleshooting, Optimization and Advanced Topics
- Use the eight-stage chain model (L1 Expose → L2 Discovery → L3 target relabel → L4 Scrape → L5 Parse and limits → L6 Storage → L7 Query and rules → L8 Notification and presentation) to pin any monitoring fault to a specific stage, and to know the “observation window” for each stage (page, API, self-monitoring metrics, commands).
- Read the real
lastError:connect: connection refused,context deadline exceeded,server returned HTTP status 403 Forbidden, newly added in Prometheus 3received unsupported Content-Type … and no fallback_scrape_protocol specified for target,sample limit exceeded,label_limit exceeded (…); distinguish “target down” from “a target that does not exist at all”. - Diagnose cardinality explosion: TSDB Status page /
/api/v1/status/tsdb,topk(10, count by (__name__)({__name__=~".+"})),promtool tsdb analyze; usesample_limit,label_limit,metric_relabel_configsand the Operator'senforcedSampleLimitto set guardrails. - Optimize slow PromQL and dashboards: understand “loaded samples = series × samples per series”, read the
query processing would load too many samples into memoryandquery timed out in …, use recording rules,$__rate_interval, Max data points, and narrowing the selector. - Explain TSDB internals: head block (in memory, default 2-hour block), WAL (128 MiB segments, checkpoints), head chunks as m-map, compaction (2h → 6h → 18h…, capped at 10% of retention and no more than 31 days), retention and disk; be able to tell from logs and metrics whether WAL replay is slow, compaction is failing, or the disk is full.
- Troubleshoot alerts that do not fire (rules not loaded,
fornot met, expression returns no data,absent()missing, Alertmanager routing / inhibition / silences) and alert storms (grouping,group_interval, flapping andkeep_firing_for). - Troubleshoot Grafana: data source connectivity, Query inspector,
$__rate_intervaland step, template variables, sidecar provisioning, permissions, and “Datasource … was not found”.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (kind cluster lab + kps, namespace faultlab) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: fault-injection environment | Deploy a controllable faultexp exporter (latency, Content-Type, series count, churn and error rate can all be toggled with environment variables) + ServiceMonitor + PrometheusRule | Environment self-check list | Baseline: up{job="faultexp"} == 1 |
| 1 | 00–06 | Troubleshooting methodology: from alert to root cause | Eight-stage chain model, observation windows per stage, self-monitoring metrics, “stop the bleeding before finding the root cause” | Alert → chain-stage locator | The same alert, three completely different root causes |
| 2 | 06–13 | Scrape failures: target down, timeouts and service discovery | lastError interpretation, scrape timeout, Content-Type fallback, ServiceMonitor selection, relabel debugging,targets/relabel_steps | Scrape pipeline fault simulator | Inject connection refused / timeout / Content-Type / selector mismatch |
| 3 | 13–21 | Cardinality explosion: label design and limits | Series = label value combinations, TSDB Status,topk(count by (__name__)), churn,sample_limit, label limits, metric_relabel drops | Core animation: effect of cardinality explosion on memory and queries | user_id label explosion → sample limit exceeded → fix |
| 4 | 21–28 | Query performance: slow PromQL and dashboard optimization | Sample loading model,--query.max-samples,--query.timeout, 11,000-point limit, recording rules, query stats, dashboard anti-patterns | Query cost calculator | Before/after comparison of the same panel |
| 5 | 28–35 | TSDB internals: head block, WAL, compaction and disk | head, WAL segments and checkpoints, m-map chunks, 2h blocks, compaction levels, retention (time / size / percentage), out-of-order samples, disk full | Core animation: TSDB head / WAL / compaction | Force-kill a Pod and watch the WAL replay; read the block list and logs |
| 6 | 35–42 | Alerts not firing or alert storms | rules not loaded, window too small,for,absent(), rule evaluation failures, Alertmanager grouping / inhibition / silences, storm governance | Alert pipeline stage-by-stage checker + grouping calculator | Write an alert that “never fires” and fix it; amtool routing test |
| 7 | 42–50 | Grafana troubleshooting: data sources, panels and permissions | Request path (browser → Grafana backend → Prometheus), Query inspector, step and $__rate_interval, variables, sidecar provisioning, permissions | Panel request path tracer | Bad data source + bad variable + wrong step, fix them one by one |
| 8 | 50–60 | Mixed fault blind box | 8 kinds of faults injected at random, diagnose from symptoms only | In-browser fault blind box + interactive troubleshooting tree | fault-box.sh random |
| — | After class | Cheat sheet · Comprehensive lab | Diagnose all 8 faults one by one + produce a monitoring-system “self-monitoring and guardrails” checklist | Final quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / pages | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Eight-stage chain localization | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | up,/targets,/rules | M1 three root causes |
| Scrape and service discovery | ✓ | ✓ | · | · | · | ✓ | · | ✓ | /api/v1/targets,relabel_steps, Operator events | Four scrape faults |
| Cardinality and churn | · | · | ✓ | ✓ | ✓ | · | · | ✓ | /api/v1/status/tsdb,promtool tsdb analyze | user_id explosion |
| Limits and guardrails | · | ✓ | ✓ | ✓ | · | · | · | ✓ | sampleLimit,labelLimit,--query.max-samples | sample limit |
| Query and dashboard performance | · | · | ✓ | ✓ | · | · | ✓ | · | stats=all, recording rules,$__rate_interval | panel optimization |
| TSDB internals and disk | · | · | ✓ | · | ✓ | · | · | ✓ | promtool tsdb list -r,/status/tsdb/blocks | WAL replay |
| Alert pipeline | ✓ | · | · | · | · | ✓ | · | ✓ | amtool config routes test,ALERTS | Alert that never fires |
| Grafana troubleshooting | ✓ | · | · | ✓ | · | · | ✓ | ✓ | Query inspector, sidecar logs | Bad data source |
Content not covered in this lesson (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Prometheus architecture, metric types, PromQL basics, Grafana introduction | Basic content | Lesson 1 |
| Writing recording / alerting rules, Alertmanager routing syntax, storage planning | This lesson only covers what to do when they fail | Lesson 2 |
| Troubleshooting managed Prometheus and Grafana on Azure / AWS | Identity and quota issues of managed services | Lesson 3,Lesson 4 |
| kube-prometheus-stack installation, writing ServiceMonitor / PrometheusRule | This lesson injects faults on top of it | Lesson 5 |
| Thanos / Mimir, remote_write tuning, SLO and burn rate | Architecture-level topics | Lesson 6 |
| Pod-level troubleshooting (the Kubernetes mechanics behind CrashLoopBackOff and OOMKilled) | Belongs to Kubernetes itself | Kubernetes lesson |
| Logs and tracing: Loki, Tempo and OpenTelemetry | Lesson 8 | Lesson 8 |
| 50 production problems, 50 interview questions | Lesson 9 (optional) | Lesson 9 |
How to use this courseware
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. All labs in this course are performed on a kind cluster
lab : kps runs in monitoring, and the fault-injection target runs in faultlab. Each lab follows the cycle “inject → observe → diagnose → fix → reset”.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh when local storage is disabled).
The “Voice” page reads the lecture script aloud using the browser Web Speech API (en-US); English terms are pronounced with en-US. Without a Chinese voice pack, the lecture script is still readable.
scrape/,model/textparse/,promql/engine.go,tsdb/,web/api/v1/api.go,cmd/prometheus/main.go,cmd/promtool/) verified; on the Kubernetes side we use kube-prometheus-stack 93.3.0 (Prometheus Operator v0.95.2, Prometheus image v3.16.0-distroless, Alertmanager v0.35.0, Grafana sub-chart 14.4.1 → Grafana 13.3.1). Note: this course is written for the current official mainline Grafana 13.x as of 2026-11; the location of same-named features in 12.x may differ slightly. IPs, times, ULIDs and counts in the sample output are example values.Module 0 · Preparation: fault-injection environment
- Completed Lesson 5: kind cluster
lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoringkps is deployed, and myapp runs in namespacemyapp. This lesson does not inject faults into myapp, but creates a new namespacefaultlab, so as not to break the results of earlier lessons. - Local machine: kubectl, helm, jq, curl; Docker Desktop / Docker Engine should give kind at least 4 CPU / 6 GiB memory (the cardinality lab will push Prometheus memory up by several hundred MiB).
- You can still learn most of the content without kind: the Docker Compose environments from Lessons 1 and 2
~/promlab(servicesprometheus:9090,alertmanager:9093,grafana:3000,myapp:5000…) can complete the query, TSDB and promtool labs in Modules 3–5. In the commands, replacekubectl exec … -c prometheus --withdocker compose exec prometheusis enough (each module notes the differences separately).
Step 1: check the cluster and kps
kubectl config use-context kind-lab helm -n monitoring list kubectl -n monitoring get prometheus,alertmanager kubectl -n monitoring get pods -l 'app.kubernetes.io/name in (prometheus,alertmanager,grafana)'
Switched to context "kind-lab". NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION kps monitoring 3 ... deployed kube-prometheus-stack-93.3.0 v0.95.2 NAME VERSION DESIRED READY RECONCILED AVAILABLE AGE prometheus.monitoring.coreos.com/kps-kube-prometheus-stack-prometheus v3.16.0 1 1 True True 2d NAME VERSION REPLICAS READY RECONCILED AVAILABLE AGE alertmanager.monitoring.coreos.com/kps-kube-prometheus-stack-alertmanager v0.35.0 1 1 True True 2d NAME READY STATUS RESTARTS AGE alertmanager-kps-kube-prometheus-stack-alertmanager-0 2/2 Running 0 2d kps-grafana-6d9f8c7b9d-x2lq7 3/3 Running 0 2d prometheus-kps-kube-prometheus-stack-prometheus-0 2/2 Running 0 2d
Resource names are derived from kps' fullname: release kps + chart kube-prometheus-stack → kps-kube-prometheus-stack. Different versions or customized fullnameOverride values change the names; the variables below are all obtained via label queries, so do not hard-code them.
Step 2: set the common variables for this lesson (run once in each new terminal)
mkdir -p ~/promlab/faultlab
cat > ~/promlab/faultlab/env.sh <<'EOF'
export NS=monitoring FNS=faultlab
export PROM_POD=$(kubectl -n $NS get pod -l app.kubernetes.io/name=prometheus -o jsonpath='{.items[0].metadata.name}')
export AM_POD=$(kubectl -n $NS get pod -l app.kubernetes.io/name=alertmanager -o jsonpath='{.items[0].metadata.name}')
export PROM_CR=$(kubectl -n $NS get prometheus -o jsonpath='{.items[0].metadata.name}')
export P=http://localhost:9090 AM=http://localhost:9093 G=http://localhost:3000
# Helper function: instant query, returns JSON
pq() { curl -s --data-urlencode "query=$1" "$P/api/v1/query" | jq -c '.data.result[] | [.metric, .value[1]]'; }
EOF
source ~/promlab/faultlab/env.sh && echo "$PROM_POD / $AM_POD / $PROM_CR"
prometheus-kps-kube-prometheus-stack-prometheus-0 / alertmanager-kps-kube-prometheus-stack-alertmanager-0 / kps-kube-prometheus-stack-prometheus
Step 3: port forwarding (Prometheus 9090, Alertmanager 9093, Grafana 3000)
cat > ~/promlab/faultlab/pf.sh <<'EOF'
#!/usr/bin/env bash
# Port-forward in the background; ./pf.sh stop ends it
pkill -f 'port-forward.*(prometheus-operated|alertmanager-operated|kps-grafana)' 2>/dev/null
[ "${1:-}" = stop ] && exit 0
kubectl -n monitoring port-forward svc/prometheus-operated 9090:9090 >/dev/null 2>&1 &
kubectl -n monitoring port-forward svc/alertmanager-operated 9093:9093 >/dev/null 2>&1 &
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 >/dev/null 2>&1 &
sleep 2; curl -s localhost:9090/-/ready; curl -s localhost:9093/-/ready; echo; curl -s localhost:3000/api/health
EOF
chmod +x ~/promlab/faultlab/pf.sh && ~/promlab/faultlab/pf.sh
# Grafana admin password (randomly generated by the chart if kps does not set adminPassword)
kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d; echo
Prometheus Server is Ready.
OK
{
"database": "ok",
"version": "13.3.1",
...
}
Xq3... (random password)
prometheus-operated and alertmanager-operated are headless Services automatically created by the Operator. Their names are fixed and more stable than the kps Service names.
Step 4: deploy faultexp (an exporter with controllable faults)
faultexp is a 40-line Python standard-library HTTP service (no pip install of any package needed) that exposes /metrics, and uses environment variables to simulate real-world “bad exporters”:
| Environment variable | Default | Effect (simulated fault) |
|---|---|---|
DELAY | 0 | Seconds to sleep before each /metrics response → scrape timeout |
CT | text/plain; version=0.0.4; charset=utf-8 | Response Content-Type → Prometheus 3's strict Content-Type validation |
SERIES | 0 | Number of extra series to output with user_id label → cardinality explosion / sample limit |
CHURN | 0 | 1 = session Label values change every 30 seconds → series churn |
ERRORS | 0 | 1 = about 2 5xx responses per second (normal requests are about 5/s) → error-rate alert |
apiVersion: v1
kind: Namespace
metadata:
name: faultlab
---
apiVersion: v1
kind: ConfigMap
metadata:
name: faultexp-code
namespace: faultlab
data:
server.py: |
import os, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
START = time.time()
def body():
e = os.environ.get
up = time.time() - START
series, churn, errors = int(e("SERIES", "0")), e("CHURN", "0") == "1", e("ERRORS", "0") == "1"
out = ["# HELP faultexp_up Always 1.", "# TYPE faultexp_up gauge", "faultexp_up 1",
"# HELP faultexp_http_requests_total HTTP requests.", "# TYPE faultexp_http_requests_total counter",
'faultexp_http_requests_total{route="/api/orders",status="200"} %d' % int(up * 5),
'faultexp_http_requests_total{route="/api/orders",status="500"} %d' % (int(up * 2) if errors else 0)]
if series:
win = int(time.time() // 30)
out += ["# HELP faultexp_user_requests_total Requests per user (anti-pattern).",
"# TYPE faultexp_user_requests_total counter"]
for i in range(series):
sid = "%d-%d" % (win, i) if churn else "s%d" % i
out.append('faultexp_user_requests_total{user_id="u%d",session="%s"} 1' % (i, sid))
return ("\n".join(out) + "\n").encode()
class H(BaseHTTPRequestHandler):
def send(self, code, data, ct):
self.send_response(code)
if ct:
self.send_header("Content-Type", ct)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
try:
self.wfile.write(data)
except BrokenPipeError:
pass
def do_GET(self):
p = self.path.split("?")[0]
if p == "/healthz":
return self.send(200, b"ok\n", "text/plain")
if p != "/metrics":
return self.send(404, b"not found\n", "text/plain")
time.sleep(float(os.environ.get("DELAY", "0")))
self.send(200, body(), os.environ.get("CT", "text/plain; version=0.0.4; charset=utf-8"))
def log_message(self, *a):
pass
ThreadingHTTPServer(("", 8080), H).serve_forever()
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: faultexp
namespace: faultlab
labels: {app: faultexp}
spec:
replicas: 1
selector:
matchLabels: {app: faultexp}
template:
metadata:
labels: {app: faultexp}
spec:
containers:
- name: faultexp
image: python:3.13-alpine
command: ["python", "-u", "/app/server.py"]
ports:
- {name: http, containerPort: 8080}
readinessProbe:
httpGet: {path: /healthz, port: http}
resources:
requests: {cpu: 20m, memory: 32Mi}
limits: {memory: 256Mi}
volumeMounts:
- {name: code, mountPath: /app}
volumes:
- name: code
configMap: {name: faultexp-code}
---
apiVersion: v1
kind: Service
metadata:
name: faultexp
namespace: faultlab
labels: {app: faultexp}
spec:
selector: {app: faultexp}
ports:
- {name: http, port: 8080, targetPort: http}
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: faultexp
namespace: faultlab
labels:
release: kps # kps only selects ServiceMonitors with this label by default
spec:
selector:
matchLabels: {app: faultexp}
endpoints:
- port: http # the Service port's name, not its number
path: /metrics
interval: 15s
scrapeTimeout: 10s
sampleLimit: 5000 # guardrail: if a single scrape exceeds 5000 samples, the whole scrape fails
labelLimit: 20
labelValueLengthLimit: 200
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: faultexp-rules
namespace: faultlab
labels:
release: kps # kps default ruleSelector
spec:
groups:
- name: faultexp.rules
rules:
- record: job:faultexp_http_requests:rate5m
expr: sum by (job, status) (rate(faultexp_http_requests_total[5m]))
- alert: FaultexpDown
expr: up{job="faultexp"} == 0
for: 1m
labels: {severity: warning}
annotations:
summary: "faultexp scrape failed ({{ $labels.instance }})"
- alert: FaultexpAbsent
expr: absent(up{job="faultexp"})
for: 2m
labels: {severity: warning}
annotations:
summary: "No target with job=faultexp can be found in Prometheus"
- alert: FaultexpHighErrorRate
expr: |
sum(rate(faultexp_http_requests_total{status=~"5.."}[2m]))
/ sum(rate(faultexp_http_requests_total[2m])) > 0.1
for: 2m
labels: {severity: critical}
annotations:
summary: "faultexp 5xx ratio {{ $value | humanizePercentage }}"
source ~/promlab/faultlab/env.sh kubectl apply -f ~/promlab/faultlab/faultexp.yaml kubectl -n faultlab rollout status deploy/faultexp --timeout=120s kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- \ -si http://faultexp.faultlab:8080/metrics | head -12
namespace/faultlab created configmap/faultexp-code created deployment.apps/faultexp created service/faultexp created servicemonitor.monitoring.coreos.com/faultexp created prometheusrule.monitoring.coreos.com/faultexp-rules created deployment "faultexp" successfully rolled out HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.13.x Date: Mon, 16 Nov 2026 01:02:03 GMT Content-Type: text/plain; version=0.0.4; charset=utf-8 Content-Length: 316 # HELP faultexp_up Always 1. # TYPE faultexp_up gauge faultexp_up 1 ...
Replace the curl image tag with a version your environment can pull; any image that includes curl will do. The Operator usually writes the new ServiceMonitor into the config within 30–60 seconds, then config-reloader triggers Prometheus to reload.
Step 5: confirm the baseline (after about 1 minute)
pq 'up{job="faultexp"}'
pq 'scrape_samples_scraped{job="faultexp"}'
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | "\(.name) \(.health) \(.state)"'
[{"__name__":"up","container":"faultexp","endpoint":"http","instance":"10.244.0.37:8080","job":"faultexp","namespace":"faultlab","pod":"faultexp-7c9d5b6f4-kq2mz","service":"faultexp"},"1"]
[{"__name__":"scrape_samples_scraped",...,"job":"faultexp",...},"3"]
FaultexpDown ok inactive
FaultexpAbsent ok inactive
FaultexpHighErrorRate ok inactive
Warm-up: answer from memory (30 seconds)
up == 0 and up series does not exist, what is the difference?
up == 0 Answer: Prometheus knows the target and tries to scrape it, but the scrape fails (L4/L5). A missing series means Prometheus does not have the target at all (L2 service discovery, an L3 relabel dropped it, or the ServiceMonitor was not selected). The former can trigger an up == 0 alert, while the latter can only be caught by absent(). This is the most important distinction in this lesson.
What is the relationship between a sample and a series in Prometheus?
A series is uniquely identified by a metric name plus a set of labels; a sample is the value of a series at one point in time. Memory mainly grows with the number of active series, disk mainly grows with the number of samples, and query cost grows with “the number of selected series × the number of samples per series”.
Module 1 · Troubleshooting methodology: from alert to root cause
- Name the eight stages of the metric signal chain: L1 Expose → L2 Discovery → L3 target relabel → L4 Scrape → L5 Parse and limits → L6 Storage → L7 Query and rules → L8 Notification and presentation.
- For each stage, name at least one “observation window”: pages (
/targets,/service-discovery,/tsdb-status,/rules,/alerts), API, self-monitoring metrics or commands. - Handle an alert in five steps — “credibility → locate the stage → gather evidence → stop the bleeding → root cause and prevention” — and distinguish business faults,monitoring system faults and observation errors.
What: the eight-stage chain model
| Stage | What happens (Prometheus 3.16 components) | Typical symptoms / errors | Primary observation window |
|---|---|---|---|
| L1 Expose | The application / exporter outputs metrics in text or protobuf format on an HTTP endpoint | Endpoint returns 404 or 500, extremely slow responses, non-standard Content-Type, illegal metric names | curl -si http://target/metrics | head |
| L2 Discovery | Service discovery (kubernetes_sd endpoints / endpointslice roles) produces candidate targets; in kps the Operator first serviceMonitorSelector selects ServiceMonitors and then generates the config | Target never appears; up series does not exist | /service-discovery, Operator events, config Secret prometheus-<CR name> |
| L3 target relabel | relabel_configs (in the Operator, the relabelings) decides whether to keep or drop targets and generates job/instance and other labels | Target appears in “Dropped targets”; labels do not match expectations | /api/v1/targets?state=dropped,/api/v1/targets/relabel_steps |
| L4 Scrape | HTTP GET (with Accept negotiation), timeout scrape_timeout TLS / authentication, body size limit | up == 0; lastError is connection refused,context deadline exceeded,server returned HTTP status 401 Unauthorized,body size limit exceeded | /targets,scrape_duration_seconds |
| L5 Parse and limit | Choose the parser by Content-Type; metric_relabel_configs; sample_limit,label_limit etc. | up == 0 and lastError is sample limit exceeded,label_limit exceeded (…),received unsupported Content-Type … | scrape_samples_scraped vs scrape_samples_post_metric_relabeling,prometheus_target_scrapes_exceeded_sample_limit_total |
| L6 Storage | Write to the head block and WAL; background compaction into 2h blocks; retention and deletion | Memory spikes / OOMKilled, long WAL replay at startup, disk full, out-of-order samples dropped | /tsdb-status,prometheus_tsdb_head_series,prometheus_tsdb_compactions_failed_total |
| L7 Query and rules | PromQL engine runs instant / range queries; rule groups are evaluated according to evaluation_interval schedule | query timeouts,query processing would load too many samples into memory, rule health = err, rule-group evaluation timeout (missed iterations) | /rules,prometheus_rule_evaluation_failures_total,prometheus_rule_group_iterations_missed_total |
| L8 Notification and presentation | Alerts are sent to Alertmanager (grouping, inhibition, silences, routing, receivers); the Grafana backend proxies queries and renders panels | Alert firing but no notification received; notification storms; panel shows No data while Prometheus has the data | /alerts,amtool,prometheus_notifications_dropped_total, Grafana Query inspector |
Why: why ask whether the monitoring system can be trusted first
The same “FaultexpDown” alert may mean the business is really down (application crash), or that the monitoring system itself has a problem (Prometheus scrape timeouts, ServiceMonitor changed). Handling it directly as a “business fault” — restarting the application, rolling back the version — is not only ineffective, it also creates new changes. Conversely, if the monitoring system breaks, the most dangerous outcome is not false alarms but silence: when a target disappears from discovery, up == 0 never holds, and alerts show “all green”. So production systems must have meta-monitoring: kps' default Watchdog alert is always firing, serving as a “dead man's switch” — if the external system stops receiving it, the alert pipeline is broken.
How: five-step method
- Credibility: is Prometheus itself healthy?
up{job=~".*prometheus.*"},/-/ready, whether Watchdog is still being sent, whether rule groups are evaluated on time (prometheus_rule_group_last_evaluation_timestamp_seconds). - Locate the stage: which of L1–L8 does the symptom fall into? Key question: does the series exist? Is the value 0 or missing?
lastErrorWhat does it write? - Gather evidence: use read-only means only — pages, APIs, self-monitoring metrics, logs — save the evidence (screenshots / JSON) before changing anything.
- Stop the bleeding: business faults follow the business process; for monitoring faults, first restore visibility (for example, temporarily raise
scrapeTimeout, silence noisy alerts, and record the reason and expiry time). - Root cause and prevention: every review should leave at least one guardrail (limit, alert, CI check, documentation).
When: when to suspect “observation error”
When the data exists but “looks wrong”: rate() Extrapolation makes results fractional, a range window shorter than two scrape intervals returns empty results, and the 5-minute lookback (--query.lookback-delta default 5m) keeps targets that have already disappeared “alive” on the graph for a few minutes, a Grafana step that is too large averages out spikes, and counter resets get misread. None of these are faults; they are misunderstandings of query semantics.
Comparison of the three problem types
| Business fault | Monitoring system fault | Observation error | |
|---|---|---|---|
| Example | myapp returns 500 | Scrape timeout, ServiceMonitor not selected, TSDB OOM | Window too small, step too large, lookback ghosts |
up | Usually 1 (the application can still expose metrics) | 0 or absent | 1 |
| Who handles it | Application team | Platform / monitoring team | The person writing the query |
| First observation window | Business metrics and logs | /targets, self-monitoring metrics | Query inspector, PromQL semantics |
up == 0 ① “Alerts cover target disappearance” — no: when a target disappears its series no longer exist, so you need absent() absent() or to count targets per job. ② “A working Prometheus page means monitoring is fine” — rule groups may be skipping evaluations, scrapes may be timing out, or notification queues may be dropping alerts. ③ “Restarting Prometheus fixes most problems” — a restart triggers WAL replay (large instances can show no data for over ten minutes) and wipes out on-site evidence. ④ “If the alert did not fire, it's Alertmanager's fault” — more often the rule is not loaded at all, or the expression returns empty.Eight-stage chain and observation windows
Decision flow from alert to root cause
Interactive: symptom → chain-stage locator
Click a real symptom to see which of the eight stages it falls into, which stages are already “confirmed normal”, and which read-only diagnostic command to run next.
Read-only commands used in the five-step method
| Command / query | Stage | Description |
|---|---|---|
count by (job) (up),count by (job) (up == 0) | L2–L5 | Target count and failure count per job; comparing against the expected replica count reveals disappeared targets |
curl -s $P/api/v1/targets?state=active | jq … | L4–L5 | Each target's health,lastError,lastScrapeDuration,scrapePool |
curl -s "$P/api/v1/targets?state=dropped" | L3 | targets dropped by relabel and their discoveredLabels |
ALERTS{alertstate="firing"} | L7 | Prometheus internal alert-state series (pending / firing) |
time() - prometheus_rule_group_last_evaluation_timestamp_seconds | L7 | How long since each rule group was last evaluated (should normally be less than the evaluation interval) |
rate(prometheus_notifications_dropped_total[5m]),prometheus_notifications_alertmanagers_discovered | L8 | whether notifications sent to Alertmanager are being dropped, and how many Alertmanagers have been discovered |
kubectl -n monitoring logs $PROM_POD -c prometheus --since=15m | grep -E 'level=(WARN|ERROR)' | All | Prometheus 3 uses slog-format logs: time=… level=WARN source=… msg="…" |
source ~/promlab/faultlab/env.sh
# 1) Credibility: Prometheus itself, rule groups, notification path
pq 'up{job=~".*prometheus.*|.*alertmanager.*"}'
pq 'max by (rule_group) (time() - prometheus_rule_group_last_evaluation_timestamp_seconds) > 60'
pq 'ALERTS{alertname="Watchdog"}'
# 2) Locate the stage: target count and failing targets (including lastError)
pq 'count by (job) (up == 0)'
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.health!="up") | [.scrapePool, .labels.instance, .lastError] | @tsv'
[{"__name__":"up","job":"kps-kube-prometheus-stack-prometheus",...},"1"]
[{"__name__":"up","job":"kps-kube-prometheus-stack-alertmanager",...},"1"]
[{"__name__":"ALERTS","alertname":"Watchdog","alertstate":"firing","severity":"none"},"1"]
(the last three queries produce no output when healthy)
How to verify: After deliberately creating a fault (lab section), the same commands should point to exactly that stage. Common mistakes: In kind's kps,kube-controller-manager,kube-scheduler,kube-etcd,kube-proxy targets are often down (control-plane components only listen on 127.0.0.1). This is known environment noise, so do not let it distract you — use job to filter the targets you care about. Production use: Turn these queries into the first page of your on-call runbook, or into a “Meta-monitoring” dashboard.
Lab 1: the same “empty panel”, three root causes (about 6 min)
The symptom is uniform: the query job:faultexp_http_requests:rate5m returns no data in Grafana / Prometheus. In each round, use the five-step method to judge first, then check the answer.
kubectl -n faultlab scale deploy/faultexp --replicas=0
sleep 60
pq 'up{job="faultexp"}' # no output: series does not exist
pq 'absent(up{job="faultexp"})' # returns 1
curl -s "$P/api/v1/targets?state=active" | jq '[.data.activeTargets[] | select(.labels.job=="faultexp")] | length'
[{"job":"faultexp"},"1"]
0
Endpoints empty → SD produces no targets → no up. FaultexpDown It will never fire; only FaultexpAbsent will be firing after 2 minutes. Reset: kubectl -n faultlab scale deploy/faultexp --replicas=1.
scrapeTimeout: 10s.
kubectl -n faultlab set env deploy/faultexp DELAY=12 && kubectl -n faultlab rollout status deploy/faultexp
sleep 45
pq 'up{job="faultexp"}'
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.labels.job=="faultexp") | .lastError'
[{"__name__":"up",...,"job":"faultexp",...},"0"]
Get "http://10.244.0.41:8080/metrics": context deadline exceeded
The series exists, its value is 0, and lastError is explicit. Reset: kubectl -n faultlab set env deploy/faultexp DELAY-.
pq 'job:faultexp_http_requests:rate5m{job="faultexp-svc"}' # empty: wrong label value
pq 'count by (job) (job:faultexp_http_requests:rate5m)' # first check which jobs actually exist
pq 'rate(faultexp_http_requests_total[10s])' # empty: window shorter than two scrape intervals (15s)
(the first query produces no output)
[{"job":"faultexp"},"2"]
(the third query produces no output)
rate() The window needs at least two samples; with a 15s scrape interval the window should be ≥ 4 × 15s = 1m to be robust (in Grafana use $__rate_interval, Module 7).
Root cause | Stage | up status | Decisive evidence | Guardrail
A | L2 | missing | absent(up{job="faultexp"}) == 1 | every key job has an absent() alert
B | L4 | 0 | lastError: context deadline exceeded | scrape_duration_seconds close to timeout as an early warning
C | L7 | 1 | label value / window error | panels use $__rate_interval uniformly; queries run count by firstCase 1: all green at midnight, but monitoring had already gone blind
Problem: After a kps upgrade, the ServiceMonitor selector was changed from release: kps to another value, so all 40 business ServiceMonitors went unselected and all business targets disappeared, and up == 0 alerts naturally stayed silent; users only noticed two days later. Action: Add absent() alert and a “target count per job below expected” alert; hook Watchdog up to an external dead man's switch service. Limitation:absent() Needs to be written separately for each key job, which suits a small number of core services; at scale, use “compare the target count with the same period last week”.
Case 2: the alert storm's root cause was the monitoring system itself
Problem: On Monday morning, 300 TargetDown fired at the same time, and on-call staff started investigating business services one by one. Action: Step 1 of the five-step method showed the Prometheus Pod had just restarted after an OOM, and WAL replay took 9 minutes — during replay all targets were treated as “newly appeared”, and some rules were evaluated on incomplete data. Conclusion: Check Prometheus' own metrics first (process_start_time_seconds,prometheus_tsdb_head_series) then business; this saved an hour. The root cause was cardinality explosion (Module 3).
Case 3: the empty panel was actually a query problem
Problem: The business team reported “Prometheus is losing data”. Action: The same query has data in the Prometheus UI but not in Grafana → L8; Query inspector shows the panel used a [1m] window while Grafana's automatic step was 2m, so in some periods the window contained only one sample. Fix: Unify on $__rate_interval.
Common errors and fixes
Alert did not fire even though the target is clearly down (up returns no series at all)
Stage: L2/L3. Cause: When the target disappears, the up series vanishes entirely after the 5-minute lookback,up == 0 so the expression returns an empty set. Diagnosis:pq 'absent(up{job="faultexp"})',/service-discovery. Fix: Add a absent() alert, or count(up{job="x"}) < N.
Prometheus UI loads, but the “Last evaluation” of every rule was several minutes ago
Stage: L7. Cause: rule-group evaluation time exceeded the evaluation interval (dragged down by a slow query), or Prometheus is replaying the WAL. Diagnosis:pq 'rate(prometheus_rule_group_iterations_missed_total[5m]) > 0',pq 'prometheus_rule_group_last_duration_seconds > prometheus_rule_group_interval_seconds'. Fix: split slow rule groups and optimize expressions (Module 4).
kube-controller-manager / kube-scheduler / kube-etcd targets down on kind: connect: connection refused
Stage: L4. Cause: kubeadm by default makes these components listen only on 127.0.0.1, so Prometheus cannot reach them from the Pod network. Handling: In the lab environment you can turn off the corresponding ServiceMonitors in the kps values (kubeControllerManager.enabled=false , etc.), or change the component's --bind-address. When troubleshooting, first filter out this known noise.
Watchdog alert disappeared
Stage: L7/L8. Meaning: either the rule is not loaded (PrometheusRule selector changed), or Prometheus is not evaluating, or Alertmanager is not receiving it. Diagnosis:/rules search for Watchdog; pq 'prometheus_notifications_alertmanagers_discovered'; kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool alert query --alertmanager.url=http://localhost:9093 alertname=Watchdog. This is the strongest signal that the alert pipeline is broken, so it has the highest priority.
1. Write a query that lists the number of failing targets per job, showing only jobs that have failures.
count by (job) (up == 0)
up == 0 Keep only series whose value is 0,count by (job) — then only jobs with failing targets will appear.
2. Use one curl + jq command to print the scrapePool, instance and lastError of every unhealthy target.
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.health!="up") | [.scrapePool, .labels.instance, .lastError] | @tsv'
On call you receive 50 TargetDown alerts for different services, all triggered in the same minute. What are your first three actions?
① Judge credibility: many targets going down at the same time usually share a common cause — Prometheus itself (restart / OOM / network policy), a node, DNS, or an Operator config change. First look at process_start_time_seconds{job=~".*prometheus.*"}, Prometheus logs and recent changes (Helm history, GitOps commits). ② Check whether lastError is consistent: if they are all context deadline exceeded pointing to Prometheus-side resources / network; if they are all connection refused pointing to the target side or a NetworkPolicy. ③ Stop the bleeding: once the common cause is confirmed, use one broad silence to hold back the storm (with reason and expiry time), and deal with the common cause centrally rather than investigating service by service.
Verified teaching videos
Official documentation
Video storyboard script (about 90 seconds)
Visual: a phone pops up the alert “FaultexpDown”; the camera pulls back to reveal a chain of eight blocks.
Narration: the alert is only a symptom; it may come from any stage of the chain.
Visual: three side-by-side terminals showing up missing, up = 0, up = 1; the matching block lights up for each.
Narration: ask one question first — does up exist, and what is its value? The answer tells you the stage directly.
Visual: the Watchdog heartbeat line keeps beating, then suddenly flattens, and an external dead man's switch sounds an alarm.
Narration: the most dangerous thing when the monitoring system breaks is silence, so monitor the monitoring itself.
Visual: the five-step checklist ticks off item by item: credibility, locate the stage, gather evidence, stop the bleeding, root cause and guardrail.
Narration: every troubleshooting session should leave at least one guardrail behind.
Module 2 · Scrape failures: target down, timeouts and service discovery
- Describe the internal steps of one scrape and the synthetic series it produces:
up,scrape_duration_seconds,scrape_samples_scraped,scrape_samples_post_metric_relabeling, andscrape_series_added. - Map common lastError messages to root causes:
connection refused,no such host,context deadline exceeded,server returned HTTP status 401/403/404,body size limit exceeded,received unsupported Content-Type …, andnon-compliant scrape target sending blank Content-Type …. - In kps, check the ServiceMonitor selection chain level by level: Prometheus CR selector → ServiceMonitor → Service label → Service port name → Endpoints (ready Pods).
- Use
/api/v1/targets?state=droppedand/api/v1/targets/relabel_stepsto debug relabel.
What: what happens internally during one scrape (v3.16.0 scrape/scrape.go)
- Scheduling: each target has its own scrape loop, running every
scrape_intervalperiod; the start offset is determined by hashing the target's labels (to avoid scraping all targets at once). - Request: HTTP GET, with the
Acceptheader, negotiated byscrape_protocols(default: OpenMetrics 1.0.0 → OpenMetrics 0.0.1 → Prometheus text 1.0.0 → text 0.0.4); the whole request is bounded byscrape_timeout(default 10s, and must not exceedscrape_interval, otherwise config loading reportsscrape timeout greater than scrape interval for scrape config with job name "…"). - Response check: status code not 200 →
server returned HTTP status 404 Not Found; body exceedsbody_size_limit→body size limit exceeded. - Choose parser: Prometheus 3 strictly selects the parser by
Content-Type. If the value is empty or unrecognized and nofallback_scrape_protocolis configured, the whole scrape fails. - Parse + metric relabel + limits: run every sample through
metric_relabel_configs, checklabel_limit,label_name_length_limit,label_value_length_limit; if the cumulative sample count exceedssample_limitthen the whole scrape is rolled back. - Write: commit to the TSDB. On a failed scrape, an empty body is appended once more, writing a stale marker to the series that existed last time, so a failed target's metrics break off on the graph immediately instead of “continuing for 5 minutes”.
- Report: write synthetic series
up(success 1 / failure 0),scrape_duration_seconds,scrape_samples_scraped,scrape_samples_post_metric_relabeling,scrape_series_added; enablingextra_scrape_metrics(in 3.x it is a config option; the old--enable-feature=extra-scrape-metricsis being phased out) also gives youscrape_timeout_seconds,scrape_sample_limit,scrape_body_size_bytes.
lastError quick reference (error text from v3.16.0 source or the Go standard library)
| lastError (original text) | Stage | Root cause | Fix direction |
|---|---|---|---|
Get "http://10.244.0.37:8081/metrics": dial tcp 10.244.0.37:8081: connect: connection refused | L4 | No process listening on the port: wrong targetPort, container not listening, only listening on 127.0.0.1 | Check Service targetPort and container ports; ss -lntp |
… dial tcp: lookup x on 10.96.0.10:53: no such host | L4 | Static target / DNS SD has a wrong hostname | correct the address, or switch to Kubernetes SD |
… context deadline exceeded | L4 | Response time > scrape_timeout: exporter is slow (queries the backend live on every scrape), too many metrics, network packet loss, NetworkPolicy silently dropping packets | Look at scrape_duration_seconds trend; optimize the exporter (caching); raise the timeout if necessary (≤ interval) |
server returned HTTP status 401 Unauthorized / 403 Forbidden | L4 | Authentication required (kubelet, protected endpoints) or insufficient RBAC | Configure in the ServiceMonitor authorization/bearerTokenSecret/TLS; check RBAC |
server returned HTTP status 404 Not Found | L1/L4 | path Wrong (/metrics vs /actuator/prometheus) | Correct path |
body size limit exceeded | L4 | Response exceeds body_size_limit (Operator: bodySizeLimit / enforcedBodySizeLimit) | Reduce metrics; confirm the limit is reasonable |
received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target | L5 | The exporter returned a non-standard Content-Type (Prometheus 2.x silently parses it as text, 3.x rejects it) | Fix the exporter; or set fallback_scrape_protocol: PrometheusText0.0.4 (Operator: fallbackScrapeProtocol) |
non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for target | L5 | Response has no Content-Type header | Same as above |
sample limit exceeded | L5 | Samples per scrape > sample_limit | Module 3 |
label_limit exceeded (metric: …, number of labels: 23, limit: 20) | L5 | A series exceeds the label count limit | Module 3 |
Why: the selection chain behind a target not appearing in kps
In the Operator setup, “why a target does not appear” is more common than “why a target is down”. Every stage of this chain is a silent failure— no error is reported, the target is simply absent:
- The Prometheus CR's
serviceMonitorSelector(kps defaultserviceMonitorSelectorNilUsesHelmValues: true→ selects onlyrelease: kps) andserviceMonitorNamespaceSelector(kps default{}= all namespaces). - ServiceMonitor
spec.selectormust match Service labels (not the Pod's labels), andnamespaceSelectorby default looks only at the ServiceMonitor's own namespace. - The endpoint's
portis the Service port's name (the Operator's official troubleshooting docs stress that port names are optional in Kubernetes but a ServiceMonitor needs them); you can also usetargetPort(not officially recommended). - The Service must have ready Endpoints (if a Pod's readiness probe fails, it is not in Endpoints and is not a target).
- Prometheus's ServiceAccount needs get / list / watch permissions on services, endpoints (or endpointslices) and pods in the target namespace — kps grants a ClusterRole by default.
How: two-step triage
Target is in /targets and down → read lastError (L4/L5). Target is not in → check in order: is the ServiceMonitor in the generated config (L2-Operator) → has it been discovered /service-discovery (L2-SD) → is it in the dropped list (L3)? The Operator rejects invalid ServiceMonitors and emits a Kubernetes Event, and kps also has PrometheusOperatorRejectedResources an alert.
When: when is raising scrape_timeout the right thing to do?
Only when the exporter is inherently slow (for example, every scrape queries a database, or a blackbox probe reaches a remote endpoint) and the data is worth waiting for; and the timeout must be ≤ interval. Better options are to have the exporter cache results, split the job, or lower the frequency. Do not raise the timeout of every job — that hides network and NetworkPolicy problems.
Comparison: target down vs. target does not exist
| Target down | Target does not exist | |
|---|---|---|
up | 0 | No series |
| /targets | Red, has lastError | Does not appear (may be in dropped) |
| Usable alert: | up == 0, kps' TargetDown | absent(up{job="x"}), drop in target count |
| Common stages | L4, L5 | L2, L3 |
port: 8080 can also be a number” —port the field is a port-name string. ② “The selector matches Pod labels” — it actually matches the Service's labels. ③ “After upgrading to Prometheus 3, the exporter suddenly goes down, so it's a network problem” — most likely the strict Content-Type check. ④ “Old data continues for 5 minutes after a failed scrape” — on failure a stale marker is written and the curve breaks immediately; only when the target disappears does a lookback ghost appear (at the very moment the target disappears a stale marker is also written, but if Prometheus restarts and misses that moment, the value simply expires via lookback).Scrape pipeline and failure points
kps ServiceMonitor selection chain
Interactive: scrape pipeline fault simulator
Select an injected fault and step through one scrape: each step shows what Prometheus actually does; at the failure point the original error text from the v3.16.0 source is shown, along with the final up and the synthetic metrics.
Core commands
| Command | Stage | Description |
|---|---|---|
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | L4–L5 | Filter by scrape pool; the kps pool name is serviceMonitor/<ns>/<name>/<endpoint index> |
curl -s "$P/api/v1/targets?state=dropped" | L3 | Dropped targets; by default only some are kept (keep_dropped_targets / Operator keepDroppedTargets ) to control the count |
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode scrapePool=… --data-urlencode labels='{…}' | L3 | Runs each relabel rule against the given discovery labels, returning the rule,output,keep |
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | L2 | the full config generated by the Operator (the method in the official troubleshooting docs) |
kubectl get events -A --field-selector involvedObject.kind=ServiceMonitor | L2 | Events emitted when the Operator rejects an illegal resource |
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | tail | L2 | Operator reconciliation log |
kubectl -n faultlab get endpointslices -l kubernetes.io/service-name=faultexp | L2 | Whether the Service has ready endpoints behind it |
source ~/promlab/faultlab/env.sh
# 1) Target status (including scrape duration and lastError)
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" \
| jq '.data.activeTargets[] | {instance: .labels.instance, health, lastError, lastScrapeDuration, scrapeInterval, scrapeTimeout}'
# 2) Whether this ServiceMonitor is in the generated config
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' \
| base64 -d | gunzip | grep -n 'job_name: serviceMonitor/faultlab/'
{
"instance": "10.244.0.37:8080",
"health": "up",
"lastError": "",
"lastScrapeDuration": 0.003121,
"scrapeInterval": "15s",
"scrapeTimeout": "10s"
}
412:- job_name: serviceMonitor/faultlab/faultexp/0
relabel step-by-step debugging (L3)
POOL=serviceMonitor/faultlab/faultexp/0
LBL=$(curl -s "$P/api/v1/targets?state=any&scrapePool=$POOL" | jq -c '(.data.activeTargets + .data.droppedTargets)[0].discoveredLabels')
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode "scrapePool=$POOL" --data-urlencode "labels=$LBL" \
| jq -r '.data.steps[] | "\(.rule.action)\t\(.rule.source_labels // [] | join(","))\tkeep=\(.keep)"' | head -12
keep __meta_kubernetes_service_label_app keep=true keep __meta_kubernetes_endpoint_port_name keep=true replace __meta_kubernetes_namespace keep=true ...
How to verify: After the problematic rule keep=false. Common mistakes:labels The argument must be a JSON object (discovery labels, including __meta_*). Production use: Before changing relabel rules, rehearse with relabel_steps on real labels. In addition, Prometheus 3 supports scrape_failure_log_file (kps: prometheus.prometheusSpec.scrapeFailureLogFile) writing each scrape failure to a file, which suits forensics on intermittent failures.
Verify L1 directly from inside the cluster (bypassing Prometheus)
kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- \
-s -o /dev/null -w 'code=%{http_code} ct=%{content_type} time=%{time_total}s size=%{size_download}\n' \
http://faultexp.faultlab:8080/metrics
code=200 ct=text/plain; version=0.0.4; charset=utf-8 time=0.004s size=316
Lab 2: four scrape faults (about 8 min)
kubectl -n faultlab patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8081}]'
sleep 40
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
down Get "http://10.244.0.37:8081/metrics": dial tcp 10.244.0.37:8081: connect: connection refused
Reset: kubectl -n faultlab patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":"http"}]'. Note the instance label has also changed to :8081 — the target address comes from the port in Endpoints.
kubectl -n faultlab set env deploy/faultexp CT=application/octet-stream && kubectl -n faultlab rollout status deploy/faultexp sleep 40 curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
down received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target
Two fixes: prefer fixing the exporter (kubectl -n faultlab set env deploy/faultexp CT-); if a third-party exporter cannot be changed, set the fallback protocol on the ServiceMonitor:
kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"fallbackScrapeProtocol":"PrometheusText0.0.4"}}'
sleep 60; pq 'up{job="faultexp"}'
kubectl -n monitoring logs $PROM_POD -c prometheus --since=2m | grep -i 'content type' | tail -1
[{"__name__":"up",...,"job":"faultexp",...},"1"]
(the "Invalid content type on scrape, using fallback setting." log only appears at DEBUG level; it is hidden at the default INFO level)
Reset: kubectl -n faultlab set env deploy/faultexp CT-, and kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/fallbackScrapeProtocol"}]'.
release label.
kubectl -n faultlab label servicemonitor faultexp release-
sleep 60
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -c 'serviceMonitor/faultlab/faultexp' || true
pq 'absent(up{job="faultexp"})'
kubectl -n monitoring get prometheus $PROM_CR -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}'
0
[{"job":"faultexp"},"1"]
{"matchLabels":{"release":"kps"}}
No error is reported — only targets disappear. Reset: kubectl -n faultlab label servicemonitor faultexp release=kps.
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"add","path":"/spec/endpoints/0/relabelings","value":[{"sourceLabels":["__meta_kubernetes_pod_label_app"],"regex":"fault-exp","action":"keep"}]}]'
sleep 60
curl -s "$P/api/v1/targets?state=dropped" | jq -r '.data.droppedTargets[] | select(.discoveredLabels.__meta_kubernetes_service_name=="faultexp") | .discoveredLabels.__meta_kubernetes_pod_label_app' | head -3
faultexp
The discovery label value is faultexp, and the regex fault-exp does not match (the relabel regex is fully anchored). The relabel_steps command above shows what is left after this keep rule keep=false. Reset: kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/endpoints/0/relabelings"}]'. If the dropped list is empty, it may be due to the retention limit on dropped targets; verify with relabel_steps instead.
Case 1: after upgrading to Prometheus 3, all three old exporters went down
Problem: On the day of the upgrade from 2.x to 3.x, one in-house exporter (hand-written HTTP, no Content-Type set) and two third-party exporters (returning text/html) all went down. Action: lastError states the cause directly; fix the in-house exporter to send text/plain; version=0.0.4; for the third-party ones, add fallbackScrapeProtocol: PrometheusText0.0.4 on the ServiceMonitor and file an upstream issue. Lesson: Before upgrading, scrape all targets with 3.x in a pre-production environment and compare up.
Case 2: intermittent context deadline exceeded
Problem: A database exporter timed out a few times per hour. Action: Plot max_over_time(scrape_duration_seconds{job="db"}[1h]), found that scrape duration rose to 12 seconds during the on-the-hour backup — the exporter runs a slow query on every scrape. Fix: enable result caching in the exporter, and move the slow-query metrics into a separate job (interval 2m, timeout 60s). Limitation: After splitting, the labels of the two jobs must be consistent, otherwise the panel queries have to change.
Case 3: NetworkPolicy causes timeouts for targets on “only some nodes”
Problem: After a default-deny NetworkPolicy was enabled on a new namespace, all targets context deadline exceeded (packets were silently dropped, so it is not connection refused). Fix: Allow inbound traffic to the metrics port from the monitoring namespace and the Prometheus Pod labels. Lesson: refused = someone explicitly rejected it; deadline = nobody responded (packet loss, overload, or a hang).
Common errors and fixes
scrape timeout greater than scrape interval for scrape config with job name "…"
Stage: config loading. Cause:scrape_timeout > scrape_interval (v3.16.0 config/config.go validation). In the Operator, such a config is rejected or causes the reload to fail. Diagnosis:kubectl -n monitoring logs $PROM_POD -c config-reloader,pq 'prometheus_config_last_reload_successful'. Fix: timeout ≤ interval.
ServiceMonitor exists, but nothing appears in /targets
Diagnosis order:① grep the config Secret for serviceMonitor/<ns>/<name>: none → selector labels / namespace selector / Operator rejection (kubectl get events -n <ns> --field-selector involvedObject.name=<sm>). ② If present → kubectl get svc -l <selector> whether it matches a Service and whether the port names agree. ③ kubectl get endpointslices -l kubernetes.io/service-name=<svc> whether there are ready endpoints. ④ dropped targets / relabel_steps.
Get "http://…/metrics": context deadline exceeded
Diagnosis:pq 'max_over_time(scrape_duration_seconds{job="X"}[30m])' Check whether it is close to the timeout; time a curl inside the cluster (see command pages); check NetworkPolicy. Fix: optimize the exporter, split jobs, fix the network; only as a last resort raise the timeout.
server returned HTTP status 403 Forbidden (kubelet / cAdvisor targets)
Cause: The Prometheus ServiceAccount lacks nodes/metrics and similar permissions, or kubelet has not enabled webhook authentication (the Operator troubleshooting docs list how to handle kubelet 403). Diagnosis:kubectl auth can-i get nodes/metrics --as=system:serviceaccount:monitoring:kps-kube-prometheus-stack-prometheus.
received unsupported Content-Type "text/html; charset=utf-8" and no fallback_scrape_protocol specified for target
Cause: Most likely path points to an HTML page (a login page or the default home page) rather than a metrics endpoint, or the exporter is non-compliant. Diagnosis: Use curl inside the cluster to look at the first few lines of the body. Fix: correct the path; only after confirming it is a compliance issue, use fallbackScrapeProtocol.
Target up = 1, but some metrics are “occasionally missing”, and the log shows Error on ingesting out-of-order samples
Cause: two targets expose exactly the same series (for example honor_labels: true and two replicas emit identical labels), or the exporter carries its own timestamps and time goes backwards. Diagnosis:pq 'rate(prometheus_target_scrapes_sample_out_of_order_total[5m]) > 0',prometheus_target_scrapes_sample_duplicate_timestamp_total. Fix: ensure each target's label set is unique (do not casually honor_labels), and remove the timestamps the exporter emits.
1. Find targets whose scrape duration in the last 30 minutes exceeds 80% of the timeout (assuming a uniform timeout of 10s).
max_over_time(scrape_duration_seconds[30m]) > 8
Enable extra_scrape_metrics and it can then be written in general form: max_over_time(scrape_duration_seconds[30m]) / scrape_timeout_seconds > 0.8.
2. Without relying on the Prometheus UI, confirm whether the ServiceMonitor faultlab/faultexp was written into the generated config.
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -n 'serviceMonitor/faultlab/faultexp'A newly launched service's ServiceMonitor has been created and its Pods run normally, but it is not in /targets, and the Operator logs show no error. Give the troubleshooting order and the command for each step.
① Selector: kubectl get prometheus -n monitoring -o jsonpath='{..serviceMonitorSelector}' against the ServiceMonitor's labels (the most common miss: missing release: kps). ② Config: decode the prometheus-<CR> Secret and grep for the job name. ③ Service: kubectl get svc -n app -l <sm's selector>; check whether the port name equals endpoints[].port. ④ Endpoints: kubectl get endpointslices -l kubernetes.io/service-name=…, check whether the Pod is Ready (a Pod whose readiness probe fails is not in the endpoints). ⑤ relabel: dropped targets or relabel_steps. ⑥ RBAC: if Prometheus has only been granted permissions in specific namespaces, SD logs forbidden. When every stage reports no error, this is exactly the reason to use absent() as a backstop.
Verified teaching videos
Official docs
- scrape_config (scrape_timeout, sample_limit, fallback_scrape_protocol)
- Prometheus 3.0 migration guide (strict Content-Type validation)
- Operator Troubleshooting · ServiceMonitor changes
- HTTP API · targets
Video storyboard (about 100 seconds)
Visual: a “scrape parcel” travels along a conveyor belt past six checkpoints: SD, relabel, GET, Content-Type, limits and write.
Narration: every scrape has to clear these checkpoints. If any one fails, up drops to zero, or the target simply disappears.
Visual: four faults appear in turn: connection refused, deadline exceeded, unsupported Content-Type, sample limit exceeded. Each one lights a red light at its checkpoint.
Narration: lastError is the diagnostic report Prometheus writes for you.
Visual: the five-stage ServiceMonitor selection chain. The first-stage label does not match, so every stage after it turns grey, with no error shown.
Narration: a target disappearing is a silent failure. You can only confirm it stage by stage, or fall back on an absent alert.
Visual: relabel_steps output expands line by line, and one keep line turns into false.
Narration: don't guess with relabel. Let Prometheus walk you through it step by step.
Module 3 · Cardinality explosion: label design and limits
- Explain cardinality: the number of series for a metric equals the number of label-value combinations that actually occur, with an upper bound of the product of each label's number of values. Understand why churn (series constantly being created and then expiring) hurts memory more than “stable high cardinality”.
- Find the culprit with three methods: the TSDB Status page /
/api/v1/status/tsdb, PromQL (topk(10, count by (__name__)({__name__=~".+"})),scrape_series_added),promtool tsdb analyze. - Configure guardrails:
sample_limit(exceeding it fails the whole scrape),label_limit/label_name_length_limit/label_value_length_limit,target_limit, plus the Operator'senforcedSampleLimitother global limits. - Stop the bleeding and fix the root cause:
metric_relabel_configsDrop metrics or labels (watch out for the trap of dropping a distinguishing label), and fix the instrumentation.
What: series, cardinality and churn
In Prometheus, one series is uniquely identified by the metric name plus all of its labels. myapp_http_requests_total{method,route,status} If there are 4 methods, 30 routes and 6 statuses, multiplied by 10 Pods (the target label pod,instance), the upper bound is 4 × 30 × 6 × 10 = 7 200 series. If someone adds user_id (100 000 users), the upper bound becomes 720 million. That is a cardinality explosion.
| Concept | Meaning | Main impact |
|---|---|---|
| Active series (head series) | Number of series currently in the head block prometheus_tsdb_head_series | Memory (each series in the head has a memSeries struct, label strings, inverted-index entries and the current chunk) |
| Samples per scrape | scrape_samples_scraped (one sample per series per scrape) | CPU, WAL writes,sample_limit |
| churn (series turnover) | Series are created and soon stop appearing (label values include time, session, Pod name, request ID) | The head keeps many inactive but unreclaimed series until GC after head compaction; the WAL grows and replay gets slower |
| Query cardinality | Number of series selected by one query | Query latency and memory (Module 4) |
Why: why cardinality can “crush” Prometheus
- Memory: every series in the head stays resident in memory. As a rule of thumb, each active series costs a few KiB (labels, index, chunk buffers); for real numbers, measure your own instance
process_resident_memory_bytes / prometheus_tsdb_head_series. Going from 500 000 to 5 million series can take memory from 3 GiB to 30 GiB and get the process OOMKilled. - churn amplification: the head covers about 2–3 hours by default (Module 5). If label values are replaced every 30 seconds, then even if only 1 000 series are “current”, the head accumulates 1 000 × 360 = 360 000 series within 3 hours.
- Slower restarts: the WAL records the creation of every series, and replay time is proportional to the number of series and samples. OOM → restart → OOM again during replay is a classic death loop.
- Slower queries:
sum(rate(x[5m]))every matching series must be read, and the postings lists in the inverted index get longer too. - Downstream cost: when remote_write-ing to Mimir / AMP / Azure Monitor, costs are usually billed by sample count or active series (Lessons 3, 4 and 6).
How: three ways to find the culprit
| Method | What to look at | Advantages | Caveats |
|---|---|---|---|
TSDB Status page (/tsdb-status) or /api/v1/status/tsdb?limit=N | headStats (numSeries, chunkCount, minTime/maxTime),seriesCountByMetricName,labelValueCountByLabelName,memoryInBytesByLabelName,seriesCountByLabelValuePair | reads the head's inverted-index statistics directly, very cheap | only reflects the head (roughly the last 2–3 hours); limit default 10, max 10000 |
| PromQL | topk(10, count by (__name__)({__name__=~".+"})),topk(10, sum by (job) (scrape_series_added)),count(count by (user_id) (x)) | can be split by job and namespace; can be charted as a trend | The first one selects all series, which is itself a heavy query; be careful on large instances (it may trigger max-samples) |
promtool tsdb analyze | churn labels, the most common label pairs, and the highest-cardinality labels and metrics in persisted blocks | can show the labels with the worst churn | analyzes on-disk blocks (the last one by default); on a new instance with no blocks yet, it errors out |
How: guardrails (verbatim v3.16.0 error messages)
| Configuration (scrape_config / ServiceMonitor fields) | When exceeded | lastError |
|---|---|---|
sample_limit / sampleLimit | the whole scrape is rolled back, up = 0, and existing series get stale markers written | sample limit exceeded |
label_limit / labelLimit | the whole scrape fails | label_limit exceeded (metric: …, number of labels: N, limit: M) |
label_name_length_limit | the whole scrape fails | label_name_length_limit exceeded (metric: …, label name: …, length: N, limit: M) |
label_value_length_limit | the whole scrape fails | label_value_length_limit exceeded (metric: …, label name: …, value: "…", length: N, limit: M) |
target_limit / targetLimit | all targets in that scrape pool are not scraped | target_limit exceeded (number of targets: N, limit: M) |
Operator: enforcedSampleLimit,enforcedLabelLimit,enforcedTargetLimit,enforcedBodySizeLimit (Prometheus CR) | enforces one cap on all ServiceMonitor/PodMonitor objects (the smaller value wins), so a team cannot bypass the limit. kps: prometheus.prometheusSpec.enforcedSampleLimit | |
sample_limit The “fail the whole scrape” design is deliberate: it is better to let one target sit at up = 0 and fire an alert than to let it quietly eat the whole Prometheus. The corresponding counter is prometheus_target_scrapes_exceeded_sample_limit_total.
When: label design rules
- Label values must be bounded small sets: method, route templates (
/orders/{id}rather than/orders/123), status classes (or exact codes), region. - Never use as labels: user_id, email, request_id / trace_id, full URLs, SQL text, timestamps, full error messages. These belong in logs, traces or exemplars.
- Histogram buckets are series too:
le12 values means 12 times the series. The unified myapp buckets from Lesson 1 (0.005…5) are a deliberate limit; Native Histograms can greatly reduce these series.
sample_limit solves it” — that just puts a bomb in the house. ② “Using labeldrop labeldrop to drop user_id is enough” — if user_id is the only label that tells series apart, dropping it makes several series share one identical label set: equal values get silently merged, and different values trigger duplicate-sample drops, so the data is no longer correct. The right fix is to aggregate at the source or drop the whole metric. ③ “Prometheus memory depends only on the current number of targets” — series left behind by churn occupy memory until head compaction. ④ “TSDB Status shows all history” — it only shows the head.Multiplying label values: how one label makes series explode
What one series occupies in the head
Key animation: how cardinality explosion affects memory and queries
Adjust label value counts and churn, and watch three things change: ① samples per scrape and sampleLimit; ② series accumulated in the head and the memory estimate; ③ samples loaded by one panel query and --query.max-samples (default 50 000 000). The “Timeline” button plays a real incident step by step: release → series spike → memory rises → sample limit takes effect or OOM → fix.
Key commands and queries
| Command / query | Purpose |
|---|---|
curl -s "$P/api/v1/status/tsdb?limit=5" | jq .data | head stats + four Top lists (limit defaults to 10, max 10000) |
prometheus_tsdb_head_series,rate(prometheus_tsdb_head_series_created_total[5m]) | active series and creation rate (direct signal of churn) |
topk(10, sum by (job) (scrape_series_added)) | which job creates new series on every scrape (churn source) |
topk(10, max by (job) (scrape_samples_scraped)) | which job has the most samples in a single scrape |
topk(10, count by (__name__)({__name__=~".+"})) | metric names with the most series (heavy query, use with care) |
count(count by (user_id) (faultexp_user_requests_total)) | number of values of a given label |
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=10 | analyzes churn and cardinality of the last persisted block |
sum(increase(prometheus_target_scrapes_exceeded_sample_limit_total[1h])) | number of times sample_limit took effect |
source ~/promlab/faultlab/env.sh
curl -s "$P/api/v1/status/tsdb?limit=5" | jq '{head: .data.headStats,
topMetrics: .data.seriesCountByMetricName,
topLabelValues: .data.labelValueCountByLabelName,
topLabelMemory: .data.memoryInBytesByLabelName}'
{
"head": {"numSeries": 61234, "numLabelPairs": 9812, "chunkCount": 132011, "minTime": 1763251200000, "maxTime": 1763258405123},
"topMetrics": [
{"name": "apiserver_request_duration_seconds_bucket", "value": 7920},
{"name": "etcd_request_duration_seconds_bucket", "value": 5544}, ...],
"topLabelValues": [{"name": "__name__", "value": 1820}, {"name": "id", "value": 410}, ...],
"topLabelMemory": [{"name": "__name__", "value": 72310}, ...]
}
How to read it: The apiserver / etcd histograms that kps collects by default are often the largest metrics in the baseline. That is why many teams drop some buckets in their kps values. Common mistakes: Running it frequently on large instances count by (__name__) full-scan queries; use TSDB Status instead.
Stop the bleeding: drop the whole metric on the ServiceMonitor
spec:
endpoints:
- port: http
metricRelabelings:
- sourceLabels: [__name__]
regex: faultexp_user_requests_total
action: drop
Global guardrail: kps values
prometheus:
prometheusSpec:
enforcedSampleLimit: 50000 # No ServiceMonitor's sampleLimit may exceed this
enforcedLabelLimit: 30
enforcedLabelValueLengthLimit: 512
enforcedTargetLimit: 500
in kps 93.3.0 values enforcedSampleLimit the default is false (disabled). Once set, the Operator takes min(own sampleLimit, enforced) for every ServiceMonitor, and ServiceMonitors without a sampleLimit are limited too.
promtool: analyzes on-disk blocks (also works in the Compose environment)
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=5 # Compose (Lesson 1 ~/promlab; the image's data directory is also /prometheus): # cd ~/promlab && docker compose exec prometheus promtool tsdb analyze /prometheus --limit=5
BLOCK ULID MIN TIME MAX TIME DURATION NUM SAMPLES NUM CHUNKS NUM SERIES SIZE 01JD… 1763229600000 1763236800000 2h0m0s 9102330 140211 60120 12MiB Block ID: 01JD… Duration: 2h0m0s Total Series: 60120 Label names: 212 Postings (unique label pairs): 9750 Postings entries (total label pairs): 512330 Label pairs most involved in churning: 1830 session=1763235570-17 ... Highest cardinality labels: 8000 user_id ... Highest cardinality metric names: 8000 faultexp_user_requests_total
kps uses prometheus:v3.16.0-distroless image: has promtool but no shell (kubectl exec … -- sh will fail). You need du,ls when needed, use kubectl debug an ephemeral container, or switch to /api/v1/status/tsdb/blocks and prometheus_tsdb_* metrics. An instance installed less than about 3 hours ago has no persisted blocks yet, so analyze will fail because it can't find any.
Lab 3: user_id label explosion → sample limit → fix (about 8 minutes)
pq 'prometheus_tsdb_head_series'
pq 'process_resident_memory_bytes{job=~".*prometheus"} / 2^20'
[{"__name__":"prometheus_tsdb_head_series",...},"61234"]
[{...,"job":"kps-kube-prometheus-stack-prometheus",...},"412.6"]kubectl -n faultlab set env deploy/faultexp SERIES=8000 && kubectl -n faultlab rollout status deploy/faultexp
sleep 45
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'increase(prometheus_target_scrapes_exceeded_sample_limit_total[2m])'
down sample limit exceeded
[{...,"job":"faultexp",...},"8003"]
[{...},"8"]
scrape_samples_scraped It still reports the real sample count (source comment: parsing continues past the limit so the correct total is reported), but not a single sample is written. FaultexpDown will go from pending to firing after 1 minute. The guardrail worked: Prometheus's head did not grow.
kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"sampleLimit":20000}}'
sleep 75
pq 'up{job="faultexp"}'
pq 'prometheus_tsdb_head_series'
curl -s "$P/api/v1/status/tsdb?limit=3" | jq -c '.data.seriesCountByMetricName, .data.labelValueCountByLabelName'
pq 'count(count by (user_id) (faultexp_user_requests_total))'
[{...},"1"]
[{"__name__":"prometheus_tsdb_head_series",...},"69241"]
[{"name":"faultexp_user_requests_total","value":8000},{"name":"apiserver_request_duration_seconds_bucket","value":7920},...]
[{"name":"user_id","value":8000},{"name":"session","value":8000},{"name":"__name__","value":1821}]
[{},"8000"]kubectl -n faultlab set env deploy/faultexp SERIES=1000 CHURN=1 && kubectl -n faultlab rollout status deploy/faultexp sleep 180 pq 'rate(prometheus_tsdb_head_series_created_total[2m])' pq 'topk(3, sum by (job) (scrape_series_added))' pq 'prometheus_tsdb_head_series'
[{...},"33.6"]
[{"job":"faultexp"},"1000"]
[{...},"75890"]
Each scrape currently has only 1000 series, but each one is new series: the head series count keeps rising until the next head compaction + GC brings it down. With a 15s scrape interval and a 30s session window, every other scrape is scrape_series_added equal to 1000 (the other is 0). A series_added value that never drops to zero is the fingerprint of churn; use sum_over_time(scrape_series_added[5m]) to see a smoother view.
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"add","path":"/spec/endpoints/0/metricRelabelings","value":[{"sourceLabels":["__name__"],"regex":"faultexp_user_requests_total","action":"drop"}]}]'
sleep 60
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'scrape_samples_post_metric_relabeling{job="faultexp"}'
# Root-cause fix + reset
kubectl -n faultlab set env deploy/faultexp SERIES- CHURN-
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/endpoints/0/metricRelabelings"}]'
kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"sampleLimit":5000}}'
[{...},"1003"]
[{...},"3"]
scrape_samples_scraped and scrape_samples_post_metric_relabeling is the number of samples dropped by metric relabeling. Note: metric relabeling happens after the scrape, the exporter still generates this data and the network still transmits it. It is a stop-gap, not a cure. Series already in the head only free their memory after head compaction.
Case 1: a path label makes Prometheus OOM every day
Problem: A service used the raw URL (including order numbers) as a path label. Head series grew from 800 000 to 9 million, Prometheus kept getting OOMKilled, and after each restart the WAL replay ran for 20 minutes before it OOMed again. Approach:① Temporary: add to the ServiceMonitor metricRelabelings to drop the metric, and temporarily raise the Prometheus memory limit so the replay can finish; ② Root-cause fix: change the instrumentation to use route templates; ③ Guardrails: set in kps enforcedSampleLimit, and set on each ServiceMonitor sampleLimit; add an alert rate(prometheus_tsdb_head_series_created_total[10m]) that fires when the count exceeds 3× the baseline.
Case 2: cardinality of Kubernetes' own metrics
Problem: The kps default collection of apiserver_request_duration_seconds_bucket,etcd_request_duration_seconds_bucket make up 30% of the series in a large cluster. Approach: In the kps values, add a drop to the kubeApiServer / kubeEtcd ServiceMonitors metricRelabelings for unused buckets or whole metrics (first confirm no dashboard or rule depends on them); use promtool tsdb analyze for a weekly review. Limitation: Some rules and dashboards that ship with kps depend on these metrics, so before dropping any, confirm with Grafana “Explore → Metrics” or grep the rule files.
Case 3: remote_write bill doubles
Problem: The monthly bill for a managed Prometheus service (billed per sample) doubled. Approach: Compare seriesCountByMetricName in the local TSDB Status with usage on the managed side, and pinpoint a new exporter's histogram (60 buckets per Pod × 200 routes). In write_relabel_configs the remote_write config, send only the metrics you need, and keep raw data locally for 2 days for troubleshooting.
Common errors and fixes
sample limit exceeded
Section: L5. Diagnosis:pq 'scrape_samples_scraped{job="X"}' check the real sample count; run curl inside the cluster to count grep -vc '^#'; find the newly added metrics and labels. Fix: Fix the instrumentation or drop with metricRelabelings; raise the limit only when really needed, and assess memory. Prevention: Set sampleLimit on each ServiceMonitor, and enforcedSampleLimit globally.
label_limit exceeded (metric: http_requests_total{…}, number of labels: 23, limit: 20)
Cause: the exporter puts a lot of metadata into labels (or during relabeling labelmap maps in all Pod labels). Fix: Narrow the labelmap regex; labeldrop drop labels you don't need (make sure the remaining labels still uniquely identify each series).
Prometheus Pod keeps getting OOMKilled, and the log stops at “Replaying WAL, this may take a while”
Cause: high cardinality / churn pushes the head over the memory limit; replaying the WAL has to rebuild all the series, which also exceeds the limit. Handling:① temporarily raise the memory limit so the replay can finish; ② immediately block new series with metricRelabelings / take the targets offline; ③ wait for head compaction to free memory. In extreme cases, back up and then delete the WAL (losing about 2–3 hours of uncompacted data in the head), and do this only if the business side accepts it. See Module 5 for details.
The TSDB Status page is slow, or the query count by (__name__) reports query processing would load too many samples into memory
Cause: selecting all series is itself a heavy query. Fix: Use /api/v1/status/tsdb?limit=…; narrow the scope by job count by (__name__) ({job="X"}).
After labeldrop, data “goes missing”, or “Error on ingesting samples with different value but same timestamp” appears
Cause: A label that uniquely identified series was dropped, so several series merged into one. Diagnosis:pq 'rate(prometheus_target_scrapes_sample_duplicate_timestamp_total[5m])'. Fix: Undo the labeldrop, and aggregate at the source or drop the whole metric instead.
1. Without a full-scan query, find the 5 metrics with the most series in the head and the 5 labels with the most values.
curl -s "$P/api/v1/status/tsdb?limit=5" | jq '.data.seriesCountByMetricName, .data.labelValueCountByLabelName'
2. Write an alert expression: the series creation rate over the last 10 minutes is more than 3 times what it was at the same time 1 day ago.
rate(prometheus_tsdb_head_series_created_total[10m]) > 3 * rate(prometheus_tsdb_head_series_created_total[10m] offset 1d)
The dev team asks to “add customer_id to the request metrics so we can view latency for big customers”. There are 50 000 customers, of which 50 are key accounts. How do you respond?
You cannot simply add a label with 50 000 values to a high-frequency metric: multiplied by route, status, Pod and histogram buckets, it reaches tens of millions of series. Options: ① emit it only for the 50 key customers customer_tier or key_account label (the rest lumped into other), so the values are bounded; ② for single-customer investigation, use logs / traces (with customer_id) and link traces from metrics via exemplars; ③ if you must report per customer, use a separate low-frequency metric without histograms and set a sampleLimit; ④ use promtool check metrics to check instrumentation (it flags some naming issues, but cardinality still needs human review).
Verified teaching videos
Official docs
- Metric and label naming · Labels
- Instrumentation · Do not overuse labels
- HTTP API · TSDB stats
- promtool
Video storyboard (about 100 seconds)
Visual: four label blocks multiply to get 7200; a fifth block, “user_id × 100000”, drops in and the number rolls up to hundreds of millions.
Narration: cardinality is multiplicative; one unbounded label can make the series count run out of control.
Visual: the head memory bar goes from green to red, the Pod gets OOMKilled, and after restart the WAL replay progress bar gets halfway and crashes again.
Narration: memory follows active series, and churn makes old series pile up in the head.
Visual: the four Top lists on the TSDB Status page light up in turn; the top row is faultexp_user_requests_total.
Narration: use TSDB Status to find the culprit first, instead of running full queries on a large instance.
Visual: sampleLimit closes like a gate; the target turns red but the head curve stays flat.
Narration: the sample limit sacrifices one target to protect the whole Prometheus.
Module 4 · Query performance: slow PromQL and dashboard optimization
- Use a cost model to estimate queries: number of series selected, samples read per step, number of steps (range / step), and read the returned
stats=allthe returnedseriesTouched,totalQueryableSamples,peakSamplesand per-stage timings. - Know the three hard limits and their errors:
--query.max-samples(default 50000000) →query processing would load too many samples into memory in …;--query.timeout(default 2m) →query timed out in …; a single series can have at most 11 000 points →exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX). - Optimize dashboards with recording rules, aggregating before computing, narrowing selectors, and sensible step and refresh intervals; use the query log and
prometheus_engine_*metrics to find the source of slow queries.
What: the cost model of a query
When the PromQL engine handles a range query sum by (job) (rate(x[5m])) (time range 6h, step 30s):
- Select series: in the inverted index, intersect the postings of the matchers
__name__="x"etc. → gives N series (seriesTouched). Regex matchers (especially=~".*foo.*") must scan all values of that label. - Compute step by step: number of steps = 6h / 30s + 1 = 721. At each step, read the samples in the window for each series: 5m / 15s ≈ 20 samples. In total you read about N × 721 × 20 samples (
totalQueryableSamplesorder of magnitude). - Peak memory: the number of samples held by the engine at the same moment (
peakSamples) is limited by--query.max-samples; exceeding it produces an error rather than just slowing down. - Aggregation and return:
sum by (job)turns N series into a few, and returns 721 points. Returned points = range / step + 1; anything above 11 000 is rejected outright by the API.
| Parameters (v3.16.0 defaults) | Meaning | When exceeded | Where to set in kps |
|---|---|---|---|
--query.max-samples=50000000 | Maximum samples a single query can load into memory at once | query processing would load too many samples into memory in query execution | prometheusSpec.query.maxSamples |
--query.timeout=2m | Maximum execution time for a single query | query timed out in expression evaluation (the stage after “in” is where the error occurs) | prometheusSpec.query.timeout |
--query.max-concurrency=20 | Number of queries executing at the same time; the excess are queued (prometheus_engine_queries queue time counts toward queue_time) | Slower, and may time out while queued | prometheusSpec.query.maxConcurrency |
--query.lookback-delta=5m | Maximum lookback distance for an instant vector to find the latest sample | — (affects lingering values and sparse series) | prometheusSpec.query.lookbackDelta |
| 11 000 points (hard-coded in the API) | Upper limit on range / step | exceeded maximum resolution of 11,000 points per timeseries… | Not configurable; increase the step |
Why: which patterns are slow
| Anti-pattern | Why it's slow | Rewrite |
|---|---|---|
{__name__=~".+"}, selectors without a metric name | select all series | Always include the metric name; for metadata use /api/v1/status/tsdb |
http_requests_total{path=~".*order.*"} | An unanchored regex scans all values of a high-cardinality label | Use an equality or anchored prefix regex; fix the label design |
histogram_quantile(0.99, rate(x_bucket[5m])) | computing separately for each Pod × route × bucket | histogram_quantile(0.99, sum by (le) (rate(x_bucket[5m]))), or a recording rule |
max_over_time(rate(x[5m])[30d:1m]) | A subquery computes the inner expression step by step over a long range | a recording rule precomputes the inner expression |
| Dashboard with 30 panels × auto-refresh every 5s × 10 people | 3 600 queries per minute | Refresh ≥ 30s–1m, collapsed rows (no queries until expanded), shared queries (Dashboard data source) |
| Panel range 30d, Max data points very large | many steps, many points | Let Grafana compute the step automatically ($__interval), and for long ranges use recording rules or downsampling (Lesson 6) |
How: recording rules are the most effective optimization
A recording rule turns sum by (job, status) (rate(faultexp_http_requests_total[5m])) an expression like this into a new series, evaluated once per evaluation interval job:faultexp_http_requests:rate5m (naming convention level:metric:operations, Lesson 2). A dashboard query goes from “N raw series × 20 samples per step” to “a few precomputed series × 1 sample per step”. Trade-offs: the rule group's own evaluation cost, and it only holds data from after the rule was created (history is available only after backfilling with promtool tsdb create-blocks-from rules ).
When: check Prometheus first or Grafana first
If the same query is also slow in the Prometheus UI → the query itself (this module); Prometheus fast but Grafana slow → too many panels, step too small, data source proxy, browser rendering (Module 7); slow only at peak times → concurrency and queueing (prometheus_engine_query_duration_seconds{slice="queue_time"}), rule groups and dashboards compete for resources.
topk it still computes all the series first.Query cost = series × samples per step × steps
How one dashboard amplifies query load
Interactive: query cost calculator
Enter the number of series, time range, step, rate window and scrape interval to calculate the number of steps, samples read, estimated peak samples, and whether a limit is triggered. Toggle “Use recording rule” to see the difference. The estimation model is simplified (peak is estimated as “window samples per series per step × number of series”). Actual values follow stats=all .
Core commands
| Command / query | Purpose |
|---|---|
curl -s "$P/api/v1/query_range" --data-urlencode query=… -d start=… -d end=… -d step=30 -d stats=all | Returns stats.timings and stats.samples (stats accepts only true/all, other values produce a deprecation warning in 3.16) |
prometheus_engine_query_duration_seconds{quantile="0.9"} | split by slice (inner_eval, prepare_time, queue_time, result_sort) breakdown of query time |
prometheus_engine_queries,prometheus_engine_queries_concurrent_max | number of queries currently executing / queued and the concurrency limit |
prometheus_rule_group_last_duration_seconds | whether the rule group itself is too slow |
kps: prometheus.prometheusSpec.queryLogFile: /dev/stdout | Enable the query log (JSON, with query text, source and stats), then read it with kubectl logs ; in distroless images you cannot cat files, so writing to stdout is the most convenient |
promtool query instant $P 'expr' | Command-line instant query (when promtool is installed locally) |
source ~/promlab/faultlab/env.sh
END=$(date +%s); START=$((END-6*3600))
q() { curl -s "$P/api/v1/query_range" --data-urlencode "query=$1" -d start=$START -d end=$END -d step=${2:-30} -d stats=all \
| jq -c '{status, error, series: (.data.result|length), touched: .data.stats.samples.seriesTouched,
samples: .data.stats.samples.totalQueryableSamples, peak: .data.stats.samples.peakSamples,
evalSec: .data.stats.timings.evalTotalTime}'; }
q 'sum by (status) (rate(faultexp_http_requests_total[5m]))'
q 'sum by (status) (job:faultexp_http_requests:rate5m)'
q 'up' 1 # 6h / 1s = 21601 points
{"status":"success","error":null,"series":2,"touched":2,"samples":28840,"peak":...,"evalSec":0.0041}
{"status":"success","error":null,"series":2,"touched":2,"samples":1442,"peak":...,"evalSec":0.0012}
{"status":"error","error":"exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)","series":0,...}
The faultexp baseline has only 2 series, so the difference is not obvious yet; in the lab you first create 8 000 series and then compare. Common mistakes: Forgetting to URL-encode --data-urlencode,+,{ etc. characters, which gives bad_data: invalid parameter "query": … (API error format: invalid parameter %q: …).
Enable query log (kps values)
prometheus:
prometheusSpec:
queryLogFile: /dev/stdout
query:
maxSamples: 50000000 # Default value, written out explicitly for auditing
timeout: 2m
maxConcurrency: 20
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --reuse-values -f querylog.yaml
kubectl -n monitoring logs $PROM_POD -c prometheus --since=5m | grep '"params"' | jq -c '{q: .params.query, step: .params.step, eval: .stats.timings.evalTotalTime}' | sort -t: -k4 -rn | head
The query log records every query (including API queries beyond rule evaluation); with high volume, enable it only during troubleshooting. --reuse-values It reuses the previous values and layers new files on top — note that it also picks up defaults from the old chart version (Helm Lesson 7); in production, use a complete values file.
Lab 4: same panel, before and after optimization (about 7 minutes)
kubectl -n faultlab set env deploy/faultexp SERIES=4000 && kubectl -n faultlab rollout status deploy/faultexp sleep 300
q() function from the “Commands” tab):
END=$(date +%s); START=$((END-3600))
q 'sum(rate(faultexp_user_requests_total[5m]))' 15
q 'count by (session) (faultexp_user_requests_total{session=~".*99.*"})' 15
{"status":"success","series":1,"touched":4000,"samples":...,"evalSec":0.21}
{"status":"success","series":40,"touched":40,"samples":...,"evalSec":0.09}
The second one is an unanchored regex: it has to scan the 4 000 values of the session label.
kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"add","path":"/spec/groups/0/rules/-","value":{"record":"job:faultexp_user_requests:rate5m","expr":"sum by (job) (rate(faultexp_user_requests_total[5m]))"}}]'
sleep 120
q 'job:faultexp_user_requests:rate5m' 15
pq 'prometheus_rule_group_last_duration_seconds{rule_group=~".*faultexp.*"}'
{"status":"success","series":1,"touched":1,"samples":...,"evalSec":0.002}
[{...,"rule_group":"/etc/prometheus/rules/prometheus-kps-kube-prometheus-stack-prometheus-rulefiles-0/faultlab-faultexp-rules-....yaml;faultexp.rules"},"0.035"]
The recording rule only has data from after it was created; once the panel switches to the rule, time ranges earlier than the rule are empty.
kubectl -n monitoring patch prometheus $PROM_CR --type=merge -p '{"spec":{"query":{"maxSamples":100000}}}'
sleep 90
q 'sum(rate(faultexp_user_requests_total[5m]))' 15
kubectl -n monitoring patch prometheus $PROM_CR --type=json -p '[{"op":"remove","path":"/spec/query/maxSamples"}]'
{"status":"error","error":"query processing would load too many samples into memory in query execution",...}
Changing Prometheus startup parameters via the Operator will trigger a rolling restart of Prometheus (which triggers WAL replay); direct patches to the CR are overwritten at the next helm upgrade time. In production, make changes through values.
kubectl -n faultlab set env deploy/faultexp SERIES- kubectl apply -f ~/promlab/faultlab/faultexp.yaml # Restore the PrometheusRule to its original state
Case 1: Monday stand-up dashboard overloads Prometheus
Problem: Every Monday at 9:00, 40 people open the “Global Overview” at the same time (48 panels, 10s refresh, default range 7d). Prometheus CPU maxes out, and missed iterations in the rule group delay alerts. Approach: Grouping the query log by source showed that 70% of queries came from this dashboard. Core panels switched to recording rules, the default range changed to 6h, refresh to 1m, and rarely used panels were moved into collapsed rows. Result: Query volume dropped by about 90% (team measurement).
Case 2: 30-day subquery in an SLO dashboard
Problem:avg_over_time((sum(rate(errors[5m])) / sum(rate(requests[5m])))[30d:5m]) It times out every time it is opened. Approach: Turn the inner ratio into a recording rule job:slo_errors_per_request:ratio_rate5m, and query the 30-day window directly on the rule series avg_over_time; for longer-term data, rely on Thanos/Mimir downsampling from Lesson 6.
Case 3: a variable query is slower than the panels
Problem: The dashboard variable label_values(pod) (no metric name) scans all series on every refresh. Approach: Change it to label_values(kube_pod_info{namespace="$namespace"}, pod), and set the variable refresh to “On dashboard load”.
Common errors and fixes
query processing would load too many samples into memory in query execution
Section: L7. Cause: The peak sample count exceeded --query.max-samples (default 50 million). Diagnosis: Shrink the time range of the same query and add stats=all and watch peakSamples peakSamples as it grows with the range; check the number of selected series. Fix: recording rules, narrow selectors, increase the step, shorten the range. Assess Prometheus's memory headroom before raising the limit.
query timed out in expression evaluation
Cause: Exceeded --query.timeout (default 2m), or queued at peak times (queue_time counts toward the total). Diagnosis:pq 'prometheus_engine_query_duration_seconds{quantile="0.99"}',pq 'prometheus_engine_queries'. Fix: Same as above; and reduce the number of concurrent dashboard loads.
exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)
Cause: range / step > 11 000 (e.g. 7 days at step 30s = 20 161 points). Fix: Increase the step; in Grafana, check the panel's Min interval and Max data points, and don't hard-code a very small step.
bad_data: invalid parameter "query": 1:12: parse error: unexpected …
Cause: A syntax error or URL-encoding error (+ was treated as a space). Fix: Use curl with --data-urlencode; the Prometheus UI editor gives syntax hints; /api/v1/parse_query and /api/v1/format_query can do format checks.
found duplicate series for the match group {…} on the right hand-side of the operation / multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)
Cause: The matching labels on the two sides of a binary operation are not unique (common with joins on kube-state-metrics info metrics, or when old and new series briefly coexist while a Pod is recreated). Fix: Use on(...) to restrict the matching labels,group_left specify many-to-one, and first deduplicate the info metric with max by (…) . This kind of error often shows up in panels that “sometimes error and sometimes work”.
1. Rewrite the P99 query below in a cheaper form: histogram_quantile(0.99, rate(myapp_http_request_duration_seconds_bucket[5m])) (you only need the overall P99).
histogram_quantile(0.99, sum by (le) (rate(myapp_http_request_duration_seconds_bucket[5m])))
First aggregate by le , then compute the quantile; go further by making it a recording rule job:myapp_http_request_duration_seconds_bucket:rate5m (keeping le).
2. Use the API to get seriesTouched and peakSamples for a range query.
curl -s "$P/api/v1/query_range" --data-urlencode 'query=sum(rate(faultexp_http_requests_total[5m]))' \
-d start=$(( $(date +%s)-3600 )) -d end=$(date +%s) -d step=30 -d stats=all | jq '.data.stats.samples | {seriesTouched, peakSamples, totalQueryableSamples}'The platform team proposes raising --query.max-samples from 50 million to 500 million, “because the business dashboards keep erroring”. How do you evaluate this?
max-samples is a fuse that stops a single query from consuming all memory. Each sample takes more than a dozen bytes in memory, so 500 million samples could let one query use several GiB, and a few concurrent ones can OOM Prometheus, affecting all alerts. First use the query log to find which panel and which query is responsible; fix it with recording rules or a narrower range; hand long-range analysis to Thanos/Mimir (with downsampling and query splitting). If you really must raise it, weigh Prometheus's memory headroom,maxConcurrency evaluate them together, and use a separate read-only replica or query frontend for the big-screen dashboards.
Verified teaching videos
Official docs
- HTTP API (stats parameter)
- prometheus command-line flags (--query.*)
- Recording rules naming convention
- Using the Prometheus query log
Video storyboard (about 90 seconds)
Visual: a query is broken into three multipliers: 8000 series × 20 samples per step × 721 steps. The number shoots upward and hits the “max-samples” red line.
Narration: query cost is a multiplication; shrink any one multiplier and the query gets faster.
Visual: a recording rule, like a prepped meal, gets made every 30 seconds and the panel takes it directly; stats compare 4000 series becoming 1.
Narration: the most effective optimization is the recording rule.
Visual: 40 browsers refresh at once and the query queue fills up; after the refresh interval is changed to one minute, the queue clears.
Narration: it's often not one slow query, but the number of queries.
Module 5 · TSDB internals: head block, WAL, compaction and disk
- Sketch the data directory: persisted blocks (
meta.json,index,chunks/,tombstones),chunks_head/(m-mapped head chunks),wal/(128 MiB segments +checkpoint.N). - Explain the head lifecycle: samples are written to the head chunk (target 120 samples) and to the WAL → full chunks are m-mapped to disk → when the head span exceeds 1.5 × 2h, the oldest 2h is persisted as a block → head truncation + GC → checkpoint of the first 2/3 of the WAL segments.
- Explain the compaction levels (2h → 6h → 18h → 54h…; maximum block size = min(retention × 10%, 31d)) and the semantics of time / size / percentage retention (whole blocks are deleted; size retention includes the WAL and head chunks).
- Diagnose from logs and metrics: slow WAL replay, compaction failures, full disk, and out-of-order samples being dropped.
What: the data directory (in kps it is /prometheus)
/prometheus ├── 01JD6Z…/ # Persisted blocks (ULID-named, sorted by time) │ ├── meta.json # minTime/maxTime, stats, compaction.level, sources │ ├── index # Series labels + inverted index (postings) │ ├── chunks/000001 # Compressed samples (XOR encoding) │ └── tombstones # Deletion markers (when series are deleted via the admin API) ├── chunks_head/ # Full chunks in the head, m-mapped to memory │ ├── 000001 │ └── 000002 ├── wal/ │ ├── 00000021 # WAL segment, default 128 MiB (tsdb/wlog DefaultSegmentSize) │ ├── 00000022 │ └── checkpoint.00000020 # Checkpoint of still-live series and samples, compressed at truncation ├── lock └── queries.active # Queries in progress (printed on startup after a crash, to help locate the “fatal query”)
How: the journey of a sample (v3.16.0 tsdb/head.go,tsdb/db.go)
- Append: a batch of scraped samples is first written to the WAL (Series records: series seen for the first time; Samples records: the samples), then written to each series' head chunk. WAL compression is on by default (
--storage.tsdb.wal-compressiondefault true, algorithm snappy, zstd optional). - m-map: once a head chunk is full (target
--storage.tsdb.samples-per-chunk=120samples, about 30 minutes at a 15s interval), it is written tochunks_head/and m-mapped; only the chunk being written stays in memory. - Compaction: the head's block range is 2h (
--storage.tsdb.min-block-duration, a hidden parameter, for testing only). When head span > 2h × 1.5 = 3h (compactable()), the oldest complete 2h range is written as a persisted block (logwrite block started,Head portion block created). - Truncation and GC: once the block is written, the head is truncated to the new minimum time and GC removes inactive series (log
Head GC completed)—series created by churn only free their memory at this moment. - WAL checkpoint: the first 2/3 of the WAL segments (
last = first + (last-first)*2/3) that are still needed are written intocheckpoint.N, and the old segments are deleted (logWAL checkpoint complete). - Block merging: in the background, adjacent small blocks are merged into larger ones. The range grows ×3 (2h, 6h, 18h, 54h…), capped at min(10% of retention, 31d) (kps defaults to 10d retention → max block 1d, so in practice the largest is an 18h block). Merging reduces index duplication and file count.
- Retention: by time (kps default
retention: 10d; Prometheus itself defaults to 15d), by size (retentionSize), or by disk percentage (new in 3.xretention.percentage), deletes entire oldest blocks. Size retention counts “WAL + head chunks + all blocks”. - Startup replay: on restart, load m-mapped chunks in order (
Replaying on-disk memory mappable chunks if any) → checkpoint (WAL checkpoint loaded) → remaining WAL segments (Replaying WAL, this may take a while/WAL segment loaded) →WAL replay completed: during replay/-/readyreturns not-ready,/api/v1/status/walreplayshows progress.
Why: which phenomena these mechanisms explain
| Phenomenon | Mechanism |
|---|---|
| Memory doesn't drop after churn stops, then drops suddenly after about 1–3 hours | Inactive series are only freed by GC after the next head compaction |
| No data for 10 minutes after restart | WAL replay: duration is proportional to the number of series and samples in the WAL (higher cardinality = slower) |
| Retention is 10d, yet data from 11 days ago can be queried | Blocks are deleted whole: a block is removed only when its maxTime is older than the retention boundary |
| Disk usage = blocks + about 3 hours of WAL | The WAL covers the part of the head not yet persisted, and has checkpoints |
| “out of bounds” samples are dropped | Without out-of-order writes enabled, samples older than the head's minimum valid time are rejected (prometheus_target_scrapes_sample_out_of_bounds_total) |
When: what needs adjusting
- Retention: in kps, use
prometheus.prometheusSpec.retention/retentionSize/retentionPercentage. Note: in 3.16 the--storage.tsdb.retention.time/sizecommand-line flag is marked DEPRECATED; prefer putting it in the config filestorage.tsdb.retention; how the Operator generates it depends on the Operator version. As a user you only change the CR fields. - Out-of-order writes: needed only for remote write receivers, backfilling, or multi-source pushes
storage.tsdb.out_of_order_time_window(config file; Operator:tsdb.outOfOrderTimeWindow); regular scraping does not need it. - Disk:
retentionSizeSet it to about 80% of PV capacity as a “fuse”, and alert onpredict_linear(kubelet_volume_stats_available_bytes[6h], 24*3600) < 0(kps ships with a similarKubePersistentVolumeFillingUp). - Memory snapshots: enable
--enable-feature=memory-snapshot-on-shutdownto write a snapshot on normal shutdown, so the next startup skips most WAL replay (no effect on abnormal exits such as OOM).
lock file exists precisely to prevent this; non-POSIX filesystems such as NFS are not supported either. ⑤ “A failed compaction is just a warning” — continued failures make the head grow until OOM, so it must be alerted on prometheus_tsdb_compactions_failed_total.Relationship between head, WAL and blocks
Timeline: one head compaction
Key animation: TSDB head / WAL / compaction
Simulates a Prometheus scraping every 15 seconds. Each click on “Next” advances time by a step; watch the head chunk fill up and get m-mapped, WAL segments grow, and compaction, truncation, GC and checkpoint happen once the head span exceeds 3h. You can also click “OOM crash and restart” to watch the WAL replay order. Tick churn to see the difference in series count before and after GC. The log lines are real messages taken from the v3.16.0 source.
Key commands and metrics
| Command / metric | Description |
|---|---|
curl -s $P/api/v1/status/tsdb/blocks | jq | ulid, minTime, maxTime, stats, compaction.level for all blocks |
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus | Block list (human-readable sizes); available in distroless images |
curl -s $P/api/v1/status/walreplay | Replay progress {min, max, current} (segment number) |
prometheus_tsdb_head_series,prometheus_tsdb_head_chunks,prometheus_tsdb_head_chunks_storage_size_bytes | head size and chunks_head disk usage |
prometheus_tsdb_wal_storage_size_bytes,prometheus_tsdb_wal_segment_current,prometheus_tsdb_wal_fsync_duration_seconds | WAL size, current segment number, fsync latency (a sign of a slow disk) |
prometheus_tsdb_storage_blocks_bytes,prometheus_tsdb_retention_limit_bytes,prometheus_tsdb_lowest_timestamp | block occupancy, size retention limit, earliest data time |
prometheus_tsdb_compactions_total,prometheus_tsdb_compactions_failed_total,prometheus_tsdb_compaction_duration_seconds | compaction count, failures, duration |
prometheus_tsdb_head_truncations_failed_total,prometheus_tsdb_checkpoint_creations_failed_total,prometheus_tsdb_wal_corruptions_total | truncation, checkpoint failures and WAL corruption |
prometheus_tsdb_time_retentions_total,prometheus_tsdb_size_retentions_total | number of blocks deleted by time / size |
source ~/promlab/faultlab/env.sh
curl -s $P/api/v1/status/tsdb/blocks | jq -r '.data.blocks[] | [.ulid, (.minTime/1000|todate), (.maxTime/1000|todate), .stats.numSeries, .compaction.level] | @tsv'
curl -s "$P/api/v1/status/tsdb" | jq '.data.headStats | {numSeries, chunkCount, min: (.minTime/1000|todate), max: (.maxTime/1000|todate)}'
pq 'prometheus_tsdb_wal_storage_size_bytes / 2^20'
pq 'prometheus_tsdb_storage_blocks_bytes / 2^20'
01JD2… 2026-11-14T00:00:00Z 2026-11-14T18:00:00Z 61002 3
01JD5… 2026-11-14T18:00:00Z 2026-11-15T12:00:00Z 60488 3
01JD8… 2026-11-15T12:00:00Z 2026-11-15T18:00:00Z 60112 2
01JD9… 2026-11-15T18:00:00Z 2026-11-15T20:00:00Z 60030 1
{"numSeries":61234,"chunkCount":132011,"min":"2026-11-15T20:00:00Z","max":"2026-11-15T22:41:05Z"}
[{...},"58.3"]
[{...},"412.9"]
How to read it: level 1 = 2h blocks written directly from the head, level 2 = 6h, level 3 = 18h; the head's min is exactly the max of the last block.
Compaction and replay-related logs
kubectl -n monitoring logs $PROM_POD -c prometheus --since=6h \ | grep -E 'write block|Head portion block created|compact blocks|Head GC completed|WAL checkpoint complete|Deleting obsolete block' | tail -8
time=2026-11-15T22:00:03Z level=INFO source=compact.go:689 msg="write block started" component=tsdb mint=1763236800000 maxt=1763244000000 ulid=01JD9… time=2026-11-15T22:00:04Z level=INFO source=db.go:1856 msg="Head portion block created" component=tsdb ulids=[01JD9…] ... time=2026-11-15T22:00:04Z level=INFO source=head.go:1806 msg="Head GC completed" component=tsdb caller=truncateMemory duration=21.4ms time=2026-11-15T22:00:05Z level=INFO source=head.go:1760 msg="WAL checkpoint complete" component=tsdb first=18 last=20 duration=402ms time=2026-11-15T22:00:09Z level=INFO source=compact.go:… msg="compact blocks" component=tsdb count=3 mint=… maxt=… ulid=01JD8… sources=[…] duration=1.1s
Lab 5: read the TSDB and watch one WAL replay (about 7 minutes)
kubectl -n faultlab set env deploy/faultexp SERIES=1000 CHURN=1 sleep 240 pq 'prometheus_tsdb_head_series'
kubectl -n monitoring delete pod $PROM_POD --grace-period=0 --force sleep 5 kubectl -n monitoring logs -f $PROM_POD -c prometheus | grep -E 'Replaying|replay|WAL segment loaded|checkpoint loaded|Server is ready|unclean' & LOGPID=$! until curl -s $P/-/ready | grep -q Ready; do curl -s $P/api/v1/status/walreplay; echo; sleep 2; done kill $LOGPID
time=… level=INFO source=head.go:762 msg="Replaying on-disk memory mappable chunks if any" component=tsdb
time=… level=INFO source=head.go:847 msg="On-disk memory mappable chunks replay completed" component=tsdb duration=…
time=… level=INFO source=head.go:855 msg="Replaying WAL, this may take a while" component=tsdb
time=… level=INFO source=head.go:914 msg="WAL checkpoint loaded" component=tsdb
time=… level=INFO source=head.go:950 msg="WAL segment loaded" component=tsdb segment=21 maxSegment=23 …
time=… level=INFO source=head.go:950 msg="WAL segment loaded" component=tsdb segment=23 maxSegment=23 …
time=… level=INFO source=head.go:988 msg="WAL replay completed" component=tsdb checkpoint_replay_duration=… wal_replay_duration=… total_replay_duration=4.2s
time=… level=INFO … msg="Server is ready to receive web requests."
{"status":"success","data":{"min":20,"max":23,"current":22}}
After a forced delete, port-forward disconnects and has to be run again ~/promlab/faultlab/pf.sh (the Pod name stays the same, since the StatefulSet recreates it with the same name). During replay, port-forwarding may fail to connect, but the loop keeps retrying. On kind it usually takes a few seconds; in production, millions of series can take over ten minutes.
up{job="faultexp"}, and you'll see holes from the Pod restart. kps defaults to a single-replica Prometheus; in production, use 2 replicas plus Thanos/Mimir deduplication (Lesson 6) to eliminate the gaps.kubectl -n faultlab set env deploy/faultexp SERIES- CHURN-.Case 1: the OOM → replay → OOM death loop
Problem: After a cardinality incident, Prometheus gets OOMKilled every time replay reaches 70% on startup. Approach:① temporarily raise the memory limit by 50% so the replay can finish; ② once replay completes, drop the culprit metric immediately; ③ restore the limit after the next head compaction. If memory cannot be increased: first back up wal/ then move it aside and start (accepting the loss of about 2–3 hours of data in the head); this requires sign-off from the business side. Prevention: enforcedSampleLimit + head series alert + memory-snapshot-on-shutdown (effective for normal restarts).
Case 2: disk fills up and no more data is accepted
Problem: PV of 50 GiB, retention 30d. As the business grew the disk filled up, and the log showed no space left on device, WAL writes failed, and all scrapes failed. Approach: Expand the PV (if the StorageClass supports allowVolumeExpansion , change the storage request in the Prometheus CR or follow the Operator docs for StatefulSet volume expansion), and set retentionSize: 40GiB as a fuse. Lesson learned: With time-based retention only, there is no disk cap; you must set both.
Case 3: compaction keeps failing and the head keeps growing
Problem:prometheus_tsdb_compactions_failed_total Each 2-hour cycle should add one more block, but the head span keeps growing and memory keeps rising. The log shows an incomplete block in the block directory (half-written when the disk was full). Approach: Move the incomplete block out of the data directory and restart; compaction recovers. Prevention: kps ships with the PrometheusTSDBCompactionsFailing alert; make sure it is routed to the on-call engineer.
Common errors and fixes
Prometheus stays not Ready for a long time after startup, and the log stops at “Replaying WAL, this may take a while”
Cause: The WAL is very large (high cardinality / churn / no compaction for a long time). Diagnosis:curl -s $P/api/v1/status/walreplay check the segment-number progress; kubectl top pod check whether memory is near the limit. Handling: Be patient and make sure memory is sufficient; do not make startupProbe / readinessProbe too aggressive (the Operator's default startupProbe already allows a long time for replay).
Encountered WAL read error, attempting repair
Cause: An earlier abnormal exit corrupted the end of the WAL. Prometheus truncates at the corruption point and continues (log Successfully repaired WAL), and data after the corruption point is lost. Diagnosis:prometheus_tsdb_wal_corruptions_total. Prevention: Avoid SIGKILL (give terminationGracePeriodSeconds enough time), and use reliable block storage.
… write /prometheus/wal/00000123: no space left on device
Handling: Expand the volume; as a temporary measure you can delete the oldest block directory (whole-block deletion, data is permanently lost, so back up first or confirm it has been uploaded to long-term storage); Do not delete the WAL first. Prevention: Set both retention and retentionSize; alert on disk-usage forecasts.
The count of the log line “Error on ingesting samples that are too old or are too far into the future / out of bounds” keeps growing
Cause: The target sends its own timestamps and they lag behind (or the node clock has drifted), so samples are older than the head's minimum valid time. Diagnosis:pq 'rate(prometheus_target_scrapes_sample_out_of_bounds_total[5m])', compare the clock on the target's node with the clock on the Prometheus node. Fix: Fix NTP; remove the timestamps from the exporter; turn on only where truly needed (backfilling, remote write receivers) out_of_order_time_window.
Retention has passed, but disk usage has not dropped
Cause: Deletion is per block: a large block (e.g. an 18h block) is only deleted once its maxTime is also past the retention period; or the head/WAL itself is very large. Diagnosis: Compare the maxTime in the block list with prometheus_tsdb_lowest_timestamp.
1. List each block's time range, series count and compaction level.
curl -s $P/api/v1/status/tsdb/blocks | jq -r '.data.blocks[] | [(.minTime/1000|todate), (.maxTime/1000|todate), .stats.numSeries, .compaction.level] | @tsv'
2. Write an alert: TSDB compaction has failed at some point in the last 3 hours.
increase(prometheus_tsdb_compactions_failed_total[3h]) > 0
You stopped an exporter with heavy churn, but Prometheus memory only dropped 2 hours later. The business side thinks it is a “Prometheus memory leak”. Explain this and give a way to verify it.
Not a leak: inactive series stay in the head until the head span exceeds 3h and triggers compaction; the oldest 2h is persisted, and then head truncation and GC delete these series and free their memory. To verify: compare prometheus_tsdb_head_series the drop time with the log entries for Head GC completed,write block started and prometheus_tsdb_head_series_removed_total growth. The Go runtime adds an extra delay before returning memory to the OS, so RSS may drop later than the head series count.
Verified teaching videos
Official docs
- Storage (directory layout, retention, capacity planning)
- Feature flags (memory-snapshot-on-shutdown, etc.)
- tsdb/docs (format and internal documentation)
Video storyboard (about 100 seconds)
Visual: one sample lands in two places at once: a WAL log entry on disk and the head chunk in memory.
Narration: every sample is written to the WAL first so nothing is lost, then into the head in memory.
Visual: once a head chunk holds 120 samples, it “snaps” into the chunks_head directory; the head timeline stretches to three hours, and the oldest two hours are cut off and compressed into a block.
Narration: once the head exceeds three hours, the oldest two hours are written out as an immutable block.
Visual: a GC broom sweeps away the grey inactive series and the memory bar drops; the first two-thirds of the WAL segments are folded into a checkpoint.
Narration: only at this point are the series left behind by churn truly released.
Visual: the process crashes; after restart, the progress bar moves through m-map chunks, checkpoint and WAL segments in turn.
Narration: a restart has to replay the WAL, and the higher the cardinality, the slower the replay.
Module 6 · Alerts not firing or alert storms
- Diagnose “no alert notifications” through the seven checkpoints: is the rule loaded (
/rules) → health and lastError → does the expression return series →foris the for duration met (pending) → did Prometheus send to Alertmanager → is it silenced / inhibited / routed tonull→ did the receiver deliver successfully. - Know the default kps Alertmanager configuration:
group_by: ['namespace'],group_wait 30s,group_interval 5m,repeat_interval 12h,default receivernull(sends no notifications); Watchdog is routed tonull, plus severity-based inhibition rules. - Handling alert storms: sensible
group_by, inhibition rules (a common cause inhibits its symptoms),forandkeep_firing_fordebouncing; symptom alerts take precedence over cause alerts.
What: the seven checkpoints of the alert pipeline
| # | Checkpoint | Failure symptom | Observation window |
|---|---|---|---|
| 1 | Rule loading (kps: PrometheusRule is ruleSelector selected → the Operator validates → written to the rules ConfigMap → reloader reloads) | /rules the rule is missing from | /api/v1/rules, Operator events,PrometheusOperatorRejectedResources,prometheus_config_last_reload_successful |
| 2 | Evaluation (every evaluation_interval, kps default 30s) | health = err, lastError has content | prometheus_rule_evaluation_failures_total |
| 3 | Expression result | health = ok, but always inactive: the expression returns empty | Paste the expr into the UI and run it |
| 4 | for Duration | Repeatedly pending → inactive (flapping), never firing | ALERTS{alertstate="pending"} history of |
| 5 | Sent to Alertmanager (every --rules.alert.resend-delay=1m resend, queue --alertmanager.notification-queue-capacity=10000) | Firing in Prometheus, but not in Alertmanager | prometheus_notifications_alertmanagers_discovered,_errors_total,_dropped_total,_queue_length |
| 6 | Alertmanager: dedup → silence → inhibition → routing → group wait | visible in Alertmanager but suppressed, or routed to null | amtool alert query -s -i,amtool config routes test, AM UI |
| 7 | receiver (webhook, email, Teams, PagerDuty…) | AM thinks it was sent, but the recipient never got it | alertmanager_notifications_failed_total{integration}, AM logs |
Why: the four most common reasons an alert never notifies
- the expression returns empty during a fault:
up == 0it is empty when the target disappears (module 1);rate(x[1m])with a 30s scrape interval there are only two samples and it goes empty on jitter; a label matcher is wrong; the metric is not exported at all during a fault (the app stops exporting when it crasheserrors_total). - The rule is not loaded: kps by default
ruleSelectorNilUsesHelmValues: true→ only loadsrelease: kpsPrometheusRule objects carrying the label; a PromQL syntax error makes the Operator reject the whole resource. - for is too long, or the data is jittery: if a single evaluation returns empty during pending, the state goes back to inactive and the timer restarts.
- Alertmanager swallowed it: the default kps route's receiver is
null; an overly broad silence (namespace=~".+"); an inhibition ruleequalwith incomplete labels causes false suppression.
How: three ways to govern an alert storm
| Technique | Effect | Example |
|---|---|---|
Grouping group_by | alerts in the same group are merged into one notification; new alerts joining the group wait group_interval before being sent | Group by ['namespace','alertname'] rather than ['...'] (each alert in its own group), or instance |
inhibition inhibit_rules | suppress “symptom” alerts while a “cause” alert is firing | NodeDown inhibits all Pod alerts on the same node (equal: [node]); kps by default, critical inhibits warning/info with the same namespace and alertname |
| Debounce | avoid repeated firing and resolving around the threshold | for: 5m; the Prometheus 2.42+ keep_firing_for: 10m (keeps firing for a while after the condition clears); use a longer rate window |
When: the on-call checklist for an alert that does not notify
Work outward from Prometheus: /rules does it exist → health → run the expr in the UI → ALERTS → Alertmanager UI/amtool → receiver logs. Every step can be done read-only; the first four steps do not involve Alertmanager.
Compare: Prometheus alert states vs Alertmanager states
| Prometheus (rules) | Alertmanager (alert instances) |
|---|---|
| inactive / pending / firing | active / suppressed (silenced or inhibited) / unprocessed |
| a firing alert is resent every resend-delay, with endsAt | not renewed before endsAt → treated as resolved (resolve_timeout applies to alerts without endsAt) |
After a restart, it restores ALERTS_FOR_STATE the for progress (--rules.alert.for-outage-tolerance default 1h) | Silences and the notification log are stored on the local data volume; they sync across the cluster via gossip |
null, so you must configure your own receiver. ② “health = ok means it will fire”—ok only means the evaluation did not error; the expression may stay empty. ③ “Once an alert recovers, Alertmanager immediately sends resolved”—this depends on send_resolved and group_interval. ④ “Silences can last forever”—every silence needs an expiry time, plus a clear author and reason; expired silences are among the most common findings in incident reviews. ⑤ “Leaving equal empty on an inhibition rule is simpler”—an empty equal means any single source alert will inhibit every matching target alert.Seven checkpoints
Storm control: grouping and inhibition
Interactive: alert pipeline checkpoint inspector + grouping calculator
Top half: pick a fault that stops an alert from notifying, step through the Prometheus rule evaluation and Alertmanager processing, and see which checkpoint it stops at. Bottom half: enter the alert count and group_by to estimate how many notifications will be sent.
Core commands
| Command | Checkpoint | Purpose |
|---|---|---|
curl -s "$P/api/v1/rules?type=alert" | jq … | ①② | whether the rule exists,health,lastError,state,evaluationTime |
pq 'ALERTS{alertname="X"}' | ③④ | pending/firing instances (with all labels) |
curl -s $P/api/v1/alertmanagers | jq | ⑤ | Alertmanagers discovered by Prometheus (activeAlertmanagers) |
kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093 alert query -s -i | ⑥ | list alerts, including silenced (-s) and inhibited (-i) ones |
… amtool --alertmanager.url=http://localhost:9093 silence query | ⑥ | current silences; silence expire <ID> expire |
… amtool --alertmanager.url=http://localhost:9093 config routes test namespace=faultlab severity=critical | ⑥ | which receiver a given label set matches |
… amtool --alertmanager.url=http://localhost:9093 config routes show | ⑥ | print the routing tree |
pq 'rate(alertmanager_notifications_failed_total[5m])' | ⑦ | count send failures by integration |
source ~/promlab/faultlab/env.sh curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | [.name, .health, .state, (.lastError // "")] | @tsv' curl -s $P/api/v1/alertmanagers | jq -r '.data.activeAlertmanagers[].url' AMT="kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093" $AMT config routes show $AMT config routes test namespace=faultlab alertname=FaultexpHighErrorRate severity=critical
FaultexpDown ok inactive
FaultexpAbsent ok inactive
FaultexpHighErrorRate ok inactive
http://10.244.0.21:9093/api/v2/alerts
Routing tree:
└── default-route receiver: null
└── {alertname="Watchdog"} receiver: null
null
last line null Note: even when the alert is firing, the kps default config notifies no one. Common mistake: spending hours debugging on the Prometheus side when the problem is actually routing. Production use: Run amtool config routes test in the CI pipeline for Alertmanager config changes.
Lab 6: an alert that never notifies, plus routing and silences (about 10 minutes)
apiVersion: v1
kind: ConfigMap
metadata: {name: amsink-code, namespace: faultlab}
data:
sink.py: |
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_POST(self):
d = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
print(d.get("status"), json.dumps(d.get("groupLabels")),
[a["labels"].get("alertname") for a in d.get("alerts", [])], flush=True)
self.send_response(200); self.end_headers()
def log_message(self, *a): pass
HTTPServer(("", 8080), H).serve_forever()
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: amsink, namespace: faultlab}
spec:
selector: {matchLabels: {app: amsink}}
template:
metadata: {labels: {app: amsink}}
spec:
containers:
- name: sink
image: python:3.13-alpine
command: ["python", "-u", "/app/sink.py"]
ports: [{containerPort: 8080}]
volumeMounts: [{name: code, mountPath: /app}]
volumes: [{name: code, configMap: {name: amsink-code}}]
---
apiVersion: v1
kind: Service
metadata: {name: amsink, namespace: faultlab}
spec:
selector: {app: amsink}
ports: [{port: 8080}]
# Replace kps alertmanager.config in full (Helm replaces lists as a whole, not merges)
alertmanager:
config:
global: {resolve_timeout: 5m}
inhibit_rules:
- source_matchers: ['severity = critical']
target_matchers: ['severity =~ warning|info']
equal: ['namespace', 'alertname']
- source_matchers: ['severity = warning']
target_matchers: ['severity = info']
equal: ['namespace', 'alertname']
- source_matchers: ['alertname = InfoInhibitor']
target_matchers: ['severity = info']
equal: ['namespace']
- target_matchers: ['alertname = InfoInhibitor']
route:
group_by: ['namespace', 'alertname']
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
receiver: 'null'
routes:
- receiver: 'null'
matchers: ['alertname = "Watchdog"']
- receiver: faultlab-sink
matchers: ['namespace = "faultlab"']
group_wait: 10s
group_interval: 1m
receivers:
- name: 'null'
- name: faultlab-sink
webhook_configs:
- url: http://amsink.faultlab:8080/
send_resolved: true
templates: ['/etc/alertmanager/config/*.tmpl']
kubectl apply -f ~/promlab/faultlab/amsink.yaml helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 --reuse-values -f ~/promlab/faultlab/am-values.yaml sleep 60 $AMT config routes test namespace=faultlab alertname=FaultexpHighErrorRate severity=critical
faultlab-sink
An alert in a PrometheusRule that has no namespace label inherits the labels from the expression result namespace (from the target labels); sum(…) after aggregating away all labels namespace it disappears: this is the trap you hit in the next step.
kubectl -n faultlab set env deploy/faultexp ERRORS=1
sleep 240
pq 'ALERTS{alertname="FaultexpHighErrorRate"}'
kubectl -n faultlab logs deploy/amsink --tail=5
[{"__name__":"ALERTS","alertname":"FaultexpHighErrorRate","alertstate":"firing","severity":"critical"},"1"]
(amsink produces no output)
The alert is already firing in Prometheus, but the webhook receives nothing. Check the routing with amtool:
$AMT alert query alertname=FaultexpHighErrorRate $AMT config routes test alertname=FaultexpHighErrorRate severity=critical
Alertname Starts At Summary State FaultexpHighErrorRate 2026-11-16 02:31:10 UTC faultexp 5xx ratio 28.57% active null
Root cause: the expression uses sum(…) aggregated away namespace, so the alert has no namespace label → it does not match the faultlab route → it falls through to the default null. Fix: sum by (namespace, job) (…) Keep the labels the route needs, or explicitly add labels to the rule's labels namespace: faultlab (the kps built-in rules all keep namespace, because the default group_by and inhibition both depend on it).
kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"add","path":"/spec/groups/0/rules/3/labels/namespace","value":"faultlab"}]'
sleep 120; kubectl -n faultlab logs deploy/amsink --tail=3
firing {"alertname": "FaultexpHighErrorRate", "namespace": "faultlab"} ['FaultexpHighErrorRate']kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"replace","path":"/spec/groups/0/rules/3/expr","value":"sum(rate(faultexp_http_requests_total{status=~\"5..\"}[10s])) / sum(rate(faultexp_http_requests_total[10s])) > 0.1"}]'
sleep 90
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[].rules[] | select(.name=="FaultexpHighErrorRate") | "\(.health) \(.state)"'
pq 'rate(faultexp_http_requests_total[10s])'
ok inactive (no output: the 10s window holds at most one sample, so rate returns empty)
health is ok: there are no errors, but the alert simply never fires. Guardrail: unit-test the rules in CI promtool test rules (lesson 2), and set a convention that the rate window is ≥ 4 × scrape interval. Reset: kubectl apply -f ~/promlab/faultlab/faultexp.yaml (restores the rule as it was, and also removes the namespace label added in the previous step; edit the file if you want to keep it).
$AMT silence add 'namespace=~".+"' --comment="maintenance window" --duration=30m --author=oncall $AMT alert query -s $AMT silence query $AMT silence expire $($AMT silence query -q)
3f1c2a9e-… Alertname Starts At Summary State FaultexpHighErrorRate … … suppressed ID Matchers Ends At Created By Comment 3f1c2a9e-… namespace=~".+" 2026-11-16 03:10:00 UTC oncall maintenance window
A namespace=~".+" silence mutes alerts across the entire cluster (Watchdog is silenced too, so the external dead man's switch will alert; that is exactly the value of Watchdog).
kubectl -n faultlab set env deploy/faultexp ERRORS- kubectl apply -f ~/promlab/faultlab/faultexp.yaml # Keep amsink and the routes for module 8; to restore the kps default Alertmanager config, run helm upgrade without -f am-values.yaml and explicitly supply the original values
Case 1: the database went down, but no alert fired
Problem: The alert rate(db_errors_total[5m]) > 10. After the database process crashed, the exporter also stopped emitting db_errors_total, so the expression returned empty. Fix: Add up{job="db"} == 0 and absent(up{job="db"}); on the business side, use black-box probing (blackbox_exporter) to detect failures from the user's perspective. Principle:“Error count” alerts must be paired with “missing data” alerts.
Case 2: one node failure produced 400 notifications
Problem: group_by included pod, so a NotReady node made 120 Pod alerts each form their own group, with one Teams message per group. Fix: Change group_by to ['namespace','alertname']; add an inhibition rule: KubeNodeNotReady inhibit warning/info alerts on the same node (Pod alerts need the node label; some kps rules have it and others need a join kube_pod_info). Result: Notifications for the same event dropped to single digits.
Case 3: a flapping disk alert
Problem: Disk usage fluctuated between 89% and 91% against a 90% threshold, with for: 0m a short for duration, which sent 200 firing/resolved notifications a day. Fix:for: 15m + keep_firing_for: 30m; also switch to predict_linear to forecast “full within a few hours”, which is more meaningful than a static threshold.
Common errors and fixes
My PrometheusRule does not show on the /rules page
Diagnosis:kubectl get prometheus -n monitoring -o jsonpath='{..ruleSelector}' compare the selector against the rule's labels; kubectl get events -n <ns> --field-selector involvedObject.name=<rule> check whether the Operator rejected it for PromQL syntax pq 'prometheus_config_last_reload_successful'. Fix: Add release: kps; locally, validate with promtool check rules check (you first need to extract the spec section).
vector contains metrics with the same labelset after applying alert labels
Segment: evaluation (health = err). Cause: The rule's labels overrides a label in the expression result that distinguishes series (for example, two results differ only by instance, and the rule then sets instance: x, producing duplicate label sets (v3.16.0 rules/alerting.go behaviour ErrDuplicateAlertLabelSet The recording rule reports the error as … after applying rule labels. Fix: Do not override dimension labels in the labels block, or aggregate first.
The alert stays pending and never fires
Cause: Data jitter makes one evaluation return empty and resets the pending timer; or for the for is longer than the fault duration. Diagnosis: Graph ALERTS{alertname="X"} in the UI, alongside the expression itself. Fix: a longer rate window,max_over_time smoothing, and a reasonable for.
Firing in Prometheus, but not visible in the Alertmanager UI
Diagnosis:curl -s $P/api/v1/alertmanagers is it empty (in kps it is set by alerting.alertmanagers pointing to alertmanager-operated); pq 'rate(prometheus_notifications_errors_total[5m])',prometheus_notifications_dropped_total; Prometheus log messages of type Error sending alerts ; NetworkPolicy.
Alertmanager shows it as sent, but Teams / Slack did not receive it
Diagnosis:pq 'increase(alertmanager_notifications_failed_total[1h])' check by integration; AM logs kubectl -n monitoring logs $AM_POD -c alertmanager | grep -i notify; expired webhook URL, proxy, TLS. Prevention: Alert on alertmanager_notifications_failed_total itself, delivered through a separate channel.
The same alert is received twice (Alertmanager HA)
Cause: The gossip cluster does not form between the Alertmanager replicas (port 9094 unreachable, wrong peer address), so each replica sends independently. Diagnosis:pq 'alertmanager_cluster_members' should equal the number of replicas; the Status page of the AM UI shows the cluster state.
1. Use amtool to check which receiver the labels namespace=payments severity=warning alertname=HighLatency will be routed to.
kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093 \ config routes test namespace=payments severity=warning alertname=HighLatency
2. List all rules whose health is not ok, along with their lastError.
curl -s "$P/api/v1/rules" | jq -r '.data.groups[].rules[] | select(.health!="ok") | [.name, .health, .lastError] | @tsv'
The team complains that there are too many alerts and nobody looks at them: 300 notifications a day. How would you govern this systematically?
① Data: from the Alertmanager notification log or ALERTS count the notifications and average duration per alertname and find the top 10. ② Classify: short, self-resolving alerts are flapping → tune for / keep_firing_for / the window; one event triggering many alerts means missing grouping or inhibition → tune group_by and add a common-cause inhibition; alerts nobody acts on → downgrade to a ticket or dashboard, or delete them. ③ Principle: alert on symptoms (user-visible error rate, latency, SLO burn rate, lesson 6) rather than causes; every alert needs a runbook and a clear owner. ④ Metrics: review the notification count and the “share that needs manual action” every week.
Verified instructional videos
Official documentation
- Alerting rules (for, keep_firing_for)
- Alertmanager configuration (route, inhibit_rules)
- amtool
- Unit testing for rules
Video storyboard (about 90 seconds)
Visual: an alert travels like a letter through seven gates: load, evaluate, result, for, send, Alertmanager, receiver; the letter vanishes before the third gate.
Narration: health equal to ok does not mean it will fire; the expression may stay empty.
Visual: amtool config routes test prints null; the camera zooms in on receiver null in the kps default config.
Narration: kps sends no notifications by default, so confirm the routing first.
Visual: 50 alerts are collapsed into 2 notifications by inhibition rules and grouping.
Narration: govern alert storms with grouping, inhibition and debouncing; cause alerts suppress symptom alerts.
Module 7 · Grafana troubleshooting: data sources, panels and permissions
- Trace the request path of a panel query: browser →
POST /api/ds/query(Grafana backend) → Prometheus data source plugin → from the Grafana Pod's network access Prometheus → result frames → transformations → rendering. - Use the Query inspector (Query / Data / Stats / JSON) to tell apart “the query returned nothing”, “it returned data but a transformation dropped it”, and “rendering settings hid it”.
- Understand
$__interval,$__rate_interval, Min interval, Max data points and the data source Scrape interval (jsonData.timeInterval) determine the step and the rate window. - Troubleshoot kps sidecar provisioning (the label
grafana_dashboard: "1",grafana_datasource: "1"), variables,Datasource … was not foundand permission issues.
What: the path of one panel query
- Frontend: the panel calculates from the time range, Max data points and Min interval
$__interval(and derives the step from them), and replaces template variables. - Grafana backend: the browser calls
POST /api/ds/query, and the backend checks the user's permissions on the dashboard / data source. - Data source plugin: the Prometheus data source (a backend plugin) converts the query into a
/api/v1/query_range(or instant) request and sends it from Grafana Pod —so the URL must be an address that Grafana can resolve (kps defaulthttp://kps-kube-prometheus-stack-prometheus.monitoring:9090/, uidprometheus), regardless of whether your browser can reach it. - Return and transform: the results become data frames and pass through transformations (filter, merge, rename).
- Rendering: visualization options (units, thresholds, Overrides, hiding series, Y-axis range).
Step and rate window
| Variable / setting | Meaning | Troubleshooting notes |
|---|---|---|
$__interval | ≈ time range / Max data points, not less than Min interval or the data source Scrape interval | step too small → too many points (11 000 limit); too large → spikes get smoothed away |
$__rate_interval | max($__interval + Scrape interval, 4 × Scrape interval) | the rate window always spans at least 4 scrape intervals, avoiding “No data after zooming the time range” |
Data source Scrape interval (jsonData.timeInterval) | the scrape interval Grafana assumes | kps sets it automatically to Prometheus's scrapeInterval; it is often missed when a data source is created by hand (default 15s) |
| Max data points / Min interval (panel Query options) | limit the number of points and the minimum step | A hard-coded, very small Min interval pushes long-range queries over the limit |
Why: classifying common Grafana faults
| Category | Typical symptom | First place to look |
|---|---|---|
| Connectivity | Red triangle on the panel: Post "http://…:9090/api/v1/query_range": dial tcp: lookup … no such host / connect: connection refused | data source “Save & test”,/api/datasources/uid/<uid>/health |
| data source reference | Datasource ${DS_PROMETHEUS} was not found,Datasource xyz was not found | in the panel JSON datasource.uid |
| Query semantics | No data; the Prometheus UI is empty too | Query inspector → Query tab, check the actual expr and step |
| Variables | No data after selecting All; variable dropdown is empty | the expr after substitution in the Inspector (= vs =~, All value) |
| Transformations / rendering | Inspector Data tab has data, but the graph shows none | Transformations, Overrides, units and thresholds |
| Provisioning | A dashboard / data source in a ConfigMap does not appear | sidecar container logs (grafana-sc-dashboard,grafana-sc-datasources), labels |
| Permissions | Cannot see dashboards, Explore unavailable, “Access denied” | Organization role (Viewer/Editor/Admin), folder permissions, teams |
How: bisection
Copy the expr from the Inspector as-is into the Prometheus UI (same time range and step) and run it: Prometheus has none either → a query problem or an L1–L7 problem; Prometheus has data, Grafana does not → check the Inspector's Data tab: no frames → data source / connectivity / permissions; frames present → transformations and rendering.
When: when to suspect Grafana itself
only some users cannot see something (permissions); only one dashboard is slow (number of panels and refresh, module 4); after an upgrade some panels report “Panel plugin not found” (plugin not installed or incompatible); a provisioned change saved in the UI no longer matches the ConfigMap (provisioned dashboards cannot be saved persistently from the UI; edit the source file instead).
$__rate_interval. ③ “No data means there is no data”—it can be caused by transformations, Overrides hiding series, units, or the time range (time zone, future time). ④ “A community dashboard always works once imported”—${DS_PROMETHEUS} input placeholders must be mapped to actual data sources at import time; metric names may differ from your exporter version.Panel request path and the failure at each hop
Sidecar provisioning in kps
Interactive: panel request path tracer
Pick a “panel anomaly” and trace the request hop by hop: each hop shows what Grafana / Prometheus actually does, and the failing hop shows the error and how to fix it.
Core commands (Grafana HTTP API, using the admin account)
| Command | Purpose |
|---|---|
curl -s -u admin:$GPW $G/api/health | Grafana version and database status |
curl -s -u admin:$GPW $G/api/datasources | jq '.[] | {uid,name,type,url}' | all data sources and their URLs |
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health | backend health check (equivalent to Save & test in the UI) |
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query -d '{…}' | run a query as the Grafana backend, bypassing the browser |
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20 | whether the dashboard sidecar found / wrote the files |
kubectl -n monitoring logs deploy/kps-grafana -c grafana | grep -iE 'level=(error|warn)' | Grafana server-side errors (provisioning, plugins, data source proxy) |
source ~/promlab/faultlab/env.sh
export GPW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
curl -s -u admin:$GPW $G/api/datasources | jq -c '.[] | {uid, name, type, url, timeInterval: .jsonData.timeInterval}'
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health | jq
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query -d '{
"from": "now-15m", "to": "now",
"queries": [{"refId": "A", "datasource": {"uid": "prometheus"}, "expr": "up{job=\"faultexp\"}", "instant": true}]
}' | jq '.results.A | {status, error, frames: (.frames | length)}'
{"uid":"prometheus","name":"Prometheus","type":"prometheus","url":"http://kps-kube-prometheus-stack-prometheus.monitoring:9090/","timeInterval":"30s"}
{"uid":"alertmanager","name":"Alertmanager","type":"alertmanager",...}
{
"message": "Successfully queried the Prometheus API.",
"status": "OK"
}
{"status": 200, "error": null, "frames": 1}
How to verify:/api/ds/query frames returned but the panel shows nothing → the problem is in the frontend (variables, transformations, rendering). Common mistake: API tokens or passwords end up in shell history; after the lab, unset GPW. Production use: Call periodically from synthetic monitoring /api/ds/query and the data source health check, as an availability check for Grafana itself.
Lab 7: bad data source, bad reference, bad variable (about 8 minutes)
apiVersion: v1
kind: ConfigMap
metadata:
name: faultlab-dashboard
namespace: faultlab
labels: {grafana_dashboard: "1"}
data:
faultlab.json: |
{
"uid": "faultlab", "title": "Faultlab", "schemaVersion": 39, "refresh": "1m",
"time": {"from": "now-1h", "to": "now"},
"templating": {"list": [{
"name": "status", "type": "query", "multi": true, "includeAll": true,
"datasource": {"type": "prometheus", "uid": "prometheus"},
"query": {"query": "label_values(faultexp_http_requests_total, status)", "refId": "V"}
}]},
"panels": [{
"id": 1, "type": "timeseries", "title": "faultexp request rate",
"gridPos": {"h": 9, "w": 24, "x": 0, "y": 0},
"datasource": {"uid": "prometheus", "type": "prometheus"},
"targets": [{"refId": "A",
"expr": "sum by (status) (rate(faultexp_http_requests_total{status=~\"$status\"}[$__rate_interval]))"}]
}]
}
kubectl apply -f ~/promlab/faultlab/dash.yaml
sleep 20
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=5 | grep -i faultlab
curl -s -u admin:$GPW "$G/api/search?query=Faultlab" | jq -c '.[] | {uid,title,folderTitle}'
... Writing /tmp/dashboards/faultlab.json ...
{"uid":"faultlab","title":"Faultlab","folderTitle":null}
Open in the browser http://localhost:3000/d/faultlab, you should see a single status=200 line (with ERRORS off, 500 is 0).
prom-old.
kubectl -n faultlab get cm faultlab-dashboard -o yaml | sed 's/{"uid": "prometheus", "type"/{"uid": "prom-old", "type"/' | kubectl apply -f -
sleep 30 # refresh the browser
Red triangle in the panel's top-left corner: Datasource prom-old was not found
The most common error of the same kind when importing a community dashboard is Datasource ${DS_PROMETHEUS} was not found (input not mapped at import time). Fix: change it back to prometheus or use a data source variable ${datasource}. Reset: kubectl apply -f ~/promlab/faultlab/dash.yaml.
status=~"$status" to status="$status", set the variable to All. Open Inspector → Query:
sum by (status) (rate(faultexp_http_requests_total{status="(200|500)"}[2m0s]))
Multi-value / All variables are formatted as a regex (200|500), so it must be paired with =~. Also note that $__rate_interval is replaced with 2m0s (the kps data source timeInterval = 30s, with a floor of 4 × 30s; if it shows 1m, the data source's Scrape interval was set to 15s, which does not match the actual scrape interval). Discard the change (do not save it; saving a provisioned dashboard fails or gets overwritten).
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: faultlab-bad-ds
namespace: monitoring
labels: {grafana_datasource: "1"}
data:
bad.yaml: |
apiVersion: 1
datasources:
- name: Prometheus-typo
uid: prom-typo
type: prometheus
access: proxy
url: http://kps-kube-prometheus-stak-prometheus.monitoring:9090
EOF
sleep 40
curl -s -u admin:$GPW $G/api/datasources/uid/prom-typo/health | jq
{
"message": "… dial tcp: lookup kps-kube-prometheus-stak-prometheus.monitoring on 10.96.0.10:53: no such host …",
"status": "ERROR"
}
Verify DNS from inside the Grafana Pod: kubectl -n monitoring exec deploy/kps-grafana -c grafana -- wget -qO- http://kps-kube-prometheus-stack-prometheus.monitoring:9090/-/ready (Grafana images usually include busybox wget; check the actual image). Cleanup: kubectl -n monitoring delete cm faultlab-bad-ds (after the sidecar deletes the file, whether the loaded data source is removed too depends on the sidecar and provisioning settings; delete it in the UI if needed).
Case 1: panels turn “patchy” after the Prometheus scrape interval is changed
Problem: To save cost, scrapeInterval was changed from 15s to 60s, and many panels turned into dashed lines with gaps. Cause: The panels hard-code rate(x[1m]), so each window holds only one sample. Fix: Replace all of them with $__rate_interval, and confirm the data source timeInterval is also changed to 60s (kps syncs it automatically).
Case 2: a new colleague cannot see any dashboards
Problem: After SSO login the user is a Viewer, but all the dashboards are in a folder granted only to the “SRE” team. Fix: Set folder permissions by team, put shared dashboards in folders that Viewers can see, and map SSO groups to Grafana teams to avoid manual maintenance.
Case 3: a GitOps-provisioned dashboard was “overwritten” by UI edits
Problem: Someone edited a sidecar-provisioned dashboard in the UI and saved it under a new name; a few weeks later the two versions had diverged. Fix: Make provisioned dashboards read-only and route changes through Git (JSON or Grafonnet / Terraform, lesson 6 and the Terraform lesson); keep UI experiments in personal folders only.
Common errors and fixes
Datasource ${DS_PROMETHEUS} was not found
Cause: The imported dashboard contains a __inputs placeholder that was not mapped at import time, or was written as-is when provisioned through a ConfigMap. Fix: Replace the ${DS_PROMETHEUS} in the JSON with the actual uid, or add a datasource-type variable datasource and reference it ${datasource}.
Post "http://…:9090/api/v1/query_range": dial tcp: lookup … no such host / connection refused
Cause: The data source URL is wrong (Service name, namespace, port, routePrefix), or a NetworkPolicy blocks Grafana → Prometheus. Diagnosis: the data source health API; request from inside the Grafana Pod /-/ready.
Panel shows No data, but the Inspector Data tab shows data
Cause: Transformations (Filter by name / Organize fields) removed the fields, Overrides hid the series, Y-axis min/max pushed the values out of view, or unit conversion changed them. Fix: Disable the transformations one by one; check the overrides in Inspector → Panel JSON.
Variable dropdown is empty or “Templating … Error updating options”
Cause:label_values(metric, label) the metric in the query has no data for the current time range; an upstream variable in the dependency chain is empty; a regex filtered out every value. Diagnosis: Run count by (label) (metric) in Explore, then check the variable refresh setting (On dashboard load / On time range change).
The sidecar-provisioned dashboard does not appear
Diagnosis: The ConfigMap label must be grafana_dashboard: "1" (kps default label / labelValue); kubectl logs deploy/kps-grafana -c grafana-sc-dashboard; whether the JSON is valid (jq . file.json); uid in conflicts, the later-loaded file overwrites or errors (see the grafana container logs).
1. Without opening a browser, check whether Grafana's Prometheus data source can reach Prometheus.
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health | jq
2. As the Grafana backend, run sum(up) as an instant query and confirm how many frames it returns.
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query \
-d '{"from":"now-5m","to":"now","queries":[{"refId":"A","datasource":{"uid":"prometheus"},"expr":"sum(up)","instant":true}]}' | jq '.results.A.frames | length'The business team says: “The error rate panel in Grafana does not match the Prometheus alert: the panel shows 2%, the alert says 12%.” How would you investigate?
① Use the Inspector to pull the panel's actual expr and step, and compare them with the alert rule expr: the window ($__rate_interval vs [2m]), label filtering (whether the variable only selected some status values or Pods), aggregation method (avg of ratios vs ratio of sums). ② When the step is large, each panel point is the instantaneous result at that step, so a short spike may not land on a point; the alert evaluates every 30s and is therefore more “sensitive”. ③ Run both expressions in the Prometheus UI at the same timestamp to compare. The usual conclusion is that the query semantics differ; fix this by unifying them in one recording rule so the panel and the alert reference the same series.
Verified instructional videos
Official documentation
- Query and transform data (Query inspector, Query options)
- Prometheus data source
- Variables
- Provisioning
- Troubleshooting
Video storyboard (about 90 seconds)
Visual: a query leaves the browser, passes the Grafana backend and the data source plugin, reaches Prometheus and returns; six checkpoints along the way.
Narration: the panel's request is sent from the Grafana server, not from your browser.
Visual: the three Query inspector tabs open in turn: expr in Query, frames in Data, timing in Stats.
Narration: run the expr in Prometheus to tell whether the problem is before or after it.
Visual: the rate window changes from a fixed one minute to $__rate_interval, and the broken line becomes continuous.
Narration: the rate window uses the rate interval, which covers at least four scrape intervals.
Module 8 · Mixed fault blind box
- Without knowing the fault type in advance, complete the diagnosis in the order “trust → locate the segment → gather evidence → stop the bleeding → root cause and guardrail”.
- Covers 8 faults: connection refused, ServiceMonitor not selected, scrape timeout, Content-Type, sample limit, churn, alert window too small, Grafana data source reference error.
- After each fix, write one guardrail (a limit, an alert, a CI check or a convention).
What: overview of the 8 faults (answer table, do not look before the drill)
| # | Injection method | Symptom seen on call | Segment | Decisive evidence | Fix | Guardrail |
|---|---|---|---|---|---|---|
| 1 | Service targetPort → 8081 | FaultexpDown firing | L4 | lastError connect: connection refused | targetPort changed back to http | use a named port; check up after deployment |
| 2 | ServiceMonitor drops release: kps | faultexp panels are all empty, FaultexpDown does not fire | L2 | absent(up{job="faultexp"}) = 1; no such job in the config Secret | Add the label | absent alert; CI checks SM labels |
| 3 | DELAY=12 | FaultexpDown firing, sometimes never recovers | L4 | lastError context deadline exceeded; scrape_duration ≈ 10s | Fix the exporter (remove the delay) | scrape duration / timeout ratio alert |
| 4 | CT=application/octet-stream | exporter is down after an “upgrade” | L5 | received unsupported Content-Type … | Fix the exporter or fallbackScrapeProtocol | scrape with 3.x in staging before upgrading |
| 5 | SERIES=8000 | FaultexpDown firing, the exporter itself is healthy | L5 | sample limit exceeded; scrape_samples_scraped ≈ 8003 | Fix the instrumentation / metricRelabelings drop | sampleLimit + enforcedSampleLimit |
| 6 | SERIES=1000 + CHURN=1 | Prometheus memory keeps climbing, all targets up | L6 | rate(prometheus_tsdb_head_series_created_total[5m]) high; scrape_series_added stays non-zero | Remove the session label | series creation rate alert |
| 7 | Rule window [10s] + ERRORS=1 | 5xx clearly increases, FaultexpHighErrorRate does not fire | L7 | rule health ok, state inactive; the expression is empty when run in the UI | Change the window to [2m] | promtool test rules; window ≥ 4 × scrape interval |
| 8 | dashboard data source uid → prom-old | Faultlab dashboard red triangle | L8 | Datasource prom-old was not found | change the uid back prometheus | dashboards use a data source variable; CI validates the uid |
How: the pace of each diagnosis round (≤ 3 minutes)
- Read the symptom and ask: does up exist? What is its value? (half of locating the segment)
- Run the “standard diagnostic bundle” (step 2 on the lab page).
- Dig into the segment: lastError / config Secret / TSDB Status / rules and ALERTS / Grafana API.
- Fix and verify: up = 1, the alert recovers, the panel shows data.
- Write one guardrail sentence.
Where the 8 faults sit in the eight-stage chain
Interactive: in-browser fault blind box
Click “Draw a fault”; you only see the on-call symptoms. Choose a diagnostic command to view the (example) output, then decide the root cause; once you answer correctly, the fix and guardrail are shown. Scores are saved in this browser.
fault-box.sh: randomly inject faults on kind + kps
Save as ~/promlab/faultlab/fault-box.sh and chmod +x. Prerequisites: module 0's faultexp.yaml, and module 7's dash.yaml already exist. The script only modifies objects in the namespace faultlab .
#!/usr/bin/env bash
# Lesson 7 mixed fault blind box: ./fault-box.sh random | 1..8 | reveal | reset
set -uo pipefail
D=~/promlab/faultlab; NS=faultlab; ANS=$D/.answer
k() { kubectl -n $NS "$@" >/dev/null; }
base() {
k set env deploy/faultexp DELAY- CT- SERIES- CHURN- ERRORS-
# Delete and recreate, to make sure all fields added by the patch (fallbackScrapeProtocol, relabelings…) are removed
k delete servicemonitor faultexp --ignore-not-found
k delete prometheusrule faultexp-rules --ignore-not-found
kubectl apply -f $D/faultexp.yaml >/dev/null
k patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":"http"}]'
[ -f $D/dash.yaml ] && kubectl apply -f $D/dash.yaml >/dev/null
k rollout status deploy/faultexp --timeout=120s
}
f1() { k patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8081}]'
echo "Alert: FaultexpDown is firing."; }
f2() { k label servicemonitor faultexp release-
echo "User report: all panels on the Faultlab dashboard show No data, but there are no alerts."; }
f3() { k set env deploy/faultexp DELAY=12
echo "Alert: FaultexpDown is firing. The exporter team says the service is “very healthy”."; }
f4() { k set env deploy/faultexp CT=application/octet-stream
echo "The exporter was just “upgraded” to a new version, and FaultexpDown started firing afterwards."; }
f5() { k set env deploy/faultexp SERIES=8000
echo "The dev team just released a new feature that counts requests “per user”; FaultexpDown started firing afterwards, but the Pods are running normally."; }
f6() { k set env deploy/faultexp SERIES=1000 CHURN=1
echo "Platform alert: Prometheus memory keeps climbing. All targets are up."; }
f7() { k set env deploy/faultexp ERRORS=1
k patch prometheusrule faultexp-rules --type=json -p '[{"op":"replace","path":"/spec/groups/0/rules/3/expr","value":"sum(rate(faultexp_http_requests_total{status=~\"5..\"}[10s])) / sum(rate(faultexp_http_requests_total[10s])) > 0.1"}]'
echo "Users are complaining about many 500 errors, but FaultexpHighErrorRate has never fired."; }
f8() { kubectl -n $NS get cm faultlab-dashboard -o yaml \
| sed 's/{"uid": "prometheus", "type"/{"uid": "prom-old", "type"/' | kubectl apply -f - >/dev/null
echo "User screenshot: a red triangle appears in the top-left corner of a Faultlab dashboard panel."; }
case "${1:-random}" in
reset) base; rm -f $ANS; echo "Reset to a clean baseline (wait about 1 minute for Prometheus to reload)";;
reveal) echo "Injected fault number this round: $(cat $ANS 2>/dev/null || echo none)";;
random|[1-8])
base
n=${1:-random}; [ "$n" = random ] && n=$(( RANDOM % 8 + 1 ))
echo $n > $ANS
echo "Fault injected; the symptoms fully appear after 2–4 minutes. On-call symptom:"; f$n;;
*) echo "Usage: $0 random|1..8|reveal|reset"; exit 1;;
esac
Note: kubectl apply -f faultexp.yaml in the Deployment has no env; applying it alone does not delete the kubectl set env variables added by it (they are not in last-applied), so the script deletes them explicitly. After fault 6 is injected, the series in the head are released only after the next head compaction (module 5). Compose environments (~/promlab) can reproduce #3, #4, #5 and #7 by hand: set the same environment variables on a test exporter other than myapp in the compose file.
Lab 8: blind box drill (about 3 minutes per round, at least 4 rounds)
cd ~/promlab/faultlab && chmod +x fault-box.sh && source env.sh ./fault-box.sh random
Fault injected; the symptoms fully appear after 2–4 minutes. On-call symptom: Alert: FaultexpDown is firing. The exporter team says the service is “very healthy”.
pq 'up{job="faultexp"}'; pq 'absent(up{job="faultexp"})'
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastScrapeDuration) \(.lastError)"'
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'rate(prometheus_tsdb_head_series_created_total[5m])'
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | "\(.name) \(.health) \(.state)"'
pq 'ALERTS{namespace="faultlab"} or ALERTS{alertname=~"Faultexp.*"}'# L2: is it in the config
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -c 'serviceMonitor/faultlab/faultexp'
kubectl -n faultlab get servicemonitor faultexp --show-labels
# L1: look at the exporter directly, bypassing Prometheus
kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- -s -o /dev/null \
-w 'code=%{http_code} ct=%{content_type} time=%{time_total}s size=%{size_download}\n' http://faultexp.faultlab:8080/metrics
# L7: rule expression
kubectl -n faultlab get prometheusrule faultexp-rules -o jsonpath='{.spec.groups[0].rules[3].expr}{"\n"}'
# L8: Grafana
curl -s -u admin:$GPW $G/api/dashboards/uid/faultlab | jq -c '[.dashboard.panels[].datasource]'./fault-box.sh reveal, then apply the fix from the fix column on the “Theory” page and verify (up = 1, the alert recovers or fires correctly, the panel shows data), and then ./fault-box.sh reset move on to the next round.round | symptom | up state | segment | decisive evidence | root cause | fix | guardrail | time spent 1 | | | | | | | | 2 | | | | | | | |
Case 1: overlapping faults
Problem: One release introduced high-cardinality labels (#5) and switched the exporter to a new framework that returns text/html framework (#4). After the on-call engineer fixed the Content-Type, the target went down again immediately due to the sample limit. Lesson: In L5, several checks run in sequence (first choose the parser, then count the samples), so fixing one exposes the next; re-read lastError after every fix.
Case 2: turning the blind box into a team drill
Approach: The platform team injects one fault a week in a shared kind environment, and new members diagnose it within a time limit; the review notes are turned into the problem bank and on-call handbook in lesson 9. Result: In real incidents, the time to “locate the segment” is clearly shorter (self-reported by the team; not quantitatively verified).
Case 3: the guardrail checklist enters the release process
Approach: Checks for every new service before go-live: ServiceMonitor labels and sampleLimit, absent alerts, rule unit tests, dashboard data source variables, Content-Type conventions. Enforced in CI by promtool check rules,promtool test rules,kubeconform and a jq check.
Interactive troubleshooting tree: Prometheus & Grafana deep faults
Start from the symptom you see and choose step by step; the leaf nodes give the diagnostic commands and fixes.
1. Use one command to tell whether faultexp's up is “missing”, “0” or “1”.
up{job="faultexp"} or on() vector(-1)Returns -1 when the series does not exist (or on() vector(-1) the or-fallback supplies a value when the left side is empty).
2. Find all targets with a non-empty lastError, and count them grouped by lastError.
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.lastError!="") | .lastError' \ | sed -E 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(:[0-9]+)?/IP/g' | sort | uniq -c | sort -rn
You injected a fault, and the symptom is “Prometheus memory keeps rising, all targets up”. A colleague suggests restarting Prometheus. Please assess this.
A restart does not fix churn: new series are still being created. It also triggers WAL replay (the more series, the slower it is), during which there is no data and no alert evaluation, and it may even enter an OOM loop if the replay runs out of memory. The right order: use rate(prometheus_tsdb_head_series_created_total[5m]) and sum_over_time(scrape_series_added[5m]) to find the churn source by job → drop or fix the instrumentation with metricRelabelings → wait for the next head compaction to free memory → add a series creation rate alert. Only consider temporarily raising the limit when memory is about to hit OOM.
Verified instructional videos
Official documentation
Video storyboard (about 90 seconds)
Visual: the blind box opens, 8 fault cards spin and stop on a card that reads only “FaultexpDown firing”.
Narration: look only at the symptom, not the answer.
Visual: the terminal runs up, absent, targets, TSDB metrics and rules in turn; the matching blocks in the eight-stage chain turn green one by one, and the last one turns red.
Narration: first ask whether up exists and what its value is, then gather evidence segment by segment.
Visual: after the fix, up becomes 1, and a guardrail is written in the record table.
Narration: every fix leaves behind one guardrail.
Command cheat sheet
ALERTS{alertname="Watchdog"}
count by (job) (up == 0)
absent(up{job="X"})
up{job="X"} or on() vector(-1)
time() - prometheus_rule_group_last_evaluation_timestamp_seconds
rate(prometheus_notifications_dropped_total[5m])curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/NS/NAME/0" | jq '.data.activeTargets[]|{health,lastError,lastScrapeDuration}'
curl -s "$P/api/v1/targets?state=dropped"
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode scrapePool=… --data-urlencode labels='{…}'
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep job_name
kubectl get events -n NS --field-selector involvedObject.kind=ServiceMonitorcurl -s "$P/api/v1/status/tsdb?limit=10" | jq .data kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=10
prometheus_tsdb_head_series rate(prometheus_tsdb_head_series_created_total[5m]) topk(10, sum by (job) (sum_over_time(scrape_series_added[5m]))) topk(10, max by (job) (scrape_samples_scraped)) increase(prometheus_target_scrapes_exceeded_sample_limit_total[1h])
curl -s "$P/api/v1/query_range" --data-urlencode query='…' -d start=… -d end=… -d step=30 -d stats=all \
| jq '.data.stats.samples|{seriesTouched,peakSamples,totalQueryableSamples}'
prometheus:
prometheusSpec:
queryLogFile: /dev/stdout
query: {maxSamples: 50000000, timeout: 2m, maxConcurrency: 20}curl -s $P/api/v1/status/tsdb/blocks | jq '.data.blocks[]|{ulid,minTime,maxTime,level:.compaction.level}'
curl -s $P/api/v1/status/walreplay
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus
increase(prometheus_tsdb_compactions_failed_total[3h]) > 0 prometheus_tsdb_wal_storage_size_bytes prometheus_tsdb_storage_blocks_bytes rate(prometheus_tsdb_wal_corruptions_total[1h])
curl -s "$P/api/v1/rules" | jq -r '.data.groups[].rules[]|select(.health!="ok")|[.name,.lastError]|@tsv' AMT="kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093" $AMT alert query -s -i $AMT silence query $AMT config routes show $AMT config routes test namespace=X severity=critical alertname=Y
curl -s -u admin:$GPW $G/api/health
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query \
-d '{"from":"now-5m","to":"now","queries":[{"refId":"A","datasource":{"uid":"prometheus"},"expr":"up","instant":true}]}'
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20# ServiceMonitor
spec:
sampleLimit: 5000
labelLimit: 30
labelValueLengthLimit: 512
endpoints:
- port: http
scrapeTimeout: 10s # ≤ interval
metricRelabelings:
- {sourceLabels: [__name__], regex: 'debug_.*', action: drop}
# kps values
prometheus:
prometheusSpec:
enforcedSampleLimit: 50000
retention: 10d
retentionSize: 40GiBQuick reference for error messages
| Error (original text) | Segment | See |
|---|---|---|
… connect: connection refused | L4 | Module 2 |
… context deadline exceeded | L4 | Module 2 |
server returned HTTP status 403 Forbidden | L4 | Module 2 |
body size limit exceeded | L4 | Module 2 |
received unsupported Content-Type "…" and no fallback_scrape_protocol specified for target | L5 | Module 2 |
non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for target | L5 | Module 2 |
sample limit exceeded | L5 | Module 3 |
label_limit exceeded (metric: …, number of labels: N, limit: M) | L5 | Module 3 |
target_limit exceeded (number of targets: N, limit: M) | L2 | Module 3 |
scrape timeout greater than scrape interval for scrape config with job name "…" | Config | Module 2 |
query processing would load too many samples into memory in query execution | L7 | Module 4 |
query timed out in … | L7 | Module 4 |
exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX) | L7 | Module 4 |
found duplicate series for the match group … on the right hand-side of the operation / multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) | L7 | Module 4 |
vector contains metrics with the same labelset after applying alert labels | L7 | Module 6 |
Replaying WAL, this may take a while (stays for a long time) | L6 | Module 5 |
Encountered WAL read error, attempting repair | L6 | Module 5 |
Datasource … was not found | L8 | Module 7 |
Comprehensive lab + final quiz
You are the monitoring lead for the platform team. The company has just upgraded from Prometheus 2.x to 3.16, and over the past month there were three incidents: “alerts silent for two days”, “Prometheus OOMs every day” and “a dashboard overloading Prometheus”. Please use the kind cluster lab in the faultlab namespace, and use fault-box.sh to inject faults 1–8 in turn, completing “locate the segment → evidence → fix → guardrail” for each one, and finally submit the diagnosis record table and self-monitoring and guardrail checklist.
dash.yaml and module 8 fault-box.sh.
cd ~/promlab/faultlab && source env.sh && ./pf.sh
export GPW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
kubectl apply -f dash.yaml && ./fault-box.sh reset./fault-box.sh 1; sleep 90; pq 'up{job="faultexp"}' # 0 → lastError: connection refused
./fault-box.sh 2; sleep 90; pq 'absent(up{job="faultexp"})' # 1 → no such job in the config Secret./fault-box.sh 3; sleep 90 # context deadline exceeded ./fault-box.sh 4; sleep 90 # received unsupported Content-Type …; fix it in two ways: “fix the exporter” and fallbackScrapeProtocol ./fault-box.sh 5; sleep 90 # sample limit exceeded; stop the bleeding with metricRelabelings drop
./fault-box.sh 6; sleep 240 pq 'rate(prometheus_tsdb_head_series_created_total[2m])' pq 'topk(3, sum by (job) (sum_over_time(scrape_series_added[2m])))'
./fault-box.sh 7; sleep 240 # rule health ok, state inactive; the expression is empty when run in the UI ./fault-box.sh 8; sleep 40 # Faultlab dashboard: Datasource prom-old was not found curl -s -u admin:$GPW $G/api/dashboards/uid/faultlab | jq -c '[.dashboard.panels[].datasource]'
# Prometheus self-monitoring and guardrail checklist
## A. Meta-monitoring
- [ ] Connect Watchdog to an external dead man's switch (alert when it stops arriving)
- [ ] For each critical job: an absent(up{job=…}) or target-count-drop alert
- [ ] Rule group missed evaluations: rate(prometheus_rule_group_iterations_missed_total[5m]) > 0
- [ ] Notification pipeline: prometheus_notifications_dropped_total, alertmanager_notifications_failed_total
## B. Scraping
- [ ] All ServiceMonitors carry the release label (CI-checked) and use named ports
- [ ] Warn when scrape duration / timeout > 0.8 (extra_scrape_metrics)
- [ ] Before upgrading Prometheus, do a full scrape in staging (Content-Type)
## C. Cardinality
- [ ] Set sampleLimit / labelLimit on every ServiceMonitor; set enforcedSampleLimit in kps
- [ ] Series creation rate alert (compared with 1 day earlier)
- [ ] Weekly review of the top 10 from TSDB Status / promtool tsdb analyze
- [ ] Instrumentation review: no unbounded labels such as user_id, request_id or raw URLs
## D. Queries
- [ ] Use recording rules for high-traffic panels and SLOs
- [ ] Dashboard refresh ≥ 1m, default range ≤ 6h, rate uses $__rate_interval
- [ ] Enable queryLogFile during investigations
## E. Storage
- [ ] Set retention and retentionSize together; disk forecast alert
- [ ] Alerts for compactions_failed and wal_corruptions
- [ ] Memory limit covers the WAL replay peak; evaluate memory-snapshot-on-shutdown
## F. Alerting
- [ ] promtool test rules for rules in CI; rate window ≥ 4 × scrape interval
- [ ] Run amtool config routes test on Alertmanager config changes
- [ ] group_by, inhibition rules and silences must have an expiry time and a reason
## G. Grafana
- [ ] Dashboards use data source variables; provisioned dashboards go through Git
- [ ] Synthetic monitoring of data source health and /api/ds/query./fault-box.sh reset kubectl delete namespace faultlab kubectl -n monitoring delete cm faultlab-bad-ds --ignore-not-found ./pf.sh stop; unset GPW # If you changed the kps Alertmanager config (module 6), run helm upgrade again with your standard values file
Open-ended self-check
1. Why does sample_limit choose “fail the whole scrape” rather than “keep only the first N samples”?
Keeping only some samples produces incomplete and unpredictable data (which ones are kept depends on the output order), and aggregates quietly go wrong; failing the whole scrape sets up = 0, triggers an alert, makes the problem visible immediately, and also protects Prometheus's memory.
2. How would you design a mechanism that detects “silence” in the monitoring system?
Watchdog always firing → Alertmanager → external dead man's switch service (alerts when it stops receiving); a second Prometheus (or a managed service) monitors the primary Prometheus's up and rule evaluation; absent alerts cover the critical jobs.
3. Why is the relationship between the number of head series and Prometheus memory not strictly linear?
Memory also includes chunk buffers, temporary query memory, WAL write buffers and Go GC headroom; label string lengths vary; m-mapped chunks go through the page cache. Capacity planning can only use measured ratios, and it must reserve headroom for query and replay peaks.
4. When should query.max-samples be raised?
Only after confirming the queries themselves are reasonable (recording rules are used, range and step are sensible), the business really needs it, Prometheus has memory headroom, and concurrency is under control. A better option is usually query splitting and downsampling in Thanos/Mimir.
5. Why is $__rate_interval recommended for Grafana's rate window?
It guarantees the window covers at least 4 scrape intervals and is not less than step + one scrape interval: there are enough samples when the time range or scrape interval changes, and no data is missed between adjacent points.
6. Which faults in this lesson show up in a different form in managed Prometheus (Azure Monitor / AMP)?
Cardinality shows up directly as cost and quotas (ingestion limits, active series limits); TSDB internals (WAL, compaction, disk) are the cloud provider's responsibility and are no longer your fault; scrape faults still exist in managed collectors (ama-metrics, AMP scraper), but the observation window becomes that collector's own logs and metrics; query limits become service quotas (lessons 3 and 4).
Sources and version notes
| Topic | Verified conclusion | Source (verification date) |
|---|---|---|
| Versions | Prometheus v3.16.0 (2026-11-05); Alertmanager v0.35.0 (2026-11-09); Grafana v13.3.1 (2026-11-10; the 12.x in the course spec is outdated); kube-prometheus-stack 93.3.0 (2026-11-13, Operator v0.95.2, Prometheus image v3.16.0-distroless, Grafana sub-chart 14.4.1 / appVersion 13.3.1) | GitHub Releases API:prometheus,alertmanager,grafana,helm-charts(2026-11-15) |
| Scrape errors | sample limit exceeded,label_limit exceeded (…),label_name_length_limit …,label_value_length_limit …,target_limit exceeded (…),body size limit exceeded,server returned HTTP status %s; after the limit is exceeded, parsing continues to report the real sample count; on failure, an empty body is appended to write the stale marker | v3.16.0 scrape/scrape.go,scrape/target.go |
| Content-Type | Four kinds of … no fallback_scrape_protocol specified for target error messages; the recognised types: application/openmetrics-text,application/vnd.google.protobuf,text/plain | v3.16.0 model/textparse/interface.go |
| Scrape configuration | default scrape_interval 1m, scrape_timeout 10s, evaluation_interval 1m; the raw error when timeout > interval; the default scrape_protocols order; extra_scrape_metrics becomes a configuration item,--enable-feature=extra-scrape-metrics being phased out | v3.16.0 config/config.go,cmd/prometheus/main.go |
| Query limits | --query.max-samples=50000000,--query.timeout=2m,--query.max-concurrency=20,--query.lookback-delta=5m; raw error messages; 11 000 point limit; stats the parameter accepts only true/all | v3.16.0 cmd/prometheus/main.go,promql/engine.go,web/api/v1/api.go,util/stats/query_stats.go |
| TSDB | blocks 2h; compactable = span > 1.5 × block range; block range grows ×3, maximum min(retention 10%, 31d); WAL segment 128 MiB, checkpoint takes the first 2/3 of segments; samples-per-chunk 120; WAL compression defaults to snappy; default retention 15d, the retention command-line flag is marked DEPRECATED (use the config file instead), new retention.percentage added; size-based retention includes the WAL and head chunks; raw log messages | v3.16.0 tsdb/db.go,tsdb/head.go,tsdb/compact.go,tsdb/wlog/wlog.go,config/config.go |
| TSDB status API | /api/v1/status/tsdb fields and limit (default 10, maximum 10000); /status/tsdb/blocks,/status/walreplay,/targets/relabel_steps | v3.16.0 web/api/v1/api.go |
| promtool | tsdb analyze (--limit default 20, --extended, --match; by default it analyses the last block) output headings; tsdb list -r; check service-discovery | v3.16.0 cmd/promtool/main.go,tsdb.go |
| Self-monitoring metrics | prometheus_target_scrapes_exceeded_sample_limit_total and other scrape metrics; prometheus_tsdb_*; prometheus_rule_*; prometheus_notifications_*; prometheus_engine_* | v3.16.0 scrape/metrics.go,tsdb/*,rules/group.go,notifier/metric.go,promql/engine.go |
| Rules | vector contains metrics with the same labelset after applying alert labels; --rules.alert.resend-delay=1m; notification queue 10000 | v3.16.0 rules/alerting.go,rules/recording.go,cmd/prometheus/main.go |
| Operator | ServiceMonitor fields sampleLimit,labelLimit,labelNameLengthLimit,labelValueLengthLimit,targetLimit,bodySizeLimit,fallbackScrapeProtocol (PrometheusText0.0.4 etc.); Prometheus CR enforced*,query,queryLogFile,scrapeFailureLogFile,tsdb.outOfOrderTimeWindow,retentionPercentage; default serviceDiscoveryRole = Endpoints; config Secret prometheus-<name> 's prometheus.yaml.gz emits an Event when it rejects a resource | Operator v0.95.2 pkg/apis/monitoring/v1/*.go;Troubleshooting |
| kps defaults | selector NilUsesHelmValues=true (release: kps), namespace selector {}; retention 10d, walCompression true, enforcedSampleLimit false; Alertmanager default route group_by [namespace], 30s/5m/12h, receiver null, Watchdog → null, three severity inhibition rules; Grafana sidecar label grafana_dashboard/grafana_datasource = "1", data source uid prometheus, timeInterval follows scrapeInterval, dashboards searchNamespace ALL; adminPassword not set | kube-prometheus-stack 93.3.0 values.yaml,templates/grafana/configmaps-datasources.yaml |
| Image | distroless image contains /bin/promtool, no shell; the Alertmanager image is based on busybox and includes amtool | v3.16.0 Dockerfile.distroless; Alertmanager v0.35.0 Dockerfile |
Video verification notes
All the videos below were verified for title and channel through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json, 2026-11-15) for title and channel: PromLabs “Don't Make These 6 Prometheus Monitoring Mistakes…” (NEMsO1qeI1s), “Relabeling in Prometheus…” (mXvuKAb6ZwY); 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 - Step-by-Step” (HOmdYtsB950); Prometheus Monitoring “PromCon 2018: Bomb Squad…” (MHiXP5QW4_U), “PromCon 2024 - Inside a PromQL Query…” (t53-7vUhbqY), “PromCon EU 2022: Anatomy of a Slow Query…” (t9dw698NMvs), “Optimizing PromQL Queries - Aliaksandr Valialkin…” (w6hj0VSnw5U), “PromCon Online 2020 - TSDB WTF…” (zTH7DKAWqHc), “PromCon 2016: The Prometheus Time Series Database…” (HbnGSNEjhUc), “PromCon EU 2019: Improved Alerting…” (RlOA5KgBkz8); CNCF “Tracking Cardinality Explosions In Flight…” (EdGNwAa-vGk); Cloud Explainers “Prometheus TSDB Churn…” (ilyNu6RmkU4); USENIX “SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB” (LOZQFT8Dcq0); FOSSASIA “Lifecycle of a Sample in the Prometheus TSDB - Ganesh Vernekar” (35TAaAESLcc); Tech with Lian “Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences…” (IoCz7NJ-LT0); DevOps Simplified “Prometheus Alerting Rules for Beginners…” (Op0cUlooq4k); Grafana “GrafanaCONline: Prometheus rate queries in Grafana” (09bR9kJczKM), “How to build a Prometheus query in Grafana” (5VrjOzIOJPw), “Understanding Dashboards in Grafana…” (vTiIkdDwT-0). Durations, upload dates and content details were not checked one by one; most were recorded in the Prometheus 2.x / Grafana 9–11 era, so the version details follow this lesson. All videos are in English.
Audio narration notes
The “Audio” tab reads the narration script aloud using the browser's Web Speech API (en-US), with English terms pronounced in en-US; the result depends on the operating system's voice packs. The environment that generated this courseware could not call a TTS service, so no MP3 is embedded; the narration script can be handed directly to a TTS tool to produce audio. This courseware also cannot generate video directly, so a storyboard is provided for each module.
Known limitations
- All commands in this lesson were written from the Prometheus v3.16.0 / Operator v0.95.2 source code, the kps 93.3.0 values and the official documentation,and have not actually been run against a kind cluster in the environment that generated this courseware; the IPs, Pod name suffixes, ULIDs, series counts, memory and timings in the “Expected output” are examples.
- The Grafana 13 error and health-check texts (for example “Successfully queried the Prometheus API.” and “Datasource … was not found”) were not checked word for word against the Grafana 13.3.1 source (the Prometheus data source code has been moved out of the main repository); follow the actual UI. Whether the Grafana image includes wget has not been verified.
- The exact fields of the Prometheus logs (
source=line number, extra key-value pairs) change between versions; the courseware only guarantees that the message text (msg) comes from the v3.16.0 source. - The memory cost per active series (estimated as 4 KiB in the animation) is an empirical value, not a benchmark; the query cost calculator is a simplified model.
- kps's default scrapeInterval is empty (determined by the Operator's default of 30s); the default searchNamespace of the datasource sidecar has not been checked line by line; where relabel_steps appears in the UI should follow the actual UI.
- The curlimages/curl:8.11.1 and python:3.13-alpine image tags are written as commonly available versions and have not been pulled and verified in this environment.
- Lessons 1–6 and 8 were written in parallel with this lesson; cross-lesson references follow the course's unified conventions (myapp, ~/promlab, the kind cluster lab, the namespace monitoring, release kps), and the specific page content follows the final version of each lesson.