Prometheus & Grafana Hour 7: Deep Troubleshooting, Optimization and Advanced Topics

Starting from “the alert fired / the panel went empty”, follow the complete signal chain to find the root cause: why a target is down, why series explode, why a query is slow, why the TSDB eats all the memory and disk, why alerts stay silent or keep firing, and why Grafana shows No data
Prometheus v3.16.0Alertmanager v0.35.0Grafana v13.3.1kube-prometheus-stack 93.3.0Verified against source code 2026-11-15
Overall learning objectives
  • 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 3 received 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; use sample_limit,label_limit,metric_relabel_configs and the Operator's enforcedSampleLimit to set guardrails.
  • Optimize slow PromQL and dashboards: understand “loaded samples = series × samples per series”, read the query processing would load too many samples into memory and query 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,for not met, expression returns no data,absent() missing, Alertmanager routing / inhibition / silences) and alert storms (grouping,group_interval, flapping and keep_firing_for).
  • Troubleshoot Grafana: data source connectivity, Query inspector,$__rate_interval and step, template variables, sidecar provisioning, permissions, and “Datasource … was not found”.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (kind cluster lab + kps, namespace faultlab)
0Before classPreparation: fault-injection environmentDeploy a controllable faultexp exporter (latency, Content-Type, series count, churn and error rate can all be toggled with environment variables) + ServiceMonitor + PrometheusRuleEnvironment self-check listBaseline: up{job="faultexp"} == 1
100–06Troubleshooting methodology: from alert to root causeEight-stage chain model, observation windows per stage, self-monitoring metrics, “stop the bleeding before finding the root cause”Alert → chain-stage locatorThe same alert, three completely different root causes
206–13Scrape failures: target down, timeouts and service discoverylastError interpretation, scrape timeout, Content-Type fallback, ServiceMonitor selection, relabel debugging,targets/relabel_stepsScrape pipeline fault simulatorInject connection refused / timeout / Content-Type / selector mismatch
313–21Cardinality explosion: label design and limitsSeries = label value combinations, TSDB Status,topk(count by (__name__)), churn,sample_limit, label limits, metric_relabel dropsCore animation: effect of cardinality explosion on memory and queriesuser_id label explosion → sample limit exceeded → fix
421–28Query performance: slow PromQL and dashboard optimizationSample loading model,--query.max-samples,--query.timeout, 11,000-point limit, recording rules, query stats, dashboard anti-patternsQuery cost calculatorBefore/after comparison of the same panel
528–35TSDB internals: head block, WAL, compaction and diskhead, WAL segments and checkpoints, m-map chunks, 2h blocks, compaction levels, retention (time / size / percentage), out-of-order samples, disk fullCore animation: TSDB head / WAL / compactionForce-kill a Pod and watch the WAL replay; read the block list and logs
635–42Alerts not firing or alert stormsrules not loaded, window too small,for,absent(), rule evaluation failures, Alertmanager grouping / inhibition / silences, storm governanceAlert pipeline stage-by-stage checker + grouping calculatorWrite an alert that “never fires” and fix it; amtool routing test
742–50Grafana troubleshooting: data sources, panels and permissionsRequest path (browser → Grafana backend → Prometheus), Query inspector, step and $__rate_interval, variables, sidecar provisioning, permissionsPanel request path tracerBad data source + bad variable + wrong step, fix them one by one
850–60Mixed fault blind box8 kinds of faults injected at random, diagnose from symptoms onlyIn-browser fault blind box + interactive troubleshooting treefault-box.sh random
—After classCheat sheet · Comprehensive labDiagnose all 8 faults one by one + produce a monitoring-system “self-monitoring and guardrails” checklistFinal quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / pagesLab
Eight-stage chain localization✓✓✓✓✓✓✓✓up,/targets,/rulesM1 three root causes
Scrape and service discovery✓✓···✓·✓/api/v1/targets,relabel_steps, Operator eventsFour scrape faults
Cardinality and churn··✓✓✓··✓/api/v1/status/tsdb,promtool tsdb analyzeuser_id explosion
Limits and guardrails·✓✓✓···✓sampleLimit,labelLimit,--query.max-samplessample limit
Query and dashboard performance··✓✓··✓·stats=all, recording rules,$__rate_intervalpanel optimization
TSDB internals and disk··✓·✓··✓promtool tsdb list -r,/status/tsdb/blocksWAL replay
Alert pipeline✓····✓·✓amtool config routes test,ALERTSAlert that never fires
Grafana troubleshooting✓··✓··✓✓Query inspector, sidecar logsBad data source

Content not covered in this lesson (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Prometheus architecture, metric types, PromQL basics, Grafana introductionBasic contentLesson 1
Writing recording / alerting rules, Alertmanager routing syntax, storage planningThis lesson only covers what to do when they failLesson 2
Troubleshooting managed Prometheus and Grafana on Azure / AWSIdentity and quota issues of managed servicesLesson 3,Lesson 4
kube-prometheus-stack installation, writing ServiceMonitor / PrometheusRuleThis lesson injects faults on top of itLesson 5
Thanos / Mimir, remote_write tuning, SLO and burn rateArchitecture-level topicsLesson 6
Pod-level troubleshooting (the Kubernetes mechanics behind CrashLoopBackOff and OOMKilled)Belongs to Kubernetes itselfKubernetes lesson
Logs and tracing: Loki, Tempo and OpenTelemetryLesson 8Lesson 8
50 production problems, 50 interview questionsLesson 9 (optional)Lesson 9

How to use this courseware

10 pages per module
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”.
Learning progress
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).
Chinese voice
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.
Version notes This course uses Prometheus v3.16.0 (2026-11-05) as its baseline; error messages, parameter defaults and metric names were checked against the v3.16.0 source code (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

Deploy a “can be broken at will” exporter, faultexp, on the kind cluster lab + kube-prometheus-stack (release kps) from Lesson 5. All faults are toggled through environment variables or labels and can be reset at any time
Before class ≈ 10 minkind · kps 93.3.0Local lab, zero cost
Prerequisites
  • Completed Lesson 5: kind cluster lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring kps is deployed, and myapp runs in namespace myapp. This lesson does not inject faults into myapp, but creates a new namespace faultlab, 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 (services prometheus:9090,alertmanager:9093,grafana:3000,myapp:5000…) can complete the query, TSDB and promtool labs in Modules 3–5. In the commands, replace kubectl exec … -c prometheus -- with docker compose exec prometheus is 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 variableDefaultEffect (simulated fault)
DELAY0Seconds to sleep before each /metrics response → scrape timeout
CTtext/plain; version=0.0.4; charset=utf-8Response Content-Type → Prometheus 3's strict Content-Type validation
SERIES0Number of extra series to output with user_id label → cardinality explosion / sample limit
CHURN01 = session Label values change every 30 seconds → series churn
ERRORS01 = 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”.

Environment self-check list

Module 1 · Troubleshooting methodology: from alert to root cause

00:00 – 06:00 · An alert is only a symptom. First ask “can I trust the monitoring system itself?”, then locate the problem to one stage of the signal chain, and only then fix it
6 minEight-stage chain model★★★★★
Learning objectives
  • 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.
Prerequisites: Lesson 1 scrape-cycle animation, Lesson 2 alert lifecycle. Importance:★★★★★

What: the eight-stage chain model

StageWhat happens (Prometheus 3.16 components)Typical symptoms / errorsPrimary observation window
L1 ExposeThe application / exporter outputs metrics in text or protobuf format on an HTTP endpointEndpoint returns 404 or 500, extremely slow responses, non-standard Content-Type, illegal metric namescurl -si http://target/metrics | head
L2 DiscoveryService discovery (kubernetes_sd endpoints / endpointslice roles) produces candidate targets; in kps the Operator first serviceMonitorSelector selects ServiceMonitors and then generates the configTarget never appears; up series does not exist/service-discovery, Operator events, config Secret prometheus-<CR name>
L3 target relabelrelabel_configs (in the Operator, the relabelings) decides whether to keep or drop targets and generates job/instance and other labelsTarget appears in “Dropped targets”; labels do not match expectations/api/v1/targets?state=dropped,/api/v1/targets/relabel_steps
L4 ScrapeHTTP GET (with Accept negotiation), timeout scrape_timeout TLS / authentication, body size limitup == 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 limitChoose 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 StorageWrite to the head block and WAL; background compaction into 2h blocks; retention and deletionMemory 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 rulesPromQL engine runs instant / range queries; rule groups are evaluated according to evaluation_interval schedulequery 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 presentationAlerts are sent to Alertmanager (grouping, inhibition, silences, routing, receivers); the Grafana backend proxies queries and renders panelsAlert 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

  1. 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).
  2. Locate the stage: which of L1–L8 does the symptom fall into? Key question: does the series exist? Is the value 0 or missing? lastError What does it write?
  3. Gather evidence: use read-only means only — pages, APIs, self-monitoring metrics, logs — save the evidence (screenshots / JSON) before changing anything.
  4. 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).
  5. 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 faultMonitoring system faultObservation error
Examplemyapp returns 500Scrape timeout, ServiceMonitor not selected, TSDB OOMWindow too small, step too large, lookback ghosts
upUsually 1 (the application can still expose metrics)0 or absent1
Who handles itApplication teamPlatform / monitoring teamThe person writing the query
First observation windowBusiness metrics and logs/targets, self-monitoring metricsQuery inspector, PromQL semantics
Common misconceptions① “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

L1 Expose/metrics L2 DiscoverySD · Operator L3 relabelkeep / drop L4 ScrapeHTTP · timeout L5 Parse & limitlimit · CT L6 Storagehead · WAL L7 Query & rulesPromQL L8 Notify & presentAM · Grafana Failure symptom: target does not exist → up series missing Failure symptom: up == 0 + lastError Failure symptom: data exists but is slow / dropped / not notified / not displayed Observation window curl -si/service-discoveryrelabel_steps/targetsscrape_samples_*/tsdb-status/rules · statsamtool · inspector Operator eventsscrape_duration_secondsexceeded_*_totalhead_seriesevaluation_failuresnotifications_dropped Meta-monitoring runs through all eight stages: Watchdog dead man's switch + Prometheus self-metrics + a second Prometheus monitoring each otherThe worst form of “monitoring is broken” is not false alarms but silence
Figure 1-1 Eight-stage chain: failures in the three left stages make targets “disappear”; failures in the two middle stages make up drop to 0; failures in the three right stages leave data that exists but cannot be used

Decision flow from alert to root cause

Alert / empty panelSymptom Is monitoring trustworthy?Watchdog · self-monitoring Series does not exist → L1–L3 up == 0 → L4–L5 up == 1 → L6–L8 or business Gather evidence → stop the bleeding Root cause + guardrail
Figure 1-2 Asking just “does up exist, and what is its value?” narrows the search space to two or three stages

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.

Select a symptom above.
$ # Suggested diagnostic commands will appear here

Read-only commands used in the five-step method

Command / queryStageDescription
count by (job) (up),count by (job) (up == 0)L2–L5Target 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–L5Each target's health,lastError,lastScrapeDuration,scrapePool
curl -s "$P/api/v1/targets?state=dropped"L3targets dropped by relabel and their discoveredLabels
ALERTS{alertstate="firing"}L7Prometheus internal alert-state series (pending / firing)
time() - prometheus_rule_group_last_evaluation_timestamp_secondsL7How 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_discoveredL8whether 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)'AllPrometheus 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.

Root cause A: target disappears (L2)— scale the Deployment down to 0.
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.

Root cause B: scrape timeout (L4)— response delayed by 12 seconds, exceeding 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-.

Root cause C: observation error (L7)— the data is intact; the query was written wrong.
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).

Review: fill in a three-row record (same symptom, different stage, different observation window).
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 first

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

Command-line exercise
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'
Scenario analysis
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

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
English · a Prometheus founding member talks about common mistakes, including missing absent alerts, cardinality, etc.; a good introduction to this lesson
▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · architecture review: where the scraping, storage and alerting components sit (corresponding to the eight-stage chain)

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% in the “Quiz”

Module 2 · Scrape failures: target down, timeouts and service discovery

06:00 – 13:00 · lastError is the diagnostic report Prometheus writes for you; first distinguish “target does not exist” from “target exists but the scrape fails”, then check stage by stage
7 minPrometheus 3.16 · Operator 0.95★★★★★
Learning objectives
  • 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, and scrape_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 …, and non-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=dropped and /api/v1/targets/relabel_steps to debug relabel.
Prerequisites: Lesson 1 scrape configuration, Lesson 5 ServiceMonitor. Importance:★★★★★

What: what happens internally during one scrape (v3.16.0 scrape/scrape.go)

  1. Scheduling: each target has its own scrape loop, running every scrape_interval period; the start offset is determined by hashing the target's labels (to avoid scraping all targets at once).
  2. Request: HTTP GET, with the Accept header, negotiated by scrape_protocols (default: OpenMetrics 1.0.0 → OpenMetrics 0.0.1 → Prometheus text 1.0.0 → text 0.0.4); the whole request is bounded by scrape_timeout (default 10s, and must not exceed scrape_interval, otherwise config loading reports scrape timeout greater than scrape interval for scrape config with job name "…").
  3. Response check: status code not 200 → server returned HTTP status 404 Not Found; body exceeds body_size_limit → body size limit exceeded.
  4. Choose parser: Prometheus 3 strictly selects the parser by Content-Type . If the value is empty or unrecognized and no fallback_scrape_protocol is configured, the whole scrape fails.
  5. Parse + metric relabel + limits: run every sample through metric_relabel_configs, check label_limit,label_name_length_limit,label_value_length_limit; if the cumulative sample count exceeds sample_limit then the whole scrape is rolled back.
  6. 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”.
  7. Report: write synthetic series up (success 1 / failure 0),scrape_duration_seconds,scrape_samples_scraped,scrape_samples_post_metric_relabeling,scrape_series_added; enabling extra_scrape_metrics (in 3.x it is a config option; the old --enable-feature=extra-scrape-metrics is being phased out) also gives you scrape_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)StageRoot causeFix direction
Get "http://10.244.0.37:8081/metrics": dial tcp 10.244.0.37:8081: connect: connection refusedL4No process listening on the port: wrong targetPort, container not listening, only listening on 127.0.0.1Check Service targetPort and container ports; ss -lntp
… dial tcp: lookup x on 10.96.0.10:53: no such hostL4Static target / DNS SD has a wrong hostnamecorrect the address, or switch to Kubernetes SD
… context deadline exceededL4Response time > scrape_timeout: exporter is slow (queries the backend live on every scrape), too many metrics, network packet loss, NetworkPolicy silently dropping packetsLook at scrape_duration_seconds trend; optimize the exporter (caching); raise the timeout if necessary (≤ interval)
server returned HTTP status 401 Unauthorized / 403 ForbiddenL4Authentication required (kubelet, protected endpoints) or insufficient RBACConfigure in the ServiceMonitor authorization/bearerTokenSecret/TLS; check RBAC
server returned HTTP status 404 Not FoundL1/L4path Wrong (/metrics vs /actuator/prometheus)Correct path
body size limit exceededL4Response 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 targetL5The 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 targetL5Response has no Content-Type headerSame as above
sample limit exceededL5Samples per scrape > sample_limitModule 3
label_limit exceeded (metric: …, number of labels: 23, limit: 20)L5A series exceeds the label count limitModule 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:

  1. The Prometheus CR's serviceMonitorSelector (kps default serviceMonitorSelectorNilUsesHelmValues: true → selects only release: kps) and serviceMonitorNamespaceSelector (kps default {} = all namespaces).
  2. ServiceMonitor spec.selector must match Service labels (not the Pod's labels), and namespaceSelector by default looks only at the ServiceMonitor's own namespace.
  3. The endpoint's port is 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 use targetPort (not officially recommended).
  4. The Service must have ready Endpoints (if a Pod's readiness probe fails, it is not in Endpoints and is not a target).
  5. 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 downTarget does not exist
up0No series
/targetsRed, has lastErrorDoes not appear (may be in dropped)
Usable alert:up == 0, kps' TargetDownabsent(up{job="x"}), drop in target count
Common stagesL4, L5L2, L3
Common misconceptions① “The ServiceMonitor's 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

SDendpoints relabelkeep/drop GETtimeout Status / size200 · body Content-TypeChoose parser Parse + limitsmetric_relabel Appendhead/WAL Reportup · scrape_* No targetdroppedrefuseddeadlineHTTP 4xx/5xxbody sizeunsupportedblank CTsample limitlabel_limitout of orderduplicate up series does not exist Whole scrape fails: up = 0 + lastErrorExisting series get stale markers; the curve breaks immediately Some samples dropped, up still 1Only logged + counter Note: out-of-order / duplicate timestamps only drop the individual sample and are counted in prometheus_target_scrapes_sample_*_total; they do not make up go to 0
Figure 2-1 The up state at each failure point: left = missing, middle = 0, right = 1 but with drops

kps ServiceMonitor selection chain

Prometheus CRserviceMonitorSelectorrelease: kps ServiceMonitorselector: app=faultexpport: http Servicelabels: app=faultexpports[].name: http EndpointsReady Pods onlytargetPort TargetserviceMonitor/faultlab/faultexp/0 ✗ Labels do not match → no✗ Port name mismatch → SD yields no targets✗ Service labels do not match✗ Not ready / wrong targetPort✗ Network / authentication → down The first four stages are all “silent failures”: no error, only missing targets — use an absent() alert as a backstop, and confirm stage by stage with the config Secret and /service-discovery
Figure 2-2 Only the last stage failing produces a lastError

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.

After selecting a fault, click “Play” or “Next step”.
$ # Prometheus behavior and logs will appear here

Core commands

CommandStageDescription
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0"L4–L5Filter by scrape pool; the kps pool name is serviceMonitor/<ns>/<name>/<endpoint index>
curl -s "$P/api/v1/targets?state=dropped"L3Dropped 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='{…}'L3Runs 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 | gunzipL2the full config generated by the Operator (the method in the official troubleshooting docs)
kubectl get events -A --field-selector involvedObject.kind=ServiceMonitorL2Events emitted when the Operator rejects an illegal resource
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | tailL2Operator reconciliation log
kubectl -n faultlab get endpointslices -l kubernetes.io/service-name=faultexpL2Whether 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)

connection refused (L4): change the Service's targetPort to 8081.
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.

Content-Type (L5, specific to Prometheus 3):
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"}]'.

ServiceMonitor not selected (L2): remove the 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.

relabel dropped the target (L3): add a keep rule with a wrong regex.
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.

Command-line exercise
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'
Scenario analysis
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

▶
Relabeling in Prometheus | Relabeling Architecture and Flow, Configuration, Examples, Debugging — Prometheus Monitoring with Julius | PromLabs
English · Relabeling flow, configuration and debugging, corresponds to L3
▶
Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step — Anton Putra
English · ServiceMonitor / PodMonitor selection mechanism, corresponds to the kps selection chain
▶
Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1 — TechWorld with Nana
English · kube-prometheus-stack component review (recorded earlier; for version details, follow this lesson)

Official docs

Video storyboard (about 100 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–55s
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.
Shot 3 · 55–85s
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.
Shot 4 · 85–100s
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.
or score ≥ 70% on the quiz

Module 3 · Cardinality explosion: label design and limits

13:00 – 21:00 · A single user_id label can make Prometheus's memory grow tenfold. Learn to find “who is creating series”, and use limits to keep it out before it overwhelms the system
8 minutesTSDB Status · sample_limitKey animation★★★★★
Learning objectives
  • 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's enforcedSampleLimit other global limits.
  • Stop the bleeding and fix the root cause: metric_relabel_configs Drop metrics or labels (watch out for the trap of dropping a distinguishing label), and fix the instrumentation.
Prerequisites: Lesson 1, data model. Importance:★★★★★

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.

ConceptMeaningMain impact
Active series (head series)Number of series currently in the head block prometheus_tsdb_head_seriesMemory (each series in the head has a memSeries struct, label strings, inverted-index entries and the current chunk)
Samples per scrapescrape_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 cardinalityNumber of series selected by one queryQuery 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

MethodWhat to look atAdvantagesCaveats
TSDB Status page (/tsdb-status) or /api/v1/status/tsdb?limit=NheadStats (numSeries, chunkCount, minTime/maxTime),seriesCountByMetricName,labelValueCountByLabelName,memoryInBytesByLabelName,seriesCountByLabelValuePairreads the head's inverted-index statistics directly, very cheaponly reflects the head (roughly the last 2–3 hours); limit default 10, max 10000
PromQLtopk(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 trendThe first one selects all series, which is itself a heavy query; be careful on large instances (it may trigger max-samples)
promtool tsdb analyzechurn labels, the most common label pairs, and the highest-cardinality labels and metrics in persisted blockscan show the labels with the worst churnanalyzes 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 exceededlastError
sample_limit / sampleLimitthe whole scrape is rolled back, up = 0, and existing series get stale markers writtensample limit exceeded
label_limit / labelLimitthe whole scrape failslabel_limit exceeded (metric: …, number of labels: N, limit: M)
label_name_length_limitthe whole scrape failslabel_name_length_limit exceeded (metric: …, label name: …, length: N, limit: M)
label_value_length_limitthe whole scrape failslabel_value_length_limit exceeded (metric: …, label name: …, value: "…", length: N, limit: M)
target_limit / targetLimitall targets in that scrape pool are not scrapedtarget_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: le 12 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.
Common misconceptions① “Raising 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

method × 4GET POST PUT DELETE route × 30route template status × 6200 201 400 404 500 503 pod × 10target label = 7 200 seriesHealthy + user_id × 100 000a code change made for “easier debugging” = upper bound of 720 million seriesActual = number of combinations that occur (can still be millions) Actual series = combinations that really occur (not the full product), but as long as one label is unbounded, growth has no limit
Figure 3-1 Cardinality is multiplicative: control the number of values each label can take

What one series occupies in the head

Inverted index (postings) __name__="faultexp_user_requests_total"→ [ref 1, 2, 3, … 8000] user_id="u0" → [1]user_id="u1" → [2]… (one postings list per value) session="s0" → [1] … memoryInBytesByLabelName countsthe memory used by these label-value strings memSeries (one per series) ref, full label sethead chunk (being written, in memory)Full chunk → m-mapped to chunks_head/last sample time, staleness stateone chunk targets 120 samples(--storage.tsdb.samples-per-chunk)Still retained after the series stops appearing, untilGC after head truncation WAL (disk) Series records: written on first appearancefull label setSamples records: every scrapechurn → many Series records→ WAL grows, replay slowseverything is replayed into memory on restart
Figure 3-2 Each new series consumes index memory, memSeries memory and WAL space at the same time

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.


Samples per target per scrape
head series (accumulated over about 3 hours)
head memory estimate (at 4 KiB/series)
Panel query sum(rate(x[5m])), 6h range, step 30s — samples loaded
Target status
Memory bar: full scale = the 8 GiB Prometheus Pod limit
Drag the slider, or play the incident timeline.
$ # Matching real metrics, errors and commands

Key commands and queries

Command / queryPurpose
curl -s "$P/api/v1/status/tsdb?limit=5" | jq .datahead 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=10analyzes 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)

Record the baseline:
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"]
Inject: a release “for easier debugging” gives every user a series (8 000 users > sampleLimit 5000).
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.

Observe “without the guardrail”: temporarily raise sampleLimit to 20000 (lab only).
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"]
Now add churn: session IDs are replaced every 30 seconds (about 2 000 new series per minute; 3 minutes is enough).
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.

Stop the bleeding and fix the root cause: first drop the metric on the ServiceMonitor, then “fix the code” (turn off SERIES/CHURN), and finally restore the sampleLimit.
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.

Command-line exercises
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)
Scenario analysis question
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

▶
PromCon 2018: Bomb Squad: Containing the Cardinality Explosion — Prometheus Monitoring
English · Practices for detecting and limiting cardinality at scale
▶
Tracking Cardinality Explosions In Flight - Roman Khavronenko & Langson Zhang — CNCF [Cloud Native Computing Foundation]
English · Tracking a cardinality explosion in a running system
▶
Prometheus TSDB Churn: Diagnosing High Cardinality Metrics — Cloud Explainers
English · Churn and high-cardinality diagnosis

Official docs

Video storyboard (about 100 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–80s
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.
Shot 4 · 80–100s
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.
or score ≥ 70% on the quiz

Module 4 · Query performance: slow PromQL and dashboard optimization

21:00 – 28:00 · Query cost can be calculated: number of series selected × samples read per series × number of steps. Shrink this product and the query gets faster
7 minutesstats=all · recording rules★★★★☆
Learning objectives
  • 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=all the returned seriesTouched,totalQueryableSamples,peakSamples and 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.
Prerequisites: Lesson 1 PromQL, Lesson 2 recording rules. Importance:★★★★☆

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

  1. 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.
  2. 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 (totalQueryableSamples order of magnitude).
  3. 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.
  4. 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)MeaningWhen exceededWhere to set in kps
--query.max-samples=50000000Maximum samples a single query can load into memory at oncequery processing would load too many samples into memory in query executionprometheusSpec.query.maxSamples
--query.timeout=2mMaximum execution time for a single queryquery timed out in expression evaluation (the stage after “in” is where the error occurs)prometheusSpec.query.timeout
--query.max-concurrency=20Number 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 queuedprometheusSpec.query.maxConcurrency
--query.lookback-delta=5mMaximum 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 / stepexceeded maximum resolution of 11,000 points per timeseries…Not configurable; increase the step

Why: which patterns are slow

Anti-patternWhy it's slowRewrite
{__name__=~".+"}, selectors without a metric nameselect all seriesAlways 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 labelUse an equality or anchored prefix regex; fix the label design
histogram_quantile(0.99, rate(x_bucket[5m]))computing separately for each Pod × route × buckethistogram_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 rangea recording rule precomputes the inner expression
Dashboard with 30 panels × auto-refresh every 5s × 10 people3 600 queries per minuteRefresh ≥ 30s–1m, collapsed rows (no queries until expanded), shared queries (Dashboard data source)
Panel range 30d, Max data points very largemany steps, many pointsLet 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.

Common misconceptions① “Just raise max-samples / timeout” — these are fuses that protect Prometheus from being dragged down by a single query. ② “A smaller step is more precise” — precision finer than the scrape interval is meaningless, while cost rises linearly. ③ “Recording rules make data late” — the delay is at most one evaluation interval, in exchange for stable panels. ④ “topk reduces computation” —topk it still computes all the series first.

Query cost = series × samples per step × steps

① Select seriespostings intersectionseriesTouched = N ② Read the window per step[5m] / 15s ≈ 20 samples× 721 steps ③ Peak memorypeakSamples≤ query.max-samples ④ Aggregate and returnpoints = 721≤ 11 000 Optimization levers① Narrow selectors / fix cardinality ② recording rules turn N into a few series and 20 samples into 1 ③ reduce the range / increase the step④ sum by (le) before histogram_quantile ⑤ dashboard refresh interval and number of panels
Figure 4-1 Each stage maps to one tunable knob

How one dashboard amplifies query load

10 browsersrefresh 5s 30 panels × 2 queries+ variable “All” expansion Grafana backenddata source proxy Prometheus7 200 queries/minmax-concurrency 20 → queueingcompetes for CPU with rule evaluation 10 × (60s / 5s) × 60 = 7 200 queries/min; change the refresh to 1m and collapse rarely used rows → about 300 queries/min
Figure 4-2 It's often not one slow query that hurts, but the number of queries

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 .

$ # Corresponding API calls and possible errors

Core commands

Command / queryPurpose
curl -s "$P/api/v1/query_range" --data-urlencode query=… -d start=… -d end=… -d step=30 -d stats=allReturns 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_maxnumber of queries currently executing / queued and the concurrency limit
prometheus_rule_group_last_duration_secondswhether the rule group itself is too slow
kps: prometheus.prometheusSpec.queryLogFile: /dev/stdoutEnable 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)

Create a “heavy” metric: have faultexp output 4 000 stable user_id series (below sampleLimit), and wait 5 minutes to accumulate data.
kubectl -n faultlab set env deploy/faultexp SERIES=4000 && kubectl -n faultlab rollout status deploy/faultexp
sleep 300
Measure the “raw panel query” (first, in the same terminal, run the code that defines the 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.

Add a recording rule and compare:
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.

Trigger max-samples (optional, lab environment only): temporarily raise maxSamples to 100 000 to see the error.
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.

Reset:
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”.

Command-line exercises
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}'
Scenario analysis question
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

▶
PromCon 2024 - Inside a PromQL Query: Understanding the Mechanics — Prometheus Monitoring
English · How PromQL queries execute internally
▶
PromCon EU 2022: Anatomy of a Slow Query, and Lessons Learned Building Query Acceleration Techniques — Prometheus Monitoring
English · Slow query analysis and speed-up tips
▶
Optimizing PromQL Queries - Aliaksandr Valialkin - PromCon 2024 Lightning Talk — Prometheus Monitoring
English · Lightning talk on key PromQL optimization points

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–60s
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.
Shot 3 · 60–90s
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.
or score ≥ 70% on the quiz

Module 5 · TSDB internals: head block, WAL, compaction and disk

28:00 – 35:00 · Understanding a sample's journey from memory to disk explains “why a restart takes ten minutes”, “why memory only drops after three hours”, and “why the disk exceeds the retention period”
7 minutesv3.16.0 tsdb/Key animation★★★★☆
Learning objectives
  • 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.
Prerequisites: Module 3. Importance:★★★★☆

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)

  1. 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-compression default true, algorithm snappy, zstd optional).
  2. m-map: once a head chunk is full (target --storage.tsdb.samples-per-chunk=120 samples, about 30 minutes at a 15s interval), it is written to chunks_head/ and m-mapped; only the chunk being written stays in memory.
  3. 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 (log write block started,Head portion block created).
  4. 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.
  5. WAL checkpoint: the first 2/3 of the WAL segments (last = first + (last-first)*2/3) that are still needed are written into checkpoint.N, and the old segments are deleted (log WAL checkpoint complete).
  6. 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.
  7. Retention: by time (kps default retention: 10d; Prometheus itself defaults to 15d), by size (retentionSize), or by disk percentage (new in 3.x retention.percentage), deletes entire oldest blocks. Size retention counts “WAL + head chunks + all blocks”.
  8. 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 /-/ready returns not-ready,/api/v1/status/walreplay shows progress.

Why: which phenomena these mechanisms explain

PhenomenonMechanism
Memory doesn't drop after churn stops, then drops suddenly after about 1–3 hoursInactive series are only freed by GC after the next head compaction
No data for 10 minutes after restartWAL 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 queriedBlocks are deleted whole: a block is removed only when its maxTime is older than the retention boundary
Disk usage = blocks + about 3 hours of WALThe WAL covers the part of the head not yet persisted, and has checkpoints
“out of bounds” samples are droppedWithout 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/size command-line flag is marked DEPRECATED; prefer putting it in the config file storage.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: retentionSize Set it to about 80% of PV capacity as a “fuse”, and alert on predict_linear(kubelet_volume_stats_available_bytes[6h], 24*3600) < 0 (kps ships with a similar KubePersistentVolumeFillingUp).
  • Memory snapshots: enable --enable-feature=memory-snapshot-on-shutdown to write a snapshot on normal shutdown, so the next startup skips most WAL replay (no effect on abnormal exits such as OOM).
Common misconceptions① “The bigger the WAL, the safer, so retention can be raised” — the WAL only covers the head and does not affect retention. ② “Deleting the WAL only loses the last few minutes” — it loses all unpersisted data in the head (up to about 3 hours). ③ “Retention is exact” — deletion happens per block, so it can be off by up to one block range. ④ “Prometheus supports multiple instances sharing one data directory” — it doesn't, and the 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

Scrape / rulesAppender.Commit WAL (disk, sequential writes)Series / Samples records128 MiB segments + checkpoint Head (memory)memSeries + inverted indexone active chunk per seriesspan ≤ ~3h chunks_head/Full chunksm-map (120 samples) Persisted block 2hindex + chunks + meta.jsonimmutable Merged blocks 6h / 18h …≤ min(retention × 10%, 31d) head span > 3h → oldest 2h written as a block Restart replay: chunks_head (m-map) → WAL checkpoint → remaining WAL segments → readyReplay time ∝ number of series and samples in the WAL — cardinality explosion makes restarts slower
Figure 5-1 The WAL guarantees no data loss on crash, the head serves writes and recent-data queries, and blocks provide long-term storage

Timeline: one head compaction

00:0002:0004:0006:0008:00 Block 00–02 Block 02–04 head 04:00–07:05 (span 3h05m > 3h) New block 04–06 head 06–07:05 Afterwards: head truncation → GC frees inactive series → WAL checkpoint; three adjacent 2h blocks are later merged into one 6h block
Figure 5-2 The head always keeps the most recent 1–3 hours; compaction happens roughly every 2 hours

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.

Head (memory)
head series count
current head chunk samples (target 120)
chunks_head/ (m-map)
wal/
Persisted blocks
Click “Next step” to start.
$ # Prometheus logs (slog format, excerpt)

Key commands and metrics

Command / metricDescription
curl -s $P/api/v1/status/tsdb/blocks | jqulid, minTime, maxTime, stats, compaction.level for all blocks
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheusBlock list (human-readable sizes); available in distroless images
curl -s $P/api/v1/status/walreplayReplay progress {min, max, current} (segment number)
prometheus_tsdb_head_series,prometheus_tsdb_head_chunks,prometheus_tsdb_head_chunks_storage_size_byteshead size and chunks_head disk usage
prometheus_tsdb_wal_storage_size_bytes,prometheus_tsdb_wal_segment_current,prometheus_tsdb_wal_fsync_duration_secondsWAL 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_timestampblock occupancy, size retention limit, earliest data time
prometheus_tsdb_compactions_total,prometheus_tsdb_compactions_failed_total,prometheus_tsdb_compaction_duration_secondscompaction count, failures, duration
prometheus_tsdb_head_truncations_failed_total,prometheus_tsdb_checkpoint_creations_failed_total,prometheus_tsdb_wal_corruptions_totaltruncation, checkpoint failures and WAL corruption
prometheus_tsdb_time_retentions_total,prometheus_tsdb_size_retentions_totalnumber 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)

Blocks and head: run the block list and headStats commands from the “Commands” tab and answer: are the last block's maxTime and the head's minTime equal? What is the highest compaction level? (kps defaults to 10d retention → max block 1d → the highest is an 18h block, i.e. level 3).
Create some churn to make the replay more visible (optional):
kubectl -n faultlab set env deploy/faultexp SERIES=1000 CHURN=1
sleep 240
pq 'prometheus_tsdb_head_series'
Force-kill Prometheus (simulating OOM) and observe the replay:
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.

Count the gaps: in the Prometheus UI, graph 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.
Reset: 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.

Command-line exercises
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
Scenario analysis question
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

▶
SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB — USENIX
English · A TSDB maintainer explains the full lifecycle of a sample, from head and WAL to blocks; matches this module's animation
▶
Lifecycle of a Sample in the Prometheus TSDB - Ganesh Vernekar — FOSSASIA
English · Another talk on the same topic
▶
PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable — Prometheus Monitoring
English · Odd TSDB behaviors seen in production, and their explanations
▶
PromCon 2016: The Prometheus Time Series Database - Björn Rabenstein — Prometheus Monitoring
English · Historical background (Prometheus 1.x storage, since replaced by the 2.x/3.x TSDB; for comparison only)

Official docs

Video storyboard (about 100 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
Shot 4 · 80–100s
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.
or score ≥ 70% on the quiz

Module 6 · Alerts not firing or alert storms

35:00 – 42:00 · The alert pipeline has seven checkpoints: rule loading, evaluation, expression result, for, sending, Alertmanager processing, and receivers. When alerts don't fire, check each checkpoint in turn; when there are too many, tackle it at three points: grouping, inhibition and thresholds
7 minutesAlertmanager v0.35.0 · amtool★★★★★
Learning objectives
  • Diagnose “no alert notifications” through the seven checkpoints: is the rule loaded (/rules) → health and lastError → does the expression return series → for is the for duration met (pending) → did Prometheus send to Alertmanager → is it silenced / inhibited / routed to null → did the receiver deliver successfully.
  • Know the default kps Alertmanager configuration: group_by: ['namespace'],group_wait 30s,group_interval 5m,repeat_interval 12h,default receiver null (sends no notifications); Watchdog is routed to null, plus severity-based inhibition rules.
  • Handling alert storms: sensible group_by, inhibition rules (a common cause inhibits its symptoms),for and keep_firing_for debouncing; symptom alerts take precedence over cause alerts.
Prerequisites: Lesson 2: alert lifecycle and Alertmanager routing. Importance:★★★★★

What: the seven checkpoints of the alert pipeline

#CheckpointFailure symptomObservation window
1Rule 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
2Evaluation (every evaluation_interval, kps default 30s)health = err, lastError has contentprometheus_rule_evaluation_failures_total
3Expression resulthealth = ok, but always inactive: the expression returns emptyPaste the expr into the UI and run it
4for DurationRepeatedly pending → inactive (flapping), never firingALERTS{alertstate="pending"} history of
5Sent to Alertmanager (every --rules.alert.resend-delay=1m resend, queue --alertmanager.notification-queue-capacity=10000)Firing in Prometheus, but not in Alertmanagerprometheus_notifications_alertmanagers_discovered,_errors_total,_dropped_total,_queue_length
6Alertmanager: dedup → silence → inhibition → routing → group waitvisible in Alertmanager but suppressed, or routed to nullamtool alert query -s -i,amtool config routes test, AM UI
7receiver (webhook, email, Teams, PagerDuty…)AM thinks it was sent, but the recipient never got italertmanager_notifications_failed_total{integration}, AM logs

Why: the four most common reasons an alert never notifies

  1. the expression returns empty during a fault: up == 0 it 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 crashes errors_total).
  2. The rule is not loaded: kps by default ruleSelectorNilUsesHelmValues: true → only loads release: kps PrometheusRule objects carrying the label; a PromQL syntax error makes the Operator reject the whole resource.
  3. 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.
  4. Alertmanager swallowed it: the default kps route's receiver is null; an overly broad silence (namespace=~".+"); an inhibition rule equal with incomplete labels causes false suppression.

How: three ways to govern an alert storm

TechniqueEffectExample
Grouping group_byalerts in the same group are merged into one notification; new alerts joining the group wait group_interval before being sentGroup by ['namespace','alertname'] rather than ['...'] (each alert in its own group), or instance
inhibition inhibit_rulessuppress “symptom” alerts while a “cause” alert is firingNodeDown inhibits all Pod alerts on the same node (equal: [node]); kps by default, critical inhibits warning/info with the same namespace and alertname
Debounceavoid repeated firing and resolving around the thresholdfor: 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 / firingactive / suppressed (silenced or inhibited) / unprocessed
a firing alert is resent every resend-delay, with endsAtnot 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
Common misconceptions① “Once kps is installed, it sends notifications”—the default receiver is 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

① LoadruleSelector ② Evaluatehealth ③ Resultnon-empty? ④ forpending ⑤ Sendnotifier ⑥ AM processingsilence · inhibition · routing ⑦ Receiverwebhook… /rules: nolastErrorUI expr emptyjitter resetsdropped/errorssuppressed / nullfailed_total Inside Prometheus (/rules, ALERTS)The first four checkpoints do not involve Alertmanager Alertmanager (amtool, AM UI)kps default receiver = null
Figure 6-1: check the checkpoints from left to right; the first anomaly is the answer

Storm control: grouping and inhibition

NodeNotReady node=w1 PodNotReady × 25 (on w1) TargetDown × 18 (on w1) HighLatency × 6 (symptom) inhibit_rulessource: alertname=NodeNotReadytarget: severity=~warning|infoequal: [node] Notification 1: NodeNotReady w1 (critical) Notification 2: HighLatency (grouped by namespace) 50 alerts → 2 notifications; the 43 suppressed alerts remain visible in AM (state=suppressed) and are released automatically after recovery
Figure 6-2: an inhibition rule requires the cause and symptom alerts to share the labels listed in equal (for example node)

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.

Select a fault, then click “Check step by step”.
$ # diagnostic commands and output

$ # notification count estimate

Core commands

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

Deploy a webhook receiver and route the faultlab alerts:
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.

Inject: turn on error traffic, then wait for the alert:
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']
“Never fires”: window too small— change the expression window to [10s] (scrape interval 15s).
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).

An overly broad silence:
$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).

Reset:
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.

Command-line tasks
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'
Scenario analysis
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

▶
PromCon EU 2019: Improved Alerting with Prometheus and Alertmanager — Prometheus Monitoring
English · Improving alert design and Alertmanager usage in practice
▶
Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences on Alertmanager — Tech with Lian
English · Hands-on demo of grouping, inhibition and silences
▶
Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output) — DevOps Simplified
English · pending/firing and promtool rule testing

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or score ≥ 70% on the quiz

Module 7 · Grafana troubleshooting: data sources, panels and permissions

42:00 – 50:00 · Prometheus has data but the panel shows No data: the problem must be at one hop on the path “browser → Grafana backend → data source → Prometheus → response → transformations → rendering”
8 minutesGrafana 13.3.1 (kps sub-chart 14.4.1)★★★★☆
Learning objectives
  • 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 found and permission issues.
Prerequisites: Lesson 1 (Grafana architecture), lesson 5 (Grafana in kps). Importance:★★★★☆

What: the path of one panel query

  1. 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.
  2. Grafana backend: the browser calls POST /api/ds/query, and the backend checks the user's permissions on the dashboard / data source.
  3. 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 default http://kps-kube-prometheus-stack-prometheus.monitoring:9090/, uid prometheus), regardless of whether your browser can reach it.
  4. Return and transform: the results become data frames and pass through transformations (filter, merge, rename).
  5. Rendering: visualization options (units, thresholds, Overrides, hiding series, Y-axis range).

Step and rate window

Variable / settingMeaningTroubleshooting notes
$__interval≈ time range / Max data points, not less than Min interval or the data source Scrape intervalstep too small → too many points (11 000 limit); too large → spikes get smoothed away
$__rate_intervalmax($__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 assumeskps 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 stepA hard-coded, very small Min interval pushes long-range queries over the limit

Why: classifying common Grafana faults

CategoryTypical symptomFirst place to look
ConnectivityRed triangle on the panel: Post "http://…:9090/api/v1/query_range": dial tcp: lookup … no such host / connect: connection refuseddata source “Save & test”,/api/datasources/uid/<uid>/health
data source referenceDatasource ${DS_PROMETHEUS} was not found,Datasource xyz was not foundin the panel JSON datasource.uid
Query semanticsNo data; the Prometheus UI is empty tooQuery inspector → Query tab, check the actual expr and step
VariablesNo data after selecting All; variable dropdown is emptythe expr after substitution in the Inspector (= vs =~, All value)
Transformations / renderingInspector Data tab has data, but the graph shows noneTransformations, Overrides, units and thresholds
ProvisioningA dashboard / data source in a ConfigMap does not appearsidecar container logs (grafana-sc-dashboard,grafana-sc-datasources), labels
PermissionsCannot 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).

Common misconceptions① “If the browser can open Prometheus, Grafana can connect too”—the Grafana backend connects from the Pod network using in-cluster DNS. ② “Hard-coding rate [1m] is the simplest choice”—when the time range or the scrape interval changes, it comes and goes; use $__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

Browservariables · $__interval Grafana backend/api/ds/query · permissions Data source pluginuid=prometheus Prometheusquery_range Transformationsframes Renderingoverrides variable empty / All403 · no permissionwas not foundno such hostbad_data · timeoutfiltered outhidden / units Query inspector: Query tab = the request actually sent (expr, step); Data tab = returned frames; Stats = timing and point countsBisection: run the expr in the Prometheus UI to tell whether the problem is before or after Prometheus
Figure 7-1: requests from Grafana to Prometheus are sent from the Grafana Pod

Sidecar provisioning in kps

ConfigMap (any namespace)label grafana_dashboard: "1" ConfigMap / Secretlabel grafana_datasource: "1" grafana-sc-dashboardwatch → write file → call reload API grafana-sc-datasourceswrite provisioning/datasources grafana containerprovisioning loadlogs: provisioning errors kps 93.3.0: dashboards sidecar searchNamespace = ALL; the datasources sidecar only looks at the Grafana namespace by default (check the values)
Figure 7-2: provisioned dashboard does not appear: label → sidecar logs → grafana logs

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.

Select an anomaly, then click “Trace”.
$ # request and response at each hop

Core commands (Grafana HTTP API, using the admin account)

CommandPurpose
curl -s -u admin:$GPW $G/api/healthGrafana 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/healthbackend 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=20whether 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)

Provision a dashboard (faultlab namespace, sidecar searchNamespace = ALL):
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).

Bad reference: change the panel data source uid to a non-existent value, 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.

Bad variable: in the UI, edit the panel and change 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).

Bad data source (connectivity): add a provisioned data source pointing to the wrong host (the datasource sidecar only looks at the Grafana namespace by default, so put it in monitoring and delete it after the lab).
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).

Command-line tasks
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'
Scenario analysis
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

▶
GrafanaCONline: Prometheus rate queries in Grafana — Grafana
English · how rate queries, $__interval and $__rate_interval work
▶
How to build a Prometheus query in Grafana — Grafana
English · building Prometheus queries in Grafana (Query builder and Code mode)
▶
Understanding Dashboards in Grafana | Panels, Visualizations, Queries, and Transformations — Grafana
English · how panels, queries and transformations relate (debugging “data present but not shown”)

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–60s
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.
Shot 3 · 60–90s
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.
or score ≥ 70% on the quiz

Module 8 · Mixed fault blind box

50:00 – 60:00 · 8 real faults injected at random: you only get the symptoms you would see on call; use the eight-stage chain and this lesson's tools to locate, fix and write a guardrail
10 minutesfault-box.shInteractive troubleshooting tree★★★★★
Learning objectives
  • 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).
Prerequisites: Modules 1–7. Importance:★★★★★

What: overview of the 8 faults (answer table, do not look before the drill)

#Injection methodSymptom seen on callSegmentDecisive evidenceFixGuardrail
1Service targetPort → 8081FaultexpDown firingL4lastError connect: connection refusedtargetPort changed back to httpuse a named port; check up after deployment
2ServiceMonitor drops release: kpsfaultexp panels are all empty, FaultexpDown does not fireL2absent(up{job="faultexp"}) = 1; no such job in the config SecretAdd the labelabsent alert; CI checks SM labels
3DELAY=12FaultexpDown firing, sometimes never recoversL4lastError context deadline exceeded; scrape_duration ≈ 10sFix the exporter (remove the delay)scrape duration / timeout ratio alert
4CT=application/octet-streamexporter is down after an “upgrade”L5received unsupported Content-Type …Fix the exporter or fallbackScrapeProtocolscrape with 3.x in staging before upgrading
5SERIES=8000FaultexpDown firing, the exporter itself is healthyL5sample limit exceeded; scrape_samples_scraped ≈ 8003Fix the instrumentation / metricRelabelings dropsampleLimit + enforcedSampleLimit
6SERIES=1000 + CHURN=1Prometheus memory keeps climbing, all targets upL6rate(prometheus_tsdb_head_series_created_total[5m]) high; scrape_series_added stays non-zeroRemove the session labelseries creation rate alert
7Rule window [10s] + ERRORS=15xx clearly increases, FaultexpHighErrorRate does not fireL7rule health ok, state inactive; the expression is empty when run in the UIChange the window to [2m]promtool test rules; window ≥ 4 × scrape interval
8dashboard data source uid → prom-oldFaultlab dashboard red triangleL8Datasource prom-old was not foundchange the uid back prometheusdashboards use a data source variable; CI validates the uid

How: the pace of each diagnosis round (≤ 3 minutes)

  1. Read the symptom and ask: does up exist? What is its value? (half of locating the segment)
  2. Run the “standard diagnostic bundle” (step 2 on the lab page).
  3. Dig into the segment: lastError / config Secret / TSDB Status / rules and ALERTS / Grafana API.
  4. Fix and verify: up = 1, the alert recovers, the panel shows data.
  5. Write one guardrail sentence.
Common misconceptions① “Fault 2 is the same as fault 1, the target is down”—one has no up at all, the other has up = 0; their alert behaviour is completely different. ② “For fault 5, just raise sampleLimit”—that leads to the memory problem of fault 6. ③ “Fault 7 is an Alertmanager problem”—there is no pending state in Prometheus at all.

Where the 8 faults sit in the eight-stage chain

L1 Exposure L2 Discovery L3 relabel L4 Scrape L5 Limits L6 Storage L7 Rules L8 Presentation (source of #3, #4, #5, #6)#2 not selected#1 refused#3 timeout#4 Content-Type#5 sample limit#6 churn#7 window too small#8 uid does not exist up missing: #2 | up = 0: #1 #3 #4 #5 | up = 1: #6 #7 #8Answer “does up exist, and what is its value?” first, and the 8-way choice becomes a 3-way choice
Figure 8-1: fault distribution and up state

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.

$ # click the button above to start

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)

Draw:
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”.
Standard diagnostic bundle (run this set first in every round):
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.*"}'
Dig into the segment:
# 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]'
Verify, fix, reset: write down your judgement, then run ./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.
Record table:
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.

Command-line tasks
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
Scenario analysis
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

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
English · Review: common mistakes checklist
▶
PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable — Prometheus Monitoring
English · TSDB fault stories from real production, suitable for a post-blind-box review

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–15s
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.
Shot 2 · 15–60s
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.
Shot 3 · 60–90s
Visual: after the fix, up becomes 1, and a guardrail is written in the record table.
Narration: every fix leaves behind one guardrail.
or score ≥ 70% on the quiz

Command cheat sheet

Common commands, queries and raw error messages for deep troubleshooting (Prometheus v3.16.0 · Alertmanager v0.35.0 · Grafana 13.3.1 · kps 93.3.0)
Trust and locating the segment
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])
Scrape and discovery (L2–L5)
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=ServiceMonitor
Cardinality (L5–L6)
curl -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])
Query performance (L7)
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}
TSDB (L6)
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])
Alerting (L7–L8)
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
Grafana (L8)
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
Guardrail snippets
# 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: 40GiB

Quick reference for error messages

Error (original text)SegmentSee
… connect: connection refusedL4Module 2
… context deadline exceededL4Module 2
server returned HTTP status 403 ForbiddenL4Module 2
body size limit exceededL4Module 2
received unsupported Content-Type "…" and no fallback_scrape_protocol specified for targetL5Module 2
non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for targetL5Module 2
sample limit exceededL5Module 3
label_limit exceeded (metric: …, number of labels: N, limit: M)L5Module 3
target_limit exceeded (number of targets: N, limit: M)L2Module 3
scrape timeout greater than scrape interval for scrape config with job name "…"ConfigModule 2
query processing would load too many samples into memory in query executionL7Module 4
query timed out in …L7Module 4
exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)L7Module 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)L7Module 4
vector contains metrics with the same labelset after applying alert labelsL7Module 6
Replaying WAL, this may take a while (stays for a long time)L6Module 5
Encountered WAL read error, attempting repairL6Module 5
Datasource … was not foundL8Module 7

Comprehensive lab + final quiz

Inject the 8 faults one by one on kind + kps, complete the diagnosis records, and produce a “self-monitoring and guardrails” checklist for the team
About 60–90 minutesLocal kind · no cost
Scenario

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.

Preparation: complete module 0; save the module 7 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
Faults 1–2 (target down and target missing):
./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
Faults 3–5 (L4/L5):
./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 6 (L6):
./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])))'
Faults 7–8 (L7/L8):
./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]'
Output: self-monitoring and guardrail checklist (copy into the team document and fill in owners and dates as appropriate):
# 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
Cleanup:
./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
Acceptance checklist

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

Basis for verifying this lesson's technical facts (verification date: 2026-11-15)
TopicVerified conclusionSource (verification date)
VersionsPrometheus 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 errorssample 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 markerv3.16.0 scrape/scrape.go,scrape/target.go
Content-TypeFour kinds of … no fallback_scrape_protocol specified for target error messages; the recognised types: application/openmetrics-text,application/vnd.google.protobuf,text/plainv3.16.0 model/textparse/interface.go
Scrape configurationdefault 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 outv3.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/allv3.16.0 cmd/prometheus/main.go,promql/engine.go,web/api/v1/api.go,util/stats/query_stats.go
TSDBblocks 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 messagesv3.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_stepsv3.16.0 web/api/v1/api.go
promtooltsdb analyze (--limit default 20, --extended, --match; by default it analyses the last block) output headings; tsdb list -r; check service-discoveryv3.16.0 cmd/promtool/main.go,tsdb.go
Self-monitoring metricsprometheus_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
Rulesvector contains metrics with the same labelset after applying alert labels; --rules.alert.resend-delay=1m; notification queue 10000v3.16.0 rules/alerting.go,rules/recording.go,cmd/prometheus/main.go
OperatorServiceMonitor 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 resourceOperator v0.95.2 pkg/apis/monitoring/v1/*.go;Troubleshooting
kps defaultsselector 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 setkube-prometheus-stack 93.3.0 values.yaml,templates/grafana/configmaps-datasources.yaml
Imagedistroless image contains /bin/promtool, no shell; the Alertmanager image is based on busybox and includes amtoolv3.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.