Prometheus & Grafana Hour 1: Core Fundamentals
kubectl top, plus the chart and values material from the Helm course; this lesson does not repeat it. Note the difference: metrics-server only provides “current” CPU and memory for scheduling and HPA; it does not store history or accept queries. Prometheus is the monitoring system that stores time series and supports queries and alerting. Lessons 1–2 explain the mechanisms in depth on local Docker Compose; Lesson 5 then moves the same things into Kubernetes with kube-prometheus-stack.- Explain Prometheus's role and architecture: pull-based metric monitoring + a local time series database + PromQL + a rule engine; draw the data flow between the server, exporters, service discovery, Pushgateway, Alertmanager and Grafana, and name the key changes in Prometheus 3 compared with 2.x (new UI, UTF-8 names by default, left-open range selectors, stable Agent mode, OTLP ingestion, Remote Write 2.0).
- Understand precisely the data model: a time series = metric name + label set; a sample = (millisecond timestamp, float64 or native histogram); distinguish the meaning and use cases of counter, gauge, histogram and summary, and know that native histograms have been stable since 3.8 and need
scrape_native_histogramsbefore they are collected. - Be able to fully reproduce one scrape cycle: service discovery →
relabel_configs→ HTTP GET/metrics(Accept negotiation, timeout header) → parsing →metric_relabel_configs→ attachjob/instancethe target labels → write to the head block and WAL → generateup,scrape_duration_secondsand other synthetic metrics → series that disappear are written a staleness marker. - Use
prometheus_clientto instrument myapp (gunicorn multi-process mode), and use node_exporter and redis_exporter to collect host and Redis metrics; write correct labels, units and names. - Master PromQL basics and advanced topics: the four expression types, label matchers,
rate()/increase()/irate(),sum by/without,histogram_quantile(),on/group_leftjoins and subqueries; be able to hand-calculate onerate()(samples within the window, counter reset compensation, the 1.1× threshold for extrapolating toward the boundary, and the rule of not extrapolating below zero). - Understand Grafana architecture (backend, data source proxy, panel queries,
$__intervaland$__rate_interval, provisioning), and build your first dashboard for myapp using the RED method, with variables, managed as files. - Set up the shared lab environment
~/promlab(Lesson 2 builds on this), and identify the six most common problems: target down, scrape timeout, wrong Content-Type, missing multi-process metrics, Grafana “No data”, and rate applied to the wrong object.
One-hour time allocation
| # | Time | Module | Core content | Animation / interaction | Lab (~/promlab) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | Create ~/promlab: the seven Compose services, the instrumented myapp, Prometheus / Alertmanager / Grafana configuration and provisioning | Environment self-check checklist | docker compose up -d,promtool check config |
| 1 | 00–06 | Monitoring and observability: architecture and the pull model | Monitoring vs observability, Prometheus components, pull vs push, changes in Prometheus 3, when to use it and when not to | Pull vs push comparison simulator (who finds out first when a target goes down) | Prometheus UI,/api/v1/targets,up |
| 2 | 06–13 | Metric types and data model | Time series and samples, text exposition format, counter / gauge / histogram / summary, naming and units, native histograms | Metric type playground: events → live changes in the exposition format | Read myapp's /metrics |
| 3 | 13–21 | scrape configuration, exporters and application instrumentation | scrape_configs, target labels, the two relabel stages, synthetic metrics, protocol negotiation, node_exporter, redis_exporter, client_python multi-process | Core animation A: one complete scrape cycle (including the relabel drop and staleness marker branches) | relabel rewriting labels, hot reload,promtool |
| 4 | 21–28 | PromQL basics: selectors, rate and aggregation | four types, matchers, lookback,offset/@,rate/increase/irate, aggregation | Core animation B: rate() calculator (resets, extrapolation, missing samples) | QPS, error rate, Top-N queries |
| 5 | 28–35 | PromQL advanced: histogram_quantile, joins and subqueries | quantile interpolation,sum by (le), vector matching on/group_left,absent,predict_linear, subqueries | histogram_quantile interpolation visualization | P95 latency, joins with version information |
| 6 | 35–42 | Grafana architecture: data sources, dashboards and panels | Grafana backend and database, data source proxy, query path,$__interval/$__rate_interval, provisioning, changes in Grafana 13 | panel query path + interval calculator | API data source checks, Explore |
| 7 | 42–50 | Building your first dashboard: variables and the RED method | RED / USE, variables, units and thresholds, heatmap, dashboard JSON and file provisioning | RED dashboard fault injection simulator | Importing the myapp RED dashboard |
| 8 | 50–60 | myapp observability readiness and troubleshooting basics | Readiness checklist; for six common failures, the symptom → root cause → fix | Failure reproduction simulator + interactive troubleshooting tree | Inject faults and fix them |
| — | After class | Cheat sheet · Integrated lab | Add /slow latency observability and node and Redis panels for myapp, and write acceptance queries | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / queries | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the Prometheus architecture and the pull model | ✓ | · | ✓ | · | · | · | · | ✓ | up,/api/v1/targets | M1 targets page |
| Read the data model and metric types | · | ✓ | ✓ | ✓ | ✓ | · | · | · | curl :5000/metrics | M2 interpret the exposition format |
| Configure scraping and relabel | · | · | ✓ | · | · | · | · | ✓ | promtool check config,POST /-/reload | M3 relabel |
| Application instrumentation and exporters | · | ✓ | ✓ | · | · | · | · | ✓ | prometheus_client multi-process | Environment setup + M3 |
| PromQL: rate and aggregation | · | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | sum by (route) (rate(...[5m])) | M4 queries |
| Quantiles, joins and subqueries | · | · | · | · | ✓ | · | ✓ | · | histogram_quantile,group_left | M5 P95 |
| Grafana data sources and panel mechanics | · | · | · | · | · | ✓ | ✓ | ✓ | $__rate_interval,/api/datasources | M6 Explore |
| RED dashboard and variables | · | · | · | · | · | ✓ | ✓ | ✓ | label_values(), provisioning | M7 dashboard |
| Troubleshooting common collection and display problems | ✓ | · | ✓ | ✓ | · | ✓ | · | ✓ | up == 0,scrape_duration_seconds | M8 fault injection |
Topics not covered in this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Recording rules, alerting rules, Alertmanager routing / inhibition / silences, notification channels, Grafana Alerting | This lesson only deploys Alertmanager and connects it; alerting is a full topic in its own right | Lesson 2 |
| Storage capacity planning, retention policies, and an in-depth look at TSDB internals (head / WAL / compaction) | This lesson only introduces the concepts | Lesson 2 Module 7, Lesson 7 Module 5 |
| Azure Monitor managed Prometheus / Azure Managed Grafana, AMP / AMG | cloud-hosted services | Lessons 3 and 4 |
| Prometheus Operator on Kubernetes, ServiceMonitor, kube-prometheus-stack, Grafana as code | Requires the local mechanisms to be understood first | Lesson 5 |
| High availability, federation, remote write, Thanos / Mimir, SLOs and burn rate | Architecture topics | Lesson 6 |
| Cardinality explosion, slow query optimization, deep dives into scrape failures | This lesson only covers introductory troubleshooting | Lesson 7 |
| Logs (Loki), distributed tracing (Tempo), profiling | This course focuses on metrics; the relationship between OpenTelemetry and Prometheus is covered in Lesson 6 | Lesson 6 Module 6; Grafana official documentation |
| Docker / Compose itself, metrics-server and HPA | Prerequisites | Docker course · K8s course Lesson 6 |
How to use this courseware
Principles · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Narration · Video. We recommend reading "Principles" and "Animation" first, then doing the "Lab". Module 3 (the scrape cycle) and Module 4 (the rate calculator) are the core of the course; be sure to work through both by hand.
A quiz score of ≥ 70%, or clicking "Mark this module complete", counts toward progress. Progress is saved in this browser's localStorage (it is cleared on refresh in private mode or when storage is disabled).
The "Narration" page uses the browser's built-in Web Speech API (en-US) to read the lecture script aloud, with English terms pronounced in en-US. Without a Chinese voice pack, the script can still be read or passed to a TTS tool.
grafana/grafana (grafana/grafana-oss is no longer updated).Module 0 · Environment setup (Docker Compose: Prometheus + Grafana + myapp)
- Lab machine: Ubuntu 24.04 (a local machine, WSL2 or an Azure VM), with Docker Engine 29.x and the Compose plugin installed (from the Docker course). We recommend ≥ 2 vCPU / 4 GiB RAM / 5 GiB disk. Docker Desktop (macOS/Windows) can also run it, but node-exporter then sees the Docker VM rather than your computer (see troubleshooting).
- Tools:
curl,jq(sudo apt-get install -y curl jq).promtoolandamtooldo not need separate installation; use the ones bundled in the containers. - Connection to the previous course: reuses the myapp (Flask + gunicorn + Redis counter) from the Docker course. This lesson builds on it by adding
/healthz,/metricsand two routes that produce latency and errors/slow,/error, with the port standardized as 5000, and rebuilt asmyapp:1.0(instrumented version).myapp:1.1Reserved for later lessons to demonstrate "a new version introducing a regression." - Cost: everything runs locally at zero cost. (If you use an Azure VM, you are billed for the VM size, so remember to stop or delete the resource group after class.) Permissions: a regular user who can run docker. Security risk: all ports are bound only to
127.0.0.1. Prometheus / Alertmanager have no authentication, and Grafana uses a lab password. Do not expose these ports directly to the public internet; for a remote VM, access them through an SSH tunnel.
Common conventions (consistent across all courses in this series)
| Service (Compose name) | Image | Port | Purpose |
|---|---|---|---|
prometheus | prom/prometheus:v3.16.0 | 9090 | Scraping, storage, queries, rule evaluation |
alertmanager | prom/alertmanager:v0.35.0 | 9093 | Alert grouping, routing and notification (this lesson only connects it; configured in Lesson 2) |
grafana | grafana/grafana:13.3.1 | 3000 | Visualization; data sources and dashboards are provisioned through files |
node-exporter | prom/node-exporter:v1.12.1 | 9100 | Host CPU, memory, disk and network metrics |
myapp | myapp:1.0 (built locally) | 5000 | Sample application,/metrics exposing metrics via prometheus_client |
redis | redis:7-alpine (same as the Docker course) | 6379 (not published) | myapp's counter storage |
redis-exporter | oliver006/redis_exporter:v1.97.0 | 9121 | Converts Redis INFO into Prometheus metrics |
Unified metric names for myapp (the rules, dashboards and alerts in later lessons all reference these three names): myapp_http_requests_total{method,route,status} (counter),myapp_http_request_duration_seconds{method,route} (histogram; buckets 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5 seconds),myapp_redis_up (gauge; 1 = the last access to Redis succeeded).
Directory structure
~/promlab/ ├── compose.yaml ├── myapp/ │ ├── app.py # Flask application + prometheus_client instrumentation │ ├── gunicorn.conf.py # multi-process directory cleanup + child_exit hook │ ├── requirements.txt │ ├── Dockerfile │ └── .dockerignore ├── prometheus/ │ ├── prometheus.yml │ └── rules/ # Lesson 2 adds recording and alerting rules here (*.yml) ├── alertmanager/ │ └── alertmanager.yml # minimal config in this lesson; completed in Lesson 2 ├── grafana/ │ ├── provisioning/ │ │ ├── datasources/prometheus.yml │ │ └── dashboards/promlab.yml │ └── dashboards/ # dashboard JSON (Module 7 generates myapp-red.json) └── loadgen.sh # small script that generates traffic
mkdir -p ~/promlab/{myapp,prometheus/rules,alertmanager,grafana/provisioning/{datasources,dashboards},grafana/dashboards}
cd ~/promlab
cat > myapp/app.py <<'EOF'
import os, random, socket, time
import redis
from flask import Flask, Response, g, request
from prometheus_client import (CONTENT_TYPE_LATEST, CollectorRegistry, Counter,
Gauge, Histogram, generate_latest, multiprocess)
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379,
socket_connect_timeout=1, socket_timeout=1)
# ---- Unified metrics (names and labels are the same across all lessons in this series) ----
REQUESTS = Counter(
"myapp_http_requests_total", "HTTP requests by method, route and status code",
["method", "route", "status"])
LATENCY = Histogram(
"myapp_http_request_duration_seconds", "HTTP request latency in seconds",
["method", "route"],
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))
REDIS_UP = Gauge(
"myapp_redis_up", "1 if the last Redis call succeeded, else 0",
multiprocess_mode="livemostrecent") # multiple workers take the most recently written value
def redis_ok():
try:
r.ping()
REDIS_UP.set(1)
return True
except redis.exceptions.RedisError:
REDIS_UP.set(0)
return False
@app.before_request
def _start_timer():
g.start = time.perf_counter()
@app.after_request
def _record(resp):
if request.path == "/metrics": # do not count the scrape request itself
return resp
# Use the route template rather than the raw path as the label, to prevent cardinality explosion from paths like /user/123
route = request.url_rule.rule if request.url_rule else "unmatched"
REQUESTS.labels(request.method, route, str(resp.status_code)).inc()
LATENCY.labels(request.method, route).observe(time.perf_counter() - g.start)
return resp
@app.get("/")
def index():
try:
hits = r.incr("hits")
REDIS_UP.set(1)
except redis.exceptions.RedisError:
hits = "N/A (redis not connected)"
REDIS_UP.set(0)
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.get("/healthz")
def healthz():
# The liveness check does not depend on Redis: if Redis goes down, the app is still "alive" but degraded
return {"status": "ok", "redis": "up" if redis_ok() else "down"}
@app.get("/slow")
def slow():
time.sleep(random.uniform(0.2, 1.5))
return "slow response\n"
@app.get("/error")
def error():
return "simulated failure\n", 500
@app.get("/metrics")
def metrics():
redis_ok() # refresh myapp_redis_up while scraping
registry = CollectorRegistry(support_collectors_without_names=True)
multiprocess.MultiProcessCollector(registry) # aggregate the metric files from all workers
return Response(generate_latest(registry),
headers={"Content-Type": CONTENT_TYPE_LATEST})
EOF
Key points: ① in multi-process mode,create a new registry for each request, attaching only MultiProcessCollector, so that the current process's metrics are not output twice (the recommended pattern in the official docs); ② route use Flask route templates (such as /slow), not raw URLs; ③ status is a string label.
cat > myapp/gunicorn.conf.py <<'EOF'
import os, shutil
from prometheus_client import multiprocess
bind = "0.0.0.0:5000"
workers = int(os.getenv("GUNICORN_WORKERS", "2"))
accesslog = "-"
def on_starting(server):
# Official requirement: empty the multi-process directory before each start, otherwise counts left over from the previous run will be read
d = os.environ["PROMETHEUS_MULTIPROC_DIR"]
shutil.rmtree(d, ignore_errors=True)
os.makedirs(d, exist_ok=True)
def child_exit(server, worker):
# when a worker exits, clean up its live* gauge files
multiprocess.mark_process_dead(worker.pid)
EOF
cat > myapp/requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
prometheus-client==0.26.*
EOF
cat > myapp/.dockerignore <<'EOF'
__pycache__
.git
.env
*.log
EOF
cat > myapp/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PROMETHEUS_MULTIPROC_DIR=/tmp/prom-multiproc
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py gunicorn.conf.py ./
RUN useradd -m appuser
USER appuser
EXPOSE 5000
HEALTHCHECK --interval=15s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/healthz', timeout=2)" || exit 1
CMD ["gunicorn", "-c", "gunicorn.conf.py", "app:app"]
EOF
PROMETHEUS_MULTIPROC_DIR It must exist in the environment before the process starts (the official recommendation is to set it in the startup script or image environment variables, not in Python), so it is written in the Dockerfile's ENV ; the directory itself is on_starting hook empties and recreates it when the master starts.
cat > prometheus/prometheus.yml <<'EOF'
global:
scrape_interval: 15s # default 1m; 15s in the lab makes changes easier to see
scrape_timeout: 10s # must be ≤ scrape_interval
evaluation_interval: 15s # rule evaluation interval (used in Lesson 2)
external_labels:
lab: promlab # added when interacting with external systems (Alertmanager, remote write)
alerting:
alertmanagers:
- static_configs:
- targets: ["alertmanager:9093"]
rule_files:
- "rules/*.yml" # relative to the directory containing this file; Lesson 2 adds rules here
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
- job_name: alertmanager
static_configs:
- targets: ["alertmanager:9093"]
- job_name: grafana
static_configs:
- targets: ["grafana:3000"]
- job_name: node
static_configs:
- targets: ["node-exporter:9100"]
labels:
env: lab
- job_name: myapp
static_configs:
- targets: ["myapp:5000"]
labels:
env: lab
service: myapp
- job_name: redis
static_configs:
- targets: ["redis-exporter:9121"]
labels:
env: lab
EOFcat > alertmanager/alertmanager.yml <<'EOF'
# Minimal working configuration: all alerts go to a receiver that sends no notifications. Lesson 2 replaces this with real routing.
route:
receiver: "null"
group_by: ["alertname", "job"]
receivers:
- name: "null"
EOF
cat > grafana/provisioning/datasources/prometheus.yml <<'EOF'
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
uid: prometheus # fixed uid; dashboard JSON uses it to reference the data source
access: proxy # requests are proxied by the Grafana backend (the browser does not connect to Prometheus directly)
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
httpMethod: POST
timeInterval: 15s # = scrape_interval; $__rate_interval depends on it
EOF
cat > grafana/provisioning/dashboards/promlab.yml <<'EOF'
apiVersion: 1
providers:
- name: promlab
folder: promlab
type: file
allowUiUpdates: true # allows edits in the UI, but the file stays authoritative after saving (a restart overwrites UI changes with the file)
updateIntervalSeconds: 30
options:
path: /etc/grafana/dashboards
EOFcat > compose.yaml <<'EOF'
name: promlab
services:
prometheus:
image: prom/prometheus:v3.16.0
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=7d
- --web.enable-lifecycle # allows POST /-/reload to hot-reload the configuration
volumes:
- ./prometheus:/etc/prometheus:ro
- prom-data:/prometheus
ports:
- "127.0.0.1:9090:9090"
restart: unless-stopped
alertmanager:
image: prom/alertmanager:v0.35.0
command:
- --config.file=/etc/alertmanager/alertmanager.yml
- --storage.path=/alertmanager
volumes:
- ./alertmanager:/etc/alertmanager:ro
- am-data:/alertmanager
ports:
- "127.0.0.1:9093:9093"
restart: unless-stopped
grafana:
image: grafana/grafana:13.3.1
environment:
GF_SECURITY_ADMIN_USER: admin
GF_SECURITY_ADMIN_PASSWORD: ${GF_ADMIN_PASSWORD:-promlab-admin}
GF_USERS_ALLOW_SIGN_UP: "false"
volumes:
- ./grafana/provisioning:/etc/grafana/provisioning:ro
- ./grafana/dashboards:/etc/grafana/dashboards:ro
- grafana-data:/var/lib/grafana
ports:
- "127.0.0.1:3000:3000"
depends_on:
- prometheus
restart: unless-stopped
node-exporter:
image: prom/node-exporter:v1.12.1
command:
- --path.rootfs=/host
pid: host
volumes:
- /:/host:ro,rslave
ports:
- "127.0.0.1:9100:9100"
restart: unless-stopped
myapp:
build: ./myapp
image: myapp:1.0
environment:
REDIS_HOST: redis
GUNICORN_WORKERS: "2"
ports:
- "127.0.0.1:5000:5000"
depends_on:
- redis
restart: unless-stopped
redis:
image: redis:7-alpine
volumes:
- redis-data:/data
restart: unless-stopped
redis-exporter:
image: oliver006/redis_exporter:v1.97.0
environment:
REDIS_ADDR: redis://redis:6379
ports:
- "127.0.0.1:9121:9121"
depends_on:
- redis
restart: unless-stopped
volumes:
prom-data:
am-data:
grafana-data:
redis-data:
EOF
Notes: ① all services are on the default Compose network promlab_default , and Prometheus uses the service name to reach targets (myapp:5000), Docker's built-in DNS (127.0.0.11) handles resolution; ② the node-exporter official README recommends network_mode: host, which gives more accurate network metrics but means Prometheus can no longer reach it by service name. For simplicity the lab keeps it on the Compose network, at the cost that node_network_* it sees the container's own network interface. ③ The default Prometheus image (busybox variant) runs as nobody ; named volume permissions need no adjustment. Since 3.10 there is also a -distroless variant (UID 65532).
cat > loadgen.sh <<'EOF' #!/usr/bin/env bash # about 5 req/s: most requests go to /, about 10% to /slow, about 5% to /error while true; do curl -s -o /dev/null http://127.0.0.1:5000/ (( RANDOM % 10 == 0 )) && curl -s -o /dev/null http://127.0.0.1:5000/slow & (( RANDOM % 20 == 0 )) && curl -s -o /dev/null http://127.0.0.1:5000/error sleep 0.2 done EOF chmod +x loadgen.sh # validate configuration with the promtool / amtool built into the images (no separate installation needed) docker run --rm -v "$PWD/prometheus:/etc/prometheus:ro" --entrypoint promtool \ prom/prometheus:v3.16.0 check config /etc/prometheus/prometheus.yml docker run --rm -v "$PWD/alertmanager:/etc/alertmanager:ro" --entrypoint amtool \ prom/alertmanager:v0.35.0 check-config /etc/alertmanager/alertmanager.yml docker compose up -d --build docker compose ps
Checking /etc/prometheus/prometheus.yml SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax Checking '/etc/alertmanager/alertmanager.yml' SUCCESS Found: - global config - route - 0 inhibit rules - 1 receivers - 0 templates ... NAME IMAGE SERVICE STATUS PORTS promlab-alertmanager-1 prom/alertmanager:v0.35.0 alertmanager Up 20 seconds 127.0.0.1:9093->9093/tcp promlab-grafana-1 grafana/grafana:13.3.1 grafana Up 20 seconds 127.0.0.1:3000->3000/tcp promlab-myapp-1 myapp:1.0 myapp Up 20 seconds (healthy) 127.0.0.1:5000->5000/tcp promlab-node-exporter-1 prom/node-exporter:v1.12.1 node-exporter Up 20 seconds 127.0.0.1:9100->9100/tcp promlab-prometheus-1 prom/prometheus:v3.16.0 prometheus Up 20 seconds 127.0.0.1:9090->9090/tcp promlab-redis-1 redis:7-alpine redis Up 21 seconds 6379/tcp promlab-redis-exporter-1 oliver006/redis_exporter:v1.97.0 redis-exporter Up 20 seconds 127.0.0.1:9121->9121/tcp
The rule_files wildcard matches no files at this point; this is normal (no error is raised). To access the UI on a remote VM: ssh -L 9090:127.0.0.1:9090 -L 3000:127.0.0.1:3000 -L 9093:127.0.0.1:9093 user@vm, then open http://localhost:9090,http://localhost:3000.
./loadgen.sh & # generate traffic in the background; to stop it, use kill %1 sleep 20 curl -s 'http://127.0.0.1:9090/api/v1/query' --data-urlencode 'query=up' \ | jq -r '.data.result[] | "\(.metric.job)\t\(.metric.instance)\t\(.value[1])"'
alertmanager alertmanager:9093 1 grafana grafana:3000 1 myapp myapp:5000 1 node node-exporter:9100 1 prometheus localhost:9090 1 redis redis-exporter:9121 1
Environment self-check checklist
docker compose down keep the data volumes; docker compose down -v delete everything, including the Prometheus TSDB and the Grafana database. Lesson 2 continues directly in this directory, so do not delete it after class ~/promlab.Module 1 · Monitoring and observability: Prometheus architecture and the pull model
- Distinguish "monitoring" from "observability"; name the kinds of question that each of the three signal types (metrics, logs, traces) answers best, and which of them Prometheus covers.
- Draw the Prometheus architecture: service discovery, retrieval (scraping), TSDB, PromQL engine, rule manager, HTTP API/UI, and where exporters, Pushgateway, Alertmanager and Grafana fit.
- Explain the pros and cons of the pull model (built-in health checks,
up, centralized target lists, and poor fit for short-lived jobs and targets behind firewalls), and know which problem each of Pushgateway, Agent mode, remote write and OTLP ingestion solves. - List the main changes in Prometheus 3 compared with 2.x, so that behaviour from older tutorials is not applied to 3.x.
What: monitoring, observability and Prometheus
Monitoring Answers "has a known problem happened?": is CPU too high, is the error rate above 1%, will the disk be full in a few days. Observability Answers "why is the system behaving this way?", including problems you did not anticipate. It requires the system to emit signals rich enough that, after the fact, you can pin a problem down to a version, an instance or a specific request.
| Signal | Data shape | Best at answering | Typical tools | Cost |
|---|---|---|---|---|
| Metrics | Numeric time series (name + labels + sample points) | "How much, how fast, how long": QPS, error rate, P95 latency, saturation; trends and alerts | Prometheus, Mimir, Thanos, Azure Monitor / AMP | Cheapest: each sample of each series compresses to about 1–2 bytes; but individual request details are not kept |
| Logs | Timestamped event text / structured records | "What exactly happened": exception stacks, request parameters, audit trails | Loki, Elasticsearch, Azure Log Analytics | Billed by data volume; expensive at high volume |
| Distributed traces | The span tree of one request across services | "Which hop is slow": call chains and dependencies | Tempo, Jaeger, OpenTelemetry | Usually requires sampling |
Prometheus is the second CNCF project to graduate (the first was Kubernetes), and it focuses on metrics: it periodically pulls metrics from targets, stores them in a local time series database (TSDB), provides the PromQL query language, and evaluates rules to produce alerts that are sent to Alertmanager. Grafana is a separate visualization platform that can turn data from Prometheus (and dozens of other data sources) into dashboards.
Why: why Prometheus became the de facto standard for cloud-native metrics
- Multi-dimensional data model: one metric name can carry arbitrary labels (
route,status,instance), and queries can slice and aggregate freely, unlike rigid dotted hierarchical names such as "host.app.metric". - Pull + service discovery: Prometheus itself knows which targets should exist (from the Kubernetes API, cloud APIs, Consul, files or static configuration), and every failed pull is immediately reflected in
upmetrics. - Single binary, no external dependencies: it runs on local SSD storage; a single instance can write hundreds of thousands to millions of samples per second, and it is simple to deploy with a small failure surface.
- Ecosystem: hundreds of exporters (node, Redis, PostgreSQL, blackbox, ...), client libraries for all mainstream languages, and native exposure by Kubernetes components
/metrics; the exposition format has been standardized as OpenMetrics.
How: architecture and the journey of one data point
- Service discovery (SD):
static_configs,file_sd_configs,kubernetes_sd_configs,azure_sd_configs,ec2_sd_configsetc. produce "target groups": a set of addresses + metadata labels (__meta_*). - Scraping (scrape): each target has its own scrape loop, and every
scrape_intervalsends one HTTP GET/metrics; first it passes through relabel, which sets the target's final labels or drops the target (the core animation of Module 3). - Storage (TSDB): samples first enter the in-memory head block, and are also appended to the on-disk WAL (write-ahead log, replayed after a crash). Data in the head is cut into an immutable block roughly every 2 hours and written to disk; blocks are later merged in the background (compaction) into larger blocks. The default retention is 15 days (
--storage.tsdb.retention.time). - Queries: the PromQL engine serves queries through the HTTP API (
/api/v1/query,/api/v1/query_range), and Grafana, the built-in UI and alerting rules all go through it. - Rules: the rule manager evaluates every
evaluation_intervalrecording rules (precomputed, written back to the TSDB) and alerting rules (when the condition holds continuously for theforperiod, the alert is pushed to Alertmanager). - Alertmanager: a separate process that handles deduplication, grouping, inhibition, silencing and routing to email / Teams / Slack / PagerDuty / webhooks (Lesson 2).
When: when to use Prometheus and when not to
| Scenario | Suitable? | Reason / alternative |
|---|---|---|
| Health, performance, capacity trends and alerting for services and infrastructure | ✓ First choice | This is exactly what it was designed for |
| Kubernetes cluster monitoring | ✓ | Native service discovery; managed with an Operator in Lesson 5 |
| Per-request billing and business data that must be 100% exact | ✗ | Metrics are sampled and extrapolated approximations (Module 4 shows increase() they can return decimals); use a database or event stream |
| to store the detailed context of each request | ✗ | Use logs and traces; high-cardinality labels (user IDs, request IDs) will overwhelm the TSDB |
| Batch jobs that finish within seconds | △ | They may finish between two scrapes: use Pushgateway (only suitable for service-level batch jobs), or have the job write a textfile collector |
| Multi-year long-term retention and global queries across clusters | △ | A single-node TSDB does not replicate: use remote write to Mimir / Thanos / a managed service (Lessons 3, 4 and 6) |
Main changes in Prometheus 3 (3.0 released 2024-11; current is 3.16)
| Area | 2.x | 3.x | Impact on you |
|---|---|---|---|
| Web UI | Old React UI | New UI (tree-style PromQL explanation, metrics explorer) | Screenshots differ from older tutorials |
| Metric and label names | Only [a-zA-Z_:][a-zA-Z0-9_:]* | is allowed, but UTF-8 is now allowed by default (such as OTel's http.server.duration); in PromQL, reference them with {"name.with.dots"} quotes | Applications should still use traditional naming to avoid incompatibility with downstream tools |
| Range selectors and lookback | Closed on both ends | Open on the left, closed on the right: samples exactly at the start of the window are no longer included | Results of a very few boundary queries may change |
| Scrape Content-Type | Falls back to the text format when unrecognized | No longer falls back implicitly; the scrape fails. It can be set with fallback_scrape_protocol | (see the Module 8 troubleshooting case) |
| Agent mode | Feature flag | Stable; use --agent to start (scraping + remote write only, no queries) | Edge / multi-cluster collection |
| Native histogram | Experimental | Stable since 3.8; but it must be set in the scrape configuration scrape_native_histograms: true | Module 2 |
| Other | — | OTLP receiving endpoint (--web.enable-otlp-receiver), Remote Write 2.0, automatic setting of GOMAXPROCS/GOMEMLIMIT, configuration auto-reload stable since 3.12, and in 3.16 anchored/smoothed the range selector modifier became stable | Lessons 6 and 7 |
Architecture diagram: Prometheus ecosystem components
Comparison diagram: pull vs push
Simulator: when a target goes down, which model notices first, pull or push?
Time advances in 15-second steps. After clicking "Take myapp down", keep advancing and compare the logs on both sides. Under the pull model, the failed scrape itself produces data (up=0); under the push model, the collector can only infer the situation from how long it has been since the last data arrived.
Core commands and APIs
| Command / endpoint | Purpose | Key parameters / notes |
|---|---|---|
GET /-/healthy,/-/ready | Liveness / readiness checks | During WAL replay at startup /-/ready returns 503 |
GET /api/v1/status/buildinfo | Version, Go version, build information | equivalent to prometheus_build_info metrics |
GET /api/v1/targets | Status of all targets, last error, scrape duration | ?state=active|dropped|any |
GET /api/v1/query?query=up | Instant query | time= specify the evaluation time |
GET /api/v1/status/flags,/config | Startup flags and configuration currently in effect | Check whether the configuration was actually loaded |
POST /-/reload | Hot-reload configuration | requires --web.enable-lifecycle; you can also send SIGHUP to the process |
promtool check config | Validate the configuration and the rule files it references | Must run in CI |
curl -s 127.0.0.1:9090/-/healthy; echo curl -s 127.0.0.1:9090/api/v1/status/buildinfo | jq -r '.data | "\(.version) \(.goVersion)"' curl -s 127.0.0.1:9090/api/v1/targets | jq -r '.data.activeTargets[] | [.labels.job, .health, .lastScrapeDuration, .lastError] | @tsv'
Prometheus Server is Healthy. 3.16.0 go1.25.x prometheus up 0.004517 alertmanager up 0.003121 grafana up 0.011893 node up 0.021774 myapp up 0.006410 redis up 0.008032
How to verify:health is up and lastError is empty. Common errors: Running curl myapp:5000 fails: the service name can only be resolved inside the Compose network; from the host, use 127.0.0.1:5000. Production use: After a CI/CD release, call the targets API to confirm that new instances have been discovered and scraped successfully.
Prometheus monitors itself
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=prometheus_tsdb_head_series' | jq -r '.data.result[0].value[1]'
curl -s 127.0.0.1:9090/metrics | grep -E '^prometheus_target_interval_length_seconds\{.*quantile="0.99"'
2187
prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15.0012
prometheus_tsdb_head_series is the number of active series in memory, the single most important number for capacity planning; target_interval_length a value close to 15 means the scrape loop runs on time; a clearly larger value means Prometheus is overloaded.
Lab 1: get to know the Prometheus UI and the pull model (about 5 min)
http://localhost:9090/targets, and check each job's Endpoint, Labels, Last scrape and Scrape duration. Click myapp the labels area and note instance="myapp:5000" and job="myapp" are added by Prometheus, not output by the application.up count by (job) (up) scrape_duration_seconds
Every target has these "synthetic metrics", even if the application itself exposes no metrics at all.
docker compose stop redis-exporter
sleep 20
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=up{job="redis"}' | jq -r '.data.result[0].value[1]'
curl -s 127.0.0.1:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.job=="redis") | .lastError'
0 Get "http://redis-exporter:9121/metrics": dial tcp: lookup redis-exporter on 127.0.0.11:53: no such host
After the container stops it disappears from the Compose network, so the error is a DNS resolution failure rather than connection refused. up=0 is written during the "failed scrape". This is the free health check that the pull model gives you.
docker compose start redis-exporter
http://localhost:9090/tsdb-status (Status → TSDB Status), note the number of series in the head and the "metrics with the most label-value pairs". Lesson 7's cardinality troubleshooting uses this page.Case 1: migrating from Nagios checks to Prometheus
Problem: The team ran 200 check scripts with Nagios every 5 minutes. They only give three states (OK / WARN / CRIT) and cannot answer "since when has latency been getting worse?"Approach: Install node_exporter on hosts, add client-library instrumentation to applications, and rewrite alerts as PromQL expressions (for example, “5-minute error rate > 2% for 10 minutes”). Limitation: Prometheus does not perform active functional checks (such as whether the login flow works). For these, use synthetic probing with blackbox_exporter (Lesson 5).
Case 2: batch jobs are "invisible"
Problem: A data export job that runs at 2 a.m. every night takes 20 seconds, with a 30-second scrape interval, so it is often never scraped at all. Approach: When the job finishes, push job_last_success_timestamp_seconds to Pushgateway, with the alert condition time() - job_last_success_timestamp_seconds > 26*3600. Limitation: Pushgateway does not expire data and is not an aggregator. Do not push metrics of long-running services to it, because that would hide instance outages (up only Pushgateway itself is reflected).
Case 3: edge sites behind firewalls
Problem: The central Prometheus cannot actively connect into the networks of 40 store sites. Approach: Each store runs prometheus --agent (scraping only, no queries or alerts) and pushes via HTTPS remote write to central storage (Mimir or managed Prometheus). Limitation: On the central side, design a separate heartbeat alert for "a store has stopped pushing" (for example, absent_over_time(up{site="x"}[10m])), because this brings back the problems of the push model.
Common errors and fixes
Browser cannot open http://localhost:9090 (ERR_CONNECTION_REFUSED)
Cause: The port is bound only to 127.0.0.1 on the lab machine, but you are opening it from a browser on another computer; or the container is not running.
docker compose ps prometheus docker compose logs --tail=20 prometheus ss -ltnp | grep 9090
Fix: Use an SSH tunnel ssh -L 9090:127.0.0.1:9090 user@vm; do not change it to 0.0.0.0 for convenience. Prometheus has no authentication by default.
err="opening storage failed: lock DB directory: resource temporarily unavailable"
Cause: Two Prometheus processes are using the same data directory (for example, by manually mounting the same volume as Compose). docker run The TSDB uses a lock file to prevent concurrent writes.
docker ps --filter volume=promlab_prom-data
Fix: Stop the extra container; in HA deployments, every replica must have its own storage.
Prometheus log: Error loading config ... field xxx not found in type config.plain
Cause: YAML indentation or a field name is wrong (for example, writing static_configs as static_config, or placing targets under job_name at the same level). Prometheus strictly rejects unknown fields: startup fails or reload is refused (after a failed reload, the old configuration keeps being used).
docker run --rm -v "$PWD/prometheus:/etc/prometheus:ro" --entrypoint promtool prom/prometheus:v3.16.0 check config /etc/prometheus/prometheus.yml
Fix: Correct it based on promtool's output; put promtool into CI.
/-/reload returns "Lifecycle API is not enabled."
Cause: Did not add --web.enable-lifecycle.
Fix: Add the flag, or use docker compose kill -s SIGHUP prometheus. In production this is usually handled by a config-reloader sidecar (Lesson 5).
1. Use a single curl + jq command to list the job and error message of every unhealthy target.
curl -s 127.0.0.1:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.health!="up") | "\(.labels.job): \(.lastError)"'
2. Query how many instances are up in each job.
sum by (job) (up)
Use count by (job) (up == 1) is also fine; count by (job) (up) counts the total number of instances (including the ones that are down).
The company needs to monitor: ① 100 Linux VMs; ② a cron job that runs for 5 seconds every 10 minutes; ③ a cluster of devices in a customer's data center that allows only outbound HTTPS; ④ the amount of each order, for reconciliation. How should each be collected?
① node_exporter + central Prometheus pulling, using azure_sd_configs/ec2_sd_configs or file-based service discovery to manage targets. ② When the job finishes, push its "last successful timestamp" and duration to Pushgateway (or write them with node_exporter's textfile collector), and alert if the timestamp is too old. ③ Run Prometheus in Agent mode on site to scrape, and use outbound remote write to push to central storage, with a missing-data alert for "stopped pushing". ④ Do not use Prometheus for this: reconciliation needs exact per-transaction data, so store it in a database or event stream; Prometheus only records aggregate trends of order counts and amounts (counters), for monitoring rather than reconciliation.
Verified teaching videos
Official documentation
- Prometheus Overview (architecture)
- FAQ (why pull, and why not 100% accuracy)
- Prometheus 3.0 migration guide
- When to use the Pushgateway
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided and can be passed to a video tool.
Visual: three screens labeled "Metrics / Logs / Traces"; the metrics screen shows line charts, the logs screen shows scrolling text, and the traces screen shows a waterfall chart.
Narration: observability has three types of signals. Metrics are the cheapest and are good for answering how much, how fast and how long. Prometheus handles only this type.
Visual: every 15 seconds the Prometheus icon sends GET /metrics arrows to three services; they return a stack of text lines that fall into a cylinder labeled TSDB.
Narration: Prometheus itself knows which targets should exist and pulls from them at a fixed interval. Samples first go into memory and the WAL, and every two hours they are written out as a block.
Visual: one of the services turns red, the arrow returns a cross, and an up = 0 label appears next to it at once. On the right, the push-model collector only shows an hourglass.
Narration: a failed pull is itself data. In the push model, silence may mean death, or it may just mean there is no traffic.
Visual: Grafana reads PromQL results from Prometheus and draws charts; an alert arrow points to Alertmanager.
Narration: Grafana is for looking, Alertmanager is for waking people up, and the data always stays in Prometheus.
Module 2 · Metric types and the data model: counter, gauge, histogram, summary
- State precisely the identity of a time series (metric name + the full set of labels) and the structure of a sample (int64 millisecond timestamp + float64 value, or a native histogram).
- Read the text exposition format's
# HELP,# TYPE,_total,_bucket{le=…},_sum,_count. - Choose the right type for a new metric (counter, gauge, histogram or summary), and explain the fundamental difference between histogram and summary in terms of "aggregability".
- Follow naming conventions (application prefix, base units,
_total,_seconds,_bytes,_ratio), and estimate how many series a metric will produce.
What: time series and samples
Every time series is uniquely identified by a metric name plus a set of label key-value pairs. The metric name is itself a label: __name__. For example, the two lines below are two different series:
myapp_http_requests_total{job="myapp", instance="myapp:5000", method="GET", route="/", status="200"}
myapp_http_requests_total{job="myapp", instance="myapp:5000", method="GET", route="/", status="500"}
each series is samples arranged in time order: (int64 millisecond timestamp, float64 value). Since 3.8, a sample value can also be a native histogram (a whole histogram stored as one value). Any change in a label value (even one extra space) creates a new series, so the number of series = the product of the number of values for each label; this is the "cardinality".
The four metric types
| Type | Meaning | Example | Correct usage | Incorrect usage |
|---|---|---|---|---|
| Counter | A cumulative value that only goes up; resets to zero on process restart | myapp_http_requests_total,node_network_receive_bytes_total | rate(),increase() then aggregate | Plot the raw value; using a counter for something that can decrease |
| Gauge | The current value, which can go up or down | myapp_redis_up,node_memory_MemAvailable_bytes, queue length, temperature | Read it directly; avg_over_time,max_over_time,deriv,predict_linear | using rate() |
| Histogram | Counts observations into preset buckets (classic: one counter series per bucket) | myapp_http_request_duration_seconds | histogram_quantile(0.95, sum by (le) (rate(..._bucket[5m]))); average = rate(_sum)/rate(_count) | Bucket boundaries unrelated to the SLO; forgetting sum by (le) |
| Summary | Quantiles computed directly on the client (sliding time window) | Go runtime's go_gc_duration_seconds | Looking at a single instance {quantile="0.99"} | Averaging quantiles across instances— this is mathematically invalid |
Why: why histogram is usually better than summary
A "P95 latency" number cannot be derived from the P95 of each instance (the P95 of averages ≠ the average of the P95s). A histogram exposes the count in each bucket, and counts can be added across instances, so you can first sum sum the buckets of all instances and then compute the quantile; the cost is that the result is an estimate from linear interpolation within a bucket, whose precision depends on the bucket boundaries. A summary is precise but cannot be aggregated, and its quantiles and time window are fixed on the client. Conclusion: use histograms for server-side latency, and place a bucket boundary at the SLO threshold (for example, if the SLO is 300ms, have a 0.25 or 0.3 bucket).
How: the text exposition format
# HELP myapp_http_requests_total Multiprocess metric
# TYPE myapp_http_requests_total counter
myapp_http_requests_total{method="GET",route="/",status="200"} 1842.0
myapp_http_requests_total{method="GET",route="/error",status="500"} 93.0
# HELP myapp_http_request_duration_seconds Multiprocess metric
# TYPE myapp_http_request_duration_seconds histogram
myapp_http_request_duration_seconds_bucket{le="0.005",method="GET",route="/"} 1790.0
myapp_http_request_duration_seconds_bucket{le="0.01",method="GET",route="/"} 1838.0
...
myapp_http_request_duration_seconds_bucket{le="5.0",method="GET",route="/"} 1842.0
myapp_http_request_duration_seconds_bucket{le="+Inf",method="GET",route="/"} 1842.0
myapp_http_request_duration_seconds_count{method="GET",route="/"} 1842.0
myapp_http_request_duration_seconds_sum{method="GET",route="/"} 4.73
# HELP myapp_redis_up Multiprocess metric
# TYPE myapp_redis_up gauge
myapp_redis_up 1.0
- Buckets are cumulative:
le="0.01"counts all requests ≤ 0.01 seconds (including those ≤ 0.005)le="+Inf"always equals_count. - Sample lines usually have no timestamp: Prometheus uses the scrape time as the timestamp.
- HELP became "Multiprocess metric": this is a known behaviour of the prometheus_client multi-process mode. The aggregator reads data back from each worker's mmap files, and the original help text is not stored in those files. It does not affect queries.
- No
_createdseries: in single-process mode the Python client also emits_createdtimestamps for counters and histograms; multi-process mode does not. - The client library adds or strips
_total: the code passes"myapp_http_requests_total", the library stores it internally asmyapp_http_requests, and adds_totalwhen exposing it.
Naming conventions (official best practices)
| Rule | Good | Bad |
|---|---|---|
| Application / domain prefix | myapp_http_requests_total | requests |
| Use base units | _seconds,_bytes,_ratio (0–1) | _milliseconds,_kb,_percent |
counters end with _total . | ..._errors_total | ..._error_count |
| Labels are for "different dimensions of the same thing" | {status="500"} | myapp_http_500_total (encoding dimensions into the name) |
| Label values must be bounded | route="/user/<id>" | path="/user/83920",user_id,request_id |
When: should you use native histograms now?
Native histograms (sparse, exponential buckets, the whole histogram stored as one sample) have been a stable feature since Prometheus 3.8. From 3.9 the old native-histogram feature flag no longer has any effect; instead, set scrape_native_histograms: true in the global or scrape configuration (default false). When enabled, scrape protocol negotiation prefers the protobuf format. Benefits: no need to predefine buckets, high precision, and one series replaces dozens of _bucket series. Prerequisite: the client library must support emitting native histograms (the Go client does; Python prometheus_client 0.26's Histogram class still emits classic histograms; the library only has the experimental NativeHistogram data structures, for custom collectors and the experimental OpenMetrics 2.0 output). This course's myapp uses classic histograms; Lesson 7 discusses migration. A transitional option is NHCB (native histograms with custom buckets,convert_classic_histograms_to_nhcb: true), which can convert classic histograms at scrape time for storage.
rate() handles this kind of "reset" automatically, but if you write delta() or subtract directly, you get negative numbers. ② "A gauge can also use rate" —rate() treats every drop of a gauge as a reset, so the result is meaningless; for the rate of change of a gauge, use deriv(). ③ "A histogram's P99 is an exact value" — it is linear interpolation within a bucket, and the sparser the buckets, the larger the error. ④ "Adding a label is cheap" — each new label value multiplies the existing number of series.Data model: series identity and samples
Classic histogram buckets (cumulative counts)
Metric type playground: how each event changes the exposition format
Click an event button; on the right, the live output of the application /metrics is shown. Note that one histogram observation increments several buckets by 1 (cumulative), and how "restarting the process" affects counters and gauges differently.
Inspect and understand the exposition format
| Command | Purpose | Notes |
|---|---|---|
curl -s 127.0.0.1:5000/metrics | Look at the application output directly | The fastest check that instrumentation is working |
curl -sI -H 'Accept: application/openmetrics-text' … | Check Content-Type | myapp always returns this lesson's fixed value text/plain; version=1.0.0 |
promtool check metrics | Check the exposition format against best practices (naming, units, HELP) | Read from stdin |
/api/v1/metadata?metric=… | The type, HELP and unit recorded by Prometheus | The Grafana metrics explorer also uses it |
/api/v1/series?match[]=… | List matching series (without fetching samples) | Estimate cardinality |
curl -s 127.0.0.1:5000/metrics | grep -E '^myapp_http_requests_total' curl -s 127.0.0.1:5000/metrics | docker run --rm -i --entrypoint promtool prom/prometheus:v3.16.0 check metrics
myapp_http_requests_total{method="GET",route="/",status="200"} 2210.0
myapp_http_requests_total{method="GET",route="/slow",status="200"} 231.0
myapp_http_requests_total{method="GET",route="/error",status="500"} 112.0
myapp_http_requests_total{method="GET",route="/healthz",status="200"} 96.0
promtool check metrics No output means no problems were found; naming problems are reported line by line (for example, a counter missing _total, or using a non-base unit).
# How many series does this metric have? curl -s -g '127.0.0.1:9090/api/v1/series?match[]=myapp_http_request_duration_seconds_bucket' | jq '.data | length' # Type and HELP that Prometheus remembers curl -s '127.0.0.1:9090/api/v1/metadata?metric=myapp_http_request_duration_seconds' | jq
44
{
"status": "success",
"data": {
"myapp_http_request_duration_seconds": [
{ "type": "histogram", "help": "Multiprocess metric", "unit": "" }
]
}
}
44 = 4 routes × 11 buckets (10 +Inf plus +Inf); method is only GET. Production use: Before going live, use the series API to estimate the number of series for a new metric, multiply by the number of instances, and assess the impact on Prometheus memory.
Lab 2: interpret the metrics of myapp, node and Redis (about 6 min)
before=$(curl -s 127.0.0.1:5000/metrics | awk '/^myapp_http_requests_total\{method="GET",route="\/error"/ {print $2}')
for i in $(seq 1 10); do curl -s -o /dev/null 127.0.0.1:5000/error; done
after=$(curl -s 127.0.0.1:5000/metrics | awk '/^myapp_http_requests_total\{method="GET",route="\/error"/ {print $2}')
echo "before=$before after=$after"
before=112.0 after=123.0
curl -s 127.0.0.1:5000/metrics | grep 'duration_seconds_bucket{.*route="/slow"'
myapp_http_request_duration_seconds_bucket{le="0.005",method="GET",route="/slow"} 0.0
...
myapp_http_request_duration_seconds_bucket{le="0.1",method="GET",route="/slow"} 0.0
myapp_http_request_duration_seconds_bucket{le="0.25",method="GET",route="/slow"} 9.0
myapp_http_request_duration_seconds_bucket{le="0.5",method="GET",route="/slow"} 58.0
myapp_http_request_duration_seconds_bucket{le="1.0",method="GET",route="/slow"} 140.0
myapp_http_request_duration_seconds_bucket{le="2.5",method="GET",route="/slow"} 236.0
myapp_http_request_duration_seconds_bucket{le="5.0",method="GET",route="/slow"} 236.0
myapp_http_request_duration_seconds_bucket{le="+Inf",method="GET",route="/slow"} 236.0
/slow sleeps randomly for 0.2–1.5 seconds, so the buckets up to 0.1 are all 0, and from 2.5 onward every request has already fallen into them.
docker compose stop redis curl -s 127.0.0.1:5000/metrics | grep ^myapp_redis_up curl -s 127.0.0.1:9121/metrics | grep -E '^redis_up ' docker compose start redis sleep 2; curl -s 127.0.0.1:5000/metrics | grep ^myapp_redis_up
myapp_redis_up 0.0 redis_up 0 myapp_redis_up 1.0
Compare two "up" values: Prometheus's up{job="redis"} is still 1 (the exporter itself can be scraped), and the exporter's own redis_up shows whether Redis can be connected. This is the standard design of exporters.
curl -s 127.0.0.1:9090/metrics | grep -E '^go_gc_duration_seconds'
go_gc_duration_seconds{quantile="0"} 2.9e-05
go_gc_duration_seconds{quantile="0.25"} 4.1e-05
go_gc_duration_seconds{quantile="0.5"} 5.6e-05
go_gc_duration_seconds{quantile="0.75"} 8.8e-05
go_gc_duration_seconds{quantile="1"} 0.000392
go_gc_duration_seconds_sum 0.0213
go_gc_duration_seconds_count 247Case 1: the raw URL path was used as a label
Problem: An API used request.path as a label, and the paths contained order numbers. A week later Prometheus memory grew from 4 GiB to 28 GiB and it was OOM-killed. Approach: Use the framework's route templates instead (Flask's url_rule.rule, Express's req.route.path), record all unmatched routes under one unmatched label value, and also set sample_limit in the scrape configuration as a fuse. Limitation: After the fix, the old series remain in the TSDB until they expire, so memory only drops after the head is truncated (about 2–3 hours).
Case 2: averaging summary quantiles across instances
Problem: The dashboard was written as avg(http_latency{quantile="0.99"}); one of 10 instances was very slow, and after averaging everything looked normal while users were complaining. Approach: Switch to a histogram,histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m]))). Limitation: Requires changing application code and redeploying; both metric types coexist during the transition.
Case 3: milliseconds or seconds?
Problem: Team A's metric is called latency_ms and team B's is called duration_seconds; the units on one dashboard were a mess, and an alert threshold was wrong by a factor of 1000. Approach: Standardize on base units (seconds, bytes) and let Grafana format them for display as ms; run promtool check metrics on the exposition format in CI.
Common errors and fixes
ValueError: Duplicated timeseries in CollectorRegistry: {'myapp_http_requests_total', ...}
Cause: The same metric was created twice (the module was imported twice, a Counter was created inside a function instead of at module level, or Flask's debug-mode reloader).
Fix: Define each metric only once at module level; in tests, when isolation is needed, pass in a separate registry=.
Only python_gc_* / process_* appear in /metrics; no myapp_ metrics are visible
Cause: In multi-process mode, the default REGISTRY was used (which only covers the current process's default collectors) instead of MultiProcessCollector; or no request has been made yet (labeled metrics are not output until the first .labels() ).
docker compose exec myapp ls -l /tmp/prom-multiproc
Fix: Following the approach in this lesson, metrics() create a new registry on each call and attach MultiProcessCollector; send a few requests first. By the way, in multi-process mode process_* custom-collector metrics like this are not available; this is a limitation listed in the official docs.
The rate() result has a huge spike / increase() returns a negative value (a "comparison" query)
Cause: A value that can decrease was declared as a counter (for example, "current connections"), so every decrease is treated as a reset; or the increment was computed by hand with x - x offset 5m and a reset produces a negative number.
Fix: Use a gauge for values that can decrease; compute counter increments with increase()/rate() always.
histogram_quantile result is always equal to some bucket's upper bound (for example, always 0.5)
Cause: The buckets are too sparse, so most observations fall into the same bucket, and interpolation can only spread them linearly within that bucket.
Fix: Add buckets around the thresholds you care about; or use native histograms in a supported language.
1. Use the series API to count how many series starting with myapp_ exist in total.
curl -s -g '127.0.0.1:9090/api/v1/series?match[]={__name__=~"myapp_.*"}' | jq '.data | length'2. Calculate the average response time of /slow (in seconds) directly from /metrics.
curl -s 127.0.0.1:5000/metrics | awk '/duration_seconds_sum\{.*route="\/slow"/{s=$2} /duration_seconds_count\{.*route="\/slow"/{c=$2} END{print s/c}'This is the average "since startup to now"; in PromQL, use rate(_sum[5m]) / rate(_count[5m]) to get the average over the last 5 minutes.
Design metrics for a file upload service: you need the number of uploads, the number of failures, the number of uploads in progress, the distribution of uploaded file sizes, and the distribution of durations (SLO: 95% within 2 seconds). Give the metric names, types, labels and buckets.
upload_requests_total{result="success|failure"} (counter; failure is a label value rather than a separate metric, which makes ratios easy to compute); upload_in_progress (gauge; in multi-process mode use livesum); upload_size_bytes (histogram with exponential buckets such as 1e4, 1e5, 1e6, 1e7, 1e8); upload_duration_seconds (histogram whose buckets include 2, the SLO threshold, for example 0.1, 0.25, 0.5, 1, 2, 5, 10). Do not use usernames or file names as labels.
Verified teaching videos
Official documentation
- Data model
- Metric types
- Metric and label naming
- Histograms and summaries
- Native histograms specification
- client_python: Multiprocess mode
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.
Visual: one metric line is split into three parts: the name, the label braces and the value; the labels are highlighted and their values replaced one by one, and each replacement splits off a new line.
Narration: the name plus all labels is one time series. Change one label value and you get a new series.
Visual: an odometer (counter) only goes up and jumps back to zero when the process restarts; a fuel gauge (gauge) swings up and down.
Narration: a counter only goes up; read it with rate. A gauge is the current value; read it directly.
Visual: requests like balls fall into a row of buckets from low to high; a ball that falls into the 0.5-second bucket lights up the 1-second, 2.5-second and +Inf buckets at the same time.
Narration: histogram buckets are cumulative, and counts can be added across instances, so you can calculate a global P95.
Visual: the P99 values of two instances are averaged, and the result is marked with a red cross.
Narration: summary quantiles cannot be averaged. For server-side latency, use a histogram.
Module 3 · Scrape configuration, exporters and application instrumentation
- Read and write
scrape_configs:job_name,scrape_interval/scrape_timeout,metrics_path,scheme,params, various*_sd_configs,sample_limit. - Distinguish the two relabel stages:
relabel_configs(before scraping, acting on the target's targets' labels, can drop targets) andmetric_relabel_configs(after scraping and before storage, acting on each sample); masterreplace,keep,drop,labelmap,labeldropactions. - Recite in order the internal steps of one scrape cycle, and the synthetic metrics and staleness markers that each scrape additionally produces.
- Know when to use an exporter and when to instrument directly; understand how node_exporter and redis_exporter work and the limitations of prometheus_client's multi-process mode.
What: the components of a scrape configuration
| Field | Default | Description |
|---|---|---|
job_name | Required | becomes a target label job; globally unique |
scrape_interval / scrape_timeout | inherits from global (global defaults: 1m / 10s) | the timeout must be ≤ the interval; this lesson uses 15s / 10s |
metrics_path / scheme / params | /metrics / http / none | the blackbox exporter uses params passes module,target (Lesson 5) |
static_configs,file_sd_configs,kubernetes_sd_configs … | — | produce target groups: __address__ + metadata labels __meta_* + added labels |
relabel_configs | none | rewrite / filter targets before scraping |
metric_relabel_configs | none | rewrite / drop samples after scraping (the last fuse; the cost of scraping and parsing has already been paid) |
honor_labels | false | When a target's own label conflicts with a target label: false → the target's own label is renamed to exported_<name>; true → keep the target's own label (used only for federation and Pushgateway) |
sample_limit / label_limit / body_size_limit | 0 (unlimited) | if exceeded,the entire scrape fails,up=0; a fuse that prevents cardinality explosion |
scrape_protocols / fallback_scrape_protocol | OpenMetrics 1.0 → OM 0.0.1 → text 1.0.0 → text 0.0.4 (protobuf preferred when native histograms are enabled) | determines the Accept header; 3.x no longer falls back implicitly for unknown Content-Types |
scrape_native_histograms | false | the native histogram scraping switch, stable since 3.8 |
How: the internal steps of one scrape cycle
- Service discovery produces target groups. Statically configured targets get:
__address__="myapp:5000",__scheme__="http",__metrics_path__="/metrics",__scrape_interval__="15s",__scrape_timeout__="10s",job="myapp"andlabels:the ones written inenv,service. - relabel_configs Executed in order; if any step
keep/dropdecides to drop a target, the target enters "dropped targets" (visible in/api/v1/targets?state=dropped), and it is not scraped. - Fill in defaults and remove internal labels: if there is no
instance, set it to__address__'s value; all labels starting with__are dropped before storage (__meta_*only available in the relabel stage). - Scheduling: each target has one goroutine scrape loop. The first scrape time is set by a fixed offset derived from the hash of the target labels, which spreads hundreds of targets evenly across one interval so they are not all hit at once.
- HTTP GET: the request headers include
Accept(negotiated withscrape_protocolsweights),Accept-Encoding: gzip,User-Agent: Prometheus/3.16.0,X-Prometheus-Scrape-Timeout-Seconds: 10(telling the exporter how much time it has left). A timeout means failure. - Parsing: the parser is chosen from the response Content-Type (text, OpenMetrics, protobuf); if Content-Type is missing or unrecognized and not set to
fallback_scrape_protocol, the scrape fails. - metric_relabel_configs Executed for each sample; it can be dropped or rewritten; then attaches target labels (
job,instance,env...), conflicts are handled byhonor_labels; checkssample_limitand other limits. - Append to TSDB: new series create a memSeries in the head; samples are appended to the head's in-memory chunk; and they are also written to the WAL (
/prometheus/wal, 128 MiB per segment). The samples of one scrape are committed as a single transaction. - Synthetic metrics: every scrape (whether it succeeds or fails) writes
up,scrape_duration_seconds,scrape_samples_scraped,scrape_samples_post_metric_relabeling,scrape_series_added. - Staleness marker: series that appeared in the previous scrape but not in this one, and all series of a target when the target disappears or its scrape fails, are written as a special NaN sample. Queries treat them as absent immediately, instead of continuing to show the value for 5 minutes (the default lookback).
Why: exporter or direct instrumentation?
| Direct instrumentation (client library) | Exporter | |
|---|---|---|
| Suitable for | your own code | software you cannot change: the Linux kernel, Redis, PostgreSQL, hardware |
| How it works | the application keeps counters inside the process,/metrics and outputs them when | a separate process; when it receives a scrape request,synchronously reads the target (/proc, Redis INFO, SQL queries) and translates it into metrics |
up meaning | whether the application itself is scrapable | whether the exporter is scrapable; whether the monitored object is available is checked through the exporter's own metrics (redis_up,pg_up) |
| Deployment | no extra process | usually one-to-one with the monitored object (sidecar or same host); there is also a multi-target mode (blackbox, redis_exporter's /scrape?target=) |
When: limitations of client_python multi-process mode (as listed in the official docs)
- must set
PROMETHEUS_MULTIPROC_DIR, and empty it before each start; metric aggregation reads the mmap files written by each worker. - Custom collectors are not available (including the default
process_*CPU/memory metrics); Gauge cannot useset_function; Info and Enum are not available; Pushgateway cannot be used; exemplars are not supported. - Gauge requires choosing
multiprocess_mode: the defaultall(one series per process, with apidlabel),min/max/sum/mostrecent, and the variant that considers only live processes,live*. myapp usesmyapp_redis_upuseslivemostrecent.
^(?:regex)$). ③ "The instance label is told to Prometheus by the application" — it is generated by Prometheus from __address__ . ④ "Grafana keeps showing the last value when a scrape fails" — staleness markers make the series disappear at once, so the graph shows a gap.Two relabel stages
Process structure of myapp instrumentation (gunicorn multi-process)
Core animation A: one scrape cycle (real mechanics)
Choose a scenario and click "Next". The log under each step gives the matching real configuration, HTTP request header or internal behaviour. Note how, in the "target failure" and "series disappears" scenarios, staleness markers make the chart break off immediately.
Scrape configuration commands
| Command | Purpose | Description |
|---|---|---|
promtool check config prometheus.yml | Static validation | also checks rule_files the rule files it references |
curl -X POST :9090/-/reload | Hot reload | On failure, the old configuration is kept; look at prometheus_config_last_reload_successful |
/api/v1/targets?state=dropped | targets dropped by relabel, along with their original labels | a handy tool for debugging keep / drop rules |
/api/v1/targets/metadata | metric metadata exposed by each target | ?match_target={job="myapp"} |
promtool query instant | run PromQL from the command line | acceptance assertions in CI |
curl -s :9100/metrics | grep ^node_ | look at the exporter output directly | rule out Prometheus-side problems |
cd ~/promlab curl -s -X POST 127.0.0.1:9090/-/reload && echo reloaded curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=prometheus_config_last_reload_successful' | jq -r '.data.result[0].value[1]' # simulate Prometheus's request headers and check the Content-Type the target returns curl -s -o /dev/null -D - 127.0.0.1:5000/metrics \ -H 'Accept: application/openmetrics-text;version=1.0.0;escaping=allow-utf-8;q=0.7,text/plain;version=0.0.4;q=0.4,*/*;q=0.3' \ -H 'X-Prometheus-Scrape-Timeout-Seconds: 10' | grep -i content-type
reloaded 1 Content-Type: text/plain; version=1.0.0; charset=utf-8
How to verify: after reload, prometheus_config_last_reload_successful must be 1; if it is 0, Prometheus is still using the old configuration, and the log gives the reason. Common errors: assuming that a successful reload means the change is live; you must also check whether the new target appears on the Targets page. Production use: Set prometheus_config_last_reload_successful == 0 an alert on (Lesson 2).
Query from the command line with promtool
docker compose exec prometheus promtool query instant http://localhost:9090 'scrape_samples_post_metric_relabeling'
scrape_samples_post_metric_relabeling{env="lab", instance="myapp:5000", job="myapp", service="myapp"} => 92 @[1794737012.42]
scrape_samples_post_metric_relabeling{env="lab", instance="node-exporter:9100", job="node"} => 1093 @[1794737012.42]
...
Lab 3: relabel and metric_relabel (about 7 min)
This lab modifies prometheus/prometheus.yml; the configuration at the end of the lab is the starting point for Lesson 2.
scrape_samples_post_metric_relabeling{job="node"}
count({job="node", __name__=~"node_scrape_collector_.*"})
1093 96
host relabel_configs), and in the node job drop the collector's own meta-metrics (metric_relabel_configs). Change the myapp and node two jobs to:
- job_name: node
static_configs:
- targets: ["node-exporter:9100"]
labels:
env: lab
metric_relabel_configs:
- source_labels: [__name__]
regex: "node_scrape_collector_.*"
action: drop
- job_name: myapp
static_configs:
- targets: ["myapp:5000"]
labels:
env: lab
service: myapp
relabel_configs:
- source_labels: [__address__]
regex: "([^:]+):\\d+"
target_label: host
replacement: "${1}"
In a YAML double-quoted string, \\d represents the regex \d. replace is the default action; the regex is fully anchored.
docker run --rm -v "$PWD/prometheus:/etc/prometheus:ro" --entrypoint promtool prom/prometheus:v3.16.0 check config /etc/prometheus/prometheus.yml
curl -s -X POST 127.0.0.1:9090/-/reload
sleep 20
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=up{job="myapp"}' | jq -c '.data.result[0].metric'
{"__name__":"up","env":"lab","host":"myapp","instance":"myapp:5000","job":"myapp","service":"myapp"}scrape_samples_scraped{job="node"}
scrape_samples_post_metric_relabeling{job="node"}
1093 997
The number of scraped samples is unchanged (the exporter still outputs them and Prometheus still parses them), but the number stored drops by 96. The old node_scrape_collector_* series receive a staleness marker at the next scrape, so queries return empty immediately.
scrape_configs add
- job_name: relabel-demo
static_configs:
- targets: ["myapp:5000", "redis-exporter:9121"]
relabel_configs:
- source_labels: [__address__]
regex: "myapp:.*"
action: keep
curl -s -X POST 127.0.0.1:9090/-/reload; sleep 5 curl -s '127.0.0.1:9090/api/v1/targets?state=dropped' | jq -r '.data.droppedTargets[].discoveredLabels.__address__'
redis-exporter:9121
After confirming,delete the relabel-demo job and reload again to keep the configuration clean (Lesson 2 starts from here).
INFO:
curl -s 127.0.0.1:9121/metrics | grep -E '^redis_(up|connected_clients|commands_processed_total|db_keys)'
redis_commands_processed_total 48211
redis_connected_clients 3
redis_db_keys{db="db0"} 1
redis_up 1Case 1: use metric_relabel as a stopgap, then fix at the source
Problem: After upgrading, an exporter added a le histogram with fine-grained buckets, and the samples per target grew from 2k to 40k. Approach: That night, first add metric_relabel_configs using drop to remove these _bucket series and set sample_limit: 10000; the next day, disable the corresponding collector on the exporter side to truly reduce scraping overhead. Limitation:sample_limit Exceeding the limit makes the whole scrape fail (up=0); always combine it with scrape_samples_scraped an alert with some headroom.
Case 2: label overwriting caused by honor_labels
Problem: The team set honor_labels: true on all jobs, and one application itself output instance="localhost", so the series of 10 replicas were merged into one and overwrote each other's data. Approach: Enable it only on the federation and Pushgateway jobs; honor_labels; normal jobs keep the default false, and conflicting labels become exported_instance.
Case 3: counts "jumping back and forth" with gunicorn multiple workers
Problem: A Flask service with 4 workers exposed metrics using the default registry,rate() producing many spikes. The cause: each scrape landed on a different worker, so the counters went up and down, and Prometheus treated the drops as resets. Approach: enable multi-process mode (the approach myapp uses in this lesson). Limitation: loses process_* the 'process' metrics; if needed, use separate node / cAdvisor metrics, or in Kubernetes use the container metrics from kubelet / cAdvisor instead.
Common errors and fixes
Get "http://myapp:5000/metrics": dial tcp 172.18.0.6:5000: connect: connection refused
Cause: DNS resolves, but nothing is listening on the port: the application has not finished starting, it is listening on 127.0.0.1, or the port is wrong.
docker compose exec prometheus wget -qO- -T 3 http://myapp:5000/metrics | head -3 docker compose logs --tail=20 myapp
Fix: have the application listen on 0.0.0.0 (gunicorn bind = "0.0.0.0:5000"); verify the port.
Get "http://myapp:5000/metrics": context deadline exceeded
Cause: the response exceeds scrape_timeout (10s). Common when the exporter synchronously queries a slow database, or all application workers are occupied by slow requests.
scrape_duration_seconds{job="myapp"}
Fix: Find the cause of the slowness (disable expensive collectors, add workers to the application, or move /metrics to a separate port or thread); do not blindly increase the timeout, since it must be ≤ the scrape interval.
received unsupported Content-Type "text/html; charset=utf-8" and no fallback_scrape_protocol specified for target
Cause: Prometheus 3 no longer parses an unrecognized Content-Type as the text format. metrics_path The wrong page is being scraped (it returns HTML), or the application framework's /metrics does not set the correct Content-Type.
curl -sI 127.0.0.1:5000/metrics | grep -i content-type
Fix: Make the target return text/plain; version=0.0.4/1.0.0 or OpenMetrics; if the target cannot be changed, set fallback_scrape_protocol: PrometheusText0.0.4 in the job.
The new job does not appear after reload; log: error loading config ... yaml: unmarshal errors
Cause: YAML indentation error; when a reload fails, Prometheus keeps using the old configuration and does not exit.
docker compose logs prometheus 2>&1 | grep -i "error loading config" | tail -1
Fix: Validate with promtool before reloading; alert on prometheus_config_last_reload_successful == 0.
exported_job / exported_instance appears in target labels
Cause: the target itself outputs job/instance a label that conflicts with the one Prometheus attaches,honor_labels: false so the target's own label is renamed.
Fix: Applications should not output these two reserved labels; use honor_labels: true only when the source labels must be kept (federation, Pushgateway).
1. Write a relabel rule that keeps only targets that have env="lab" the target label.
relabel_configs:
- source_labels: [env]
regex: lab
action: keep2. Use one PromQL query to find targets where the number stored is less than the number scraped (i.e., metric_relabel is dropping data).
scrape_samples_scraped - scrape_samples_post_metric_relabeling > 0
A newly launched service shows UP on the Targets page, but Grafana cannot find its business metrics orders_created_total. List the troubleshooting order.
① curl ① Check the target's /metrics"/metrics" output to confirm the metrics are really being produced (multi-process mode? has a request triggered the labeled metric yet?); ② compare scrape_samples_scraped and scrape_samples_post_metric_relabeling to see whether metric_relabel dropped them; ③ query directly in Prometheus {__name__=~"orders.*"} to see whether the name was rewritten or has different labels (exported_job?); ④ check the label filters and variables in the Grafana query (job whether the names match); ⑤ if sample_limit is used, confirm it has not been exceeded.
Verified teaching videos
No verified videos dedicated to "the two relabel stages" or "client_python multi-process mode" were found; please use the storyboard script below.
Official documentation
- scrape_config
- relabel_config
- Jobs and instances (automatically generated labels and metrics)
- Exporters and integrations
- node_exporter README
- redis_exporter README
Video storyboard script (about 100 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.
Visual: service discovery spits out a card listing __address__ and a string of __meta_ labels; the card passes through a "rewriter" labeled relabel, some labels are changed, and some cards are dropped into the recycle bin.
Narration: each target first goes through relabel, which decides its final labels and also whether to scrape it at all.
Visual: on a clock face with 15-second ticks, the scrape points of dozens of targets are spread evenly around the circle; an HTTP request expands to show the Accept and timeout headers.
Narration: each target has its own scrape loop, with the offset determined by a label hash; the request tells the target how many seconds remain before the timeout.
Visual: the returned text lines are parsed into samples, pass through a second rewriter, get job and instance labels, are written into the in-memory block, and are appended to the WAL tape at the same time.
Narration: parsing, sample-level relabel, attaching target labels, then committing everything to the head and the WAL in one go.
Visual: the up, scrape_duration_seconds and other synthetic metrics appear automatically; a curve is marked "stale" at one point and then breaks off immediately.
Narration: every scrape writes synthetic metrics; series that disappear are written a staleness marker, so the graph breaks at once instead of pretending they are still alive.
Module 4 · PromQL basics: selectors, rate and aggregation
- Distinguish PromQL's four value types (instant vector, range vector, scalar, string) and understand how instant queries and range queries (
start/end/step) relate. - Skilfully use label matchers
=,!=,=~,!~(regexes fully anchored),offset,@, and understand the 5-minute lookback and staleness markers. - Be able to hand-calculate
rate(): samples within the window, counter reset compensation, extrapolation to the window boundaries (a 1.1× average-interval threshold; otherwise extrapolate only half an interval), and no extrapolation below zero; know the difference betweenincreaseandirate. - Use the aggregation operators
sum/avg/max/count/topkplusby/withoutto write QPS, error rate and Top-N queries, following "rate first, then sum".
What: the four types of expressions
| Type | Example | Meaning | Can it be plotted directly? |
|---|---|---|---|
| Instant vector instant vector | myapp_http_requests_total{route="/"} | one value per matching series at the evaluation time a single value (looking back at most 5 minutes) | ✓ |
| Range vector range vector | myapp_http_requests_total[5m] | for each series, over (t-5m, t] the all samples | ✗ (must be passed to rate and similar functions) |
| Scalar | 0.95,scalar(...),time() | a single floating-point number | ✓ |
| String | "hello" | currently only used as an argument to some functions | ✗ |
Instant query (/api/v1/query?time=t) evaluates an expression at one point in time; Range query (/api/v1/query_range?start&end&step) evaluates the instant query at every step between start and end. Grafana's time series graphs are range queries, and each point on the graph is a separate calculation.
Selectors and modifiers
{job="myapp", status=~"5.."}: regex fully anchored,"5.."is equivalent to^5..$.{route!~"/healthz|/metrics"}Exclude multiple values.- At least one matcher must not match the empty string:
{job=~".*"}is illegal,{job=~".+"}is legal. - lookback: an instant vector takes "the latest sample within 5 minutes before the evaluation time" (
--query.lookback-delta); if the series has been written a staleness marker, it is treated as absent immediately. offset 1h: look back 1 hour as a whole (for year-over-year comparisons);@ 1794736800or@ end(): pin the evaluation time to a specific moment.- In 3.x, range selectors are open on the left, closed on the right:
[5m]select(t-5m, t].
How: the real algorithm of rate() (source extrapolatedRate)
- take the window
(t-range, t](the samples of that series within it); if there are fewer than 2, output nothing (no result, not 0). result = last value − first value; then iterate over adjacent samples; whenever a sample is smaller than the previous one (a counter reset), add the previous value back (assuming the counter restarts from 0 after a reset).sampledInterval = last timestamp − first timestamp;avg = sampledInterval / (number of samples − 1);threshold = 1.1 × avg.durationToStart = first sample time − window start,durationToEnd = window end − last sample time. If the distance on one side ≥ threshold, the series is considered to have started or ended within the window, and that side is extrapolated only byavg / 2; otherwise extrapolate to the boundary.- A counter is not extrapolated below zero: if
result > 0and the first value is ≥ 0, computedurationToZero = sampledInterval × (first value / result); if it is smaller thandurationToStart, use it (the case of a new series starting from 0). increase = result × (sampledInterval + durationToStart + durationToEnd) / sampledInterval;rate = increase / range in seconds.
So increase() returns decimals even for integer counters; this is not a bug. irate() Uses only the last two samples within the window (resets are handled the same way); it reacts quickly but is jittery, so it suits only high-resolution views of instantaneous change, not alerting. The window must contain at least 2 samples; a rule of thumb is ≥ 4 × scrape interval (with a 15s scrape interval, start with [1m] ; this lesson mostly uses [5m]).
Aggregation: rate first, then sum
sum by (route) (rate(myapp_http_requests_total[5m])) ✓ each series computes its rate first (handling resets individually), then the results are added rate(sum by (route) (myapp_http_requests_total)[5m:]) ✗ summing first turns one instance's reset into a "drop in the total", which is then treated as an overall reset
| Operator | Example | Description |
|---|---|---|
sum by (l) / sum without (l) | sum by (status) (rate(...[5m])) | by keeps the listed labels; without removes the listed labels and keeps the rest (more robust to newly added labels) |
avg,min,max,count | count by (job) (up == 1) | count count the number of series |
topk(k, …),bottomk | topk(3, sum by (route) (rate(...[5m]))) | in a range query, Top-k is chosen independently at each step, so the graph may show more than k lines |
quantile(φ, …) | quantile across series | is not histogram_quantile |
| Comparison / filtering | up == 0,... > 0.05 | by default is filtering: series that do not satisfy the condition are dropped; adding bool turns it into 0/1 |
When: the new anchored / smoothed modifiers
Introduced in Prometheus 3.7,stable in 3.16: increase(x[5m] anchored) takes the latest sample before the window start as the starting point, with no extrapolation; the result for float counters is an integer, which suits reconciliation-style questions like "how many requests were added in these 5 minutes exactly"; rate(x[5m] smoothed) interpolates linearly at the boundaries, but requires the evaluation time after samples, so using it in a rule requires the rule group's query_offset. This lesson uses the classic rate() by default, because Grafana, managed services and many existing rules are all based on it.
or vector(0)). ④ "rate can be used on gauges" — it treats drops as resets. ⑤ "a smaller [1m] " is more precise" — if the window contains fewer than 2 samples, there is simply no data.Instant vector vs range vector
rate() extrapolation diagram
Core animation B: rate() calculator (step by step, following the source algorithm)
Evaluation time t = 120s, scrape interval 15s, sample times 3, 18, 33 … 108s. Choose a scenario and window; below, each intermediate value is given line by line extrapolatedRate for irate() and compares it with
Common queries (run in the Prometheus UI or API)
| Purpose | PromQL |
|---|---|
| myapp total QPS | sum(rate(myapp_http_requests_total{job="myapp"}[5m])) |
| QPS by route | sum by (route) (rate(myapp_http_requests_total[5m])) |
| 5xx error rate | sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m])) |
| requests in the past 1 hour | sum(increase(myapp_http_requests_total[1h])) |
| average latency | sum(rate(myapp_http_request_duration_seconds_sum[5m])) / sum(rate(myapp_http_request_duration_seconds_count[5m])) |
| CPU utilization | 1 - avg without (cpu, mode) (rate(node_cpu_seconds_total{mode="idle"}[5m])) |
| Top 3 Redis commands | topk(3, rate(redis_commands_total[5m])) |
| compare with 1 hour ago | sum(rate(myapp_http_requests_total[5m])) / sum(rate(myapp_http_requests_total[5m] offset 1h)) |
# instant query curl -s 127.0.0.1:9090/api/v1/query \ --data-urlencode 'query=sum by (route) (rate(myapp_http_requests_total[5m]))' \ | jq -r '.data.result[] | "\(.metric.route)\t\(.value[1])"' # range query: last 10 minutes, one point every 60 seconds curl -s 127.0.0.1:9090/api/v1/query_range \ --data-urlencode 'query=sum(rate(myapp_http_requests_total[5m]))' \ --data-urlencode "start=$(date -d '-10 min' +%s)" --data-urlencode "end=$(date +%s)" --data-urlencode 'step=60' \ | jq -c '.data.result[0].values[:3]'
/ 4.38 /slow 0.47 /error 0.24 /healthz 0.0667 [[1794736440,"5.1"],[1794736500,"5.13"],[1794736560,"5.08"]]
How to verify: loadgen sends one request about every 0.2 seconds / request (plus curl's own overhead, about 4–5 req/s), which matches the result; /healthz comes from the Docker HEALTHCHECK, once every 15 seconds = 0.0667. Common errors: The API returns values as strings; timestamps are in seconds (floating point). Production use: Scripted release acceptance (for example, the error rate must be < 1% after release).
Assertions with promtool
docker compose exec prometheus promtool query instant http://localhost:9090 \
'sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m]))'
{} => 0.0464 @[1794737040.11]
Lab 4: verify rate's reset compensation and extrapolation yourself (about 6 min)
myapp_http_requests_total{route="/error"}[1m]
myapp_http_requests_total{env="lab", host="myapp", instance="myapp:5000", job="myapp", method="GET", route="/error", service="myapp", status="500"}
231 @1794737013.517
234 @1794737028.517
238 @1794737043.517
241 @1794737058.517
The 4 samples are exactly 15 seconds apart (the scrape times of the same target are fixed). Hand calculation: Δ = 10, sampledInterval = 45s; then check the distances from the evaluation time to both ends to get increase(...[1m]).
docker compose restart myapp sleep 45
myapp_http_requests_total{route="/"}
rate(myapp_http_requests_total{route="/"}[2m])
resets(myapp_http_requests_total{route="/"}[5m])
Raw value: drops from thousands to tens rate: stays around 4–5, with no negative values or cliffs (the reset is compensated) resets: 1
sum(rate(myapp_http_requests_total[5m])) sum(irate(myapp_http_requests_total[5m])) sum(increase(myapp_http_requests_total[5m])) / 300
the first and third lines coincide (increase = rate × window seconds); irate is clearly jumpier.
rate(myapp_http_requests_total{route="/"}[20s])
sometimes there is a value and sometimes it is empty: a 20-second window sometimes contains only 1 sample. This is why the window should be ≥ 4 × the scrape interval, and it is also why Grafana provides $__rate_interval (Module 6).
sum without (instance, host, env, service) (rate(myapp_http_requests_total[5m])) sum by (route) (rate(myapp_http_requests_total[5m])) > 0.3 sum by (route) (rate(myapp_http_requests_total[5m])) > bool 0.3
the second query returns only routes above 0.3; the third returns all routes, with values of 0 or 1.
Case 1: a false spike caused by sum followed by rate
Problem: The dashboard was written as rate(sum(http_requests_total)[5m:]) (a subquery), and a huge spike appeared on every rolling release. The cause: a Pod restart made the "total" drop, rate treated that as an overall reset and added the whole total back. Approach: Changed to sum(rate(http_requests_total[5m])). Configuration: Recording rules also follow "rate first, then sum" (the Lesson 2 naming convention job:myapp_http_requests:rate5m).
Case 2: error-rate alerts jump around at low traffic
Problem: At night there are only 3 requests per minute, so one failure means a 33% error rate, and the alert fires repeatedly all night. Approach: Require a minimum traffic level in the alert condition as well and sum(rate(...[5m])) > 0.5, or use a longer window; for the SLO burn rate method, see Lesson 6.
Case 3: decimals appear when increase is used for billing reconciliation
Problem: The finance report uses increase(orders_total[1d]) and gets 10234.7 orders. Approach: After explaining the extrapolation mechanics, switch reconciliation to the business database; keep using Prometheus for monitoring. If you only need the "real increment within the window" and the version is ≥ 3.16, you can use increase(orders_total[1d] anchored), but it is still affected by sample retention and scrape failures and cannot replace the ledger.
Common errors and fixes
Error executing query: invalid parameter "query": 1:1: parse error: ranges only allowed for vector selectors
Cause: used [5m] on something that is not a selector, such as sum(x)[5m].
Fix: Move the function outside: sum(rate(x[5m])); when you really need a range over an expression, use a subquery (expr)[30m:1m] (Module 5).
many-to-many matching not allowed: matching labels must be unique on one side
Cause: A binary operation has one-to-many or many-to-many matches when matching labels on both sides (for example, one side of a division is aggregated by route and the other is not).
Fix: Use the same by aggregation on both sides, or use on()/ignoring(),group_left (Module 5).
parse error: vector selector must contain at least one non-empty matcher
Cause: Wrote {job=~".*"} a selector like this that can match an empty string.
Fix: Change it to {job=~".+"} or add a metric name.
The error-rate query returns empty (Empty query result), even though the service is clearly healthy
Cause: there has never been a 5xx, so the numerator has no series; an empty vector divided by anything is still empty.
(sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) or vector(0)) / sum(rate(myapp_http_requests_total[5m]))
Fix: Use or vector(0) to fill in 0; in alerting scenarios, empty usually means "not triggered", so no filling is needed.
1. Write a query for the average latency (in milliseconds) of each route over the past 5 minutes.
1000 * sum by (route) (rate(myapp_http_request_duration_seconds_sum[5m]))
/ sum by (route) (rate(myapp_http_request_duration_seconds_count[5m]))2. Hand calculation: window [1m], evaluation time t=120s, samples (63s, 100) (78s, 130) (93s, 10) (108s, 40). What is the increase?
Δ = 40 − 100 = −60; a reset occurs at 93s, so add back 130 → result = 70. sampledInterval = 45, avg = 15, threshold 16.5; durationToStart = 63 − 60 = 3, durationToEnd = 120 − 108 = 12, both < 16.5, so extrapolate to both ends; zero-point check: 45 × 100/70 ≈ 64.3 > 3, which does not affect the result. increase = 70 × 60/45 ≈ 93.3, rate ≈ 1.556/s.
A colleague says: "On Grafana, QPS often breaks off with a 1-minute window, while the 5-minute window is smooth, but alerts on the 5-minute window react too slowly." Explain the cause and propose a solution.
With a 15s scrape interval, a 1-minute window has only about 4 samples; when a scrape is occasionally missed or alignment is off, fewer than 2 samples means no result, which creates the gaps. The 5-minute window is smooth but lags. Solution: for charts, use Grafana's $__rate_interval (which guarantees at least 4 scrape intervals); for alerts, use a 2–5 minute window combined with for, or precompute both 1m and 5m rates with recording rules; for SLO scenarios, use multi-window burn rates (Lesson 6). Do not use irate for alerting.
Verified teaching videos
No verified video was found that specifically explains rate() the extrapolation algorithm; this module's calculator and storyboard are based on the Prometheus v3.16.0 source code promql/functions.go.
Official documentation
- Querying basics (types, selectors, lookback, anchored / smoothed)
- rate / increase / irate
- Operators (aggregation and vector matching)
- Source code promql/functions.go (extrapolatedRate)
Video storyboard script (about 100 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.
Visual: on the timeline, a semi-transparent 1-minute window containing 4 sample points; the left boundary of the window is an open bracket and the right boundary is a closed bracket.
Narration: rate first takes the samples in the window; the window is open on the left and closed on the right; with fewer than two samples there is no result.
Visual: the third point suddenly drops to the bottom, a "+130" compensation bubble pops up beside it, and the curve is reconnected.
Narration: if a value is smaller than the previous one, the counter is considered reset, and the previous value is added back.
Visual: the first and last points extend with dashed lines toward the window boundaries; one side is labeled 3 seconds and the other 12 seconds, compared against the 16.5-second threshold; in the new-series scenario, the left dashed line extends only half an interval and is cut off at zero.
Narration: if a point is close enough to the boundary, extrapolate to the boundary; if it is too far, extrapolate only half an interval; and a counter is never extrapolated below zero.
Visual: the formula increase equals the increase multiplied by the ratio, and dividing by 60 gives the per-second rate; beside it, irate connects only the last two points, and the curve jitters.
Narration: so increase can produce decimals. Use rate for trends, irate for instantaneous values, and never irate for alerts.
Module 5 · PromQL advanced: histogram_quantile, joins and subqueries
- Write correct P95 / P99 queries:
histogram_quantile(0.95, sum by (le) (rate(..._bucket[5m]))), and explain linear interpolation within buckets,+Infand the boundary rules for the +Inf bucket and the lowest bucket. - Master vector matching for binary operations: one-to-one,
on()/ignoring(),group_left/group_right(many-to-one), and set operationsand/or/unless. - Know how to use
absent(),predict_linear(),label_replace(),*_over_time()and subqueriesexpr[range:resolution], and know the cost of subqueries.
What: how histogram_quantile estimates quantiles
- The input is a set of series that carry the
lelabel, grouped by the other labels (usually already processed withraterate, meaning "the number of requests per second falling into each bucket over the last 5 minutes"). - Total =
le="+Inf"the value of the bucket; target rankrank = φ × total. - Find the first bucket whose cumulative value ≥ rank
(lower, upper]; within the bucket,interpolate linearly:lower + (upper − lower) × (rank − cumulative value of previous bucket) / (cumulative value of this bucket − cumulative value of previous bucket). - Boundary rules: when the result falls in the lowest bucket and its upper bound is > 0, the lower bound is treated as 0; when it falls in
+Infthe +Inf bucket, it returns the upper bound of the second-highest bucket (so if P99 is always exactly 5, it means "at least 1% exceed 5 seconds, and it is unknown how many"). - With fewer than 2 buckets, or no
+Infbuckets, it returns NaN; for native histograms, pass the histogram series directly, with no need forle.
histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket[5m]))) ✓ global P95 histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m]))) ✓ P95 per route histogram_quantile(0.95, sum by (route) (rate(myapp_http_request_duration_seconds_bucket[5m]))) ✗ le was aggregated away, so there are no buckets to interpolate histogram_quantile(0.95, rate(myapp_http_request_duration_seconds_bucket[5m])) △ P95 for each instance separately (many lines when there are multiple instances) avg(histogram_quantile(0.95, …)) ✗ quantiles cannot be averaged
What: binary operations and vector matching (PromQL's "join")
| Matching method | Syntax | Rule | Typical use |
|---|---|---|---|
| One-to-one (default) | a / b | the label sets on both sides are exactly the same series are paired; those that do not match are dropped | Error rate: use the same sum by |
| restrict matching labels | a / on(route) b,a / ignoring(status) b | pair only by the listed labels (or ignoring the listed labels) | the numerator has one more status label than the denominator |
| Many-to-one | a * on(instance) group_left(nodename) b | many series on the left match one on the right; the labels listed from the right are copied to the result | Use *_info an info metric to "add" metadata labels to the result |
| Set | a and b,a or b,a unless b | intersection / union / difference by label sets, with values taken from the left side | "look at the error rate only when traffic > threshold", filling in default values |
info metric pattern: the value is always 1 and the labels carry metadata (such as node_uname_info{nodename,release},redis_instance_info{redis_version}, and Kubernetes' kube_pod_info). Multiplying by it does not change the value, it only adds labels. Prometheus 3 also has an experimental info() function that simplifies this pattern (requires a feature flag); this lesson uses the general group_left.
How: commonly used advanced functions
| Function | Example | Description |
|---|---|---|
absent(v) / absent_over_time(v[d]) | absent(up{job="myapp"}) | returns 1 when there are no series: detects "metric disappeared / target gone from service discovery" |
predict_linear(v[d], t) | predict_linear(node_filesystem_avail_bytes[6h], 4*3600) < 0 | linear regression predicts the value t seconds ahead (gauge) |
*_over_time | max_over_time(myapp_redis_up[10m]) | takes avg / min / max / last / quantile etc. of a gauge within a time window |
label_replace | label_replace(up, "host", "$1", "instance", "([^:]+):.*") | with labels derived at query time (regexes are likewise fully anchored) |
| Subquery | max_over_time(sum(rate(x[5m]))[1h:1m]) | evaluates an instant expression every 1m over the past 1h to produce a range vector; cost = inner query × number of points |
clamp_min/max,round | clamp_max(x, 1) | trimmed for display |
histogram_count/sum/fraction | histogram_fraction(0, 0.25, …) | used for native histograms (3.x); for classic histograms use _bucket{le="0.25"} / _count |
When: when to use subqueries and when to use recording rules
Subqueries suit ad hoc analysis ("what was the peak 5-minute QPS over the past day?"). If the same subquery appears in a dashboard or alert and is executed repeatedly, switch to a recording rule to precompute it rate(...[5m]), and then run max_over_time on the recorded results (Lesson 2).
a / b automatically aligns on labels other than the name" — all labels must match, otherwise you silently get an empty result. ④ "group_left changes the value" — multiplying by an info metric (value 1) leaves it unchanged; multiplying by an ordinary metric is real multiplication.The interpolation process of histogram_quantile
group_left: add labels to the result
Interaction: drag φ and watch how histogram_quantile selects the bucket and interpolates
Bucket data comes from myapp /slow route's typical distribution (per-second counts after rate). Switch to "requests get slower" to see the capping behaviour when the quantile falls in the +Inf bucket.
Advanced query checklist
| Purpose | PromQL |
|---|---|
| P95 per route | histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m]))) |
| proportion of requests completed within 250ms (SLI) | sum(rate(myapp_http_request_duration_seconds_bucket{le="0.25"}[5m])) / sum(rate(myapp_http_request_duration_seconds_count[5m])) |
| error rate by route (the numerator has one extra status label) | sum by (route) (rate(myapp_http_requests_total{status=~"5.."}[5m])) / ignoring(status) sum by (route) (rate(myapp_http_requests_total[5m]))On both sides, by (route) they are actually already aligned,ignoring syntax for when the data is not aggregated |
| CPU utilization with hostname | (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))) * on(instance) group_left(nodename) node_uname_info |
| attach the Redis version to redis_up | redis_up * on(instance) group_left(redis_version) redis_instance_info |
| whether the myapp target has disappeared | absent(up{job="myapp"}) |
| whether the disk will be full in 4 hours | predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0 |
| peak QPS over the past 1 hour | max_over_time(sum(rate(myapp_http_requests_total[5m]))[1h:1m]) |
| whether Redis has dropped out at any point in the past 10 minutes | min_over_time(myapp_redis_up[10m]) == 0 |
q='histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m])))' curl -s 127.0.0.1:9090/api/v1/query --data-urlencode "query=$q" | jq -r '.data.result[] | "\(.metric.route)\t\(.value[1])"'
/ 0.00475 /error 0.00475 /healthz 0.0095 /slow 2.31
How to verify:/slow The true distribution is uniform over 0.2–1.5 seconds, so the theoretical P95 = 0.2 + 0.95 × 1.3 ≈ 1.435 seconds. But about 61.5% of requests are ≤ 1 second, so rank 0.95 falls in the (1, 2.5] bucket. Interpolation assumes requests are uniformly distributed over 1–2.5 seconds, giving 1 + 1.5 × (0.95 − 0.615) / (1 − 0.615) ≈ 2.3 seconds—overestimating by 60%, because the real requests are only spread across the 1–1.5 second part of this bucket. This is a live example of "bucket boundaries determine precision"; / the P95 of 0.00475 is the result of interpolating within the (0, 0.005] bucket. The real value could be 1 ms or 4 ms; the buckets are too coarse to tell. Common errors: when a PromQL string contains double quotes in the shell, wrap the variable assignment in single quotes.
Diagnosing vector matching failures
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=redis_up' | jq -c '.data.result[].metric'
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=redis_instance_info' | jq -c '.data.result[].metric | {instance, job, redis_version}'
Before the join, print the labels on both sides and compare them, to confirm that the labels in on() exist on both sides with the same values.
Lab 5: P95, SLI and joined queries (about 6 min)
for i in $(seq 1 60); do curl -s -o /dev/null 127.0.0.1:5000/slow & done; wait
gunicorn has only 2 synchronous workers, so 60 concurrent slow requests will queue,and the latency of other routes will also rise; this gives you an intuitive feel for "saturation".
histogram_quantile(0.5, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[1m])))
histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[1m])))
histogram_quantile(0.99, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[1m])))
during the peak, the P99 of / jumps from milliseconds to seconds (requests wait in the gunicorn queue), while P50 changes little.
sum(rate(myapp_http_request_duration_seconds_bucket{le="0.25"}[5m]))
/ sum(rate(myapp_http_request_duration_seconds_count[5m]))
0.8813
redis_up * on(instance) group_left(redis_version) redis_instance_info count by (release) (node_uname_info)
{env="lab", instance="redis-exporter:9121", job="redis", redis_version="7.4.x"} 1
{release="6.8.0-xx-generic"} 1max_over_time(sum(rate(myapp_http_requests_total[1m]))[30m:15s])
Open the UI's "Explain" view (the tree icon next to the query box in the new 3.x UI) to inspect the execution structure of the subquery.
docker compose stop myapp; sleep 20
up{job="myapp"}
absent(myapp_http_requests_total{job="myapp"})
up is 0 (the target is still in the configuration), the business metrics disappear after being marked stale,absent returns 1. Then docker compose start myapp recovers.
Case 1: P99 stuck at 10 seconds
Problem: The P99 graph of one service was a flat line at 10 for two days, and everyone assumed "the slowest request takes 10 seconds". Approach: Check _bucket{le="+Inf"} - _bucket{le="10"} 3% of requests exceed 10 seconds (the highest bucket), so the true tail latency is unknown. Add 30- and 60-second buckets on the client, or switch to native histograms (for Go services). Limitation: Changing buckets creates new series, and old data cannot be recalculated.
Case 2: data "disappears" after a join
Problem:... * on(pod) group_left(team) kube_pod_labels Some Pods return no results. The cause is that these Pods have no team label, so kube_pod_labels the corresponding series is missing in the join; the two sides of the multiplication cannot match, so the series are dropped. Approach: Use or to fill in a default value, or first label_replace generate a fallback label; in CI, check that the required Pod labels are present.
Case 3: a dashboard overwhelmed by a subquery
Problem: A "30-day peak QPS per service" panel used max_over_time(...[30d:1m]), and each refresh evaluated the inner query 43,200 times, causing Prometheus CPU to spike. Approach: Add a recording rule service:requests:rate5m, and change the panel to run max_over_time(service:requests:rate5m[30d]) on the recording rule's results; also set a longer refresh interval for the dashboard.
Common errors and fixes
histogram_quantile returns NaN
Cause: there are no observations in the window (the rate of every bucket is 0, so 0/0); or the aggregation dropped le; or only some buckets were selected (for example, le=~"0.1|0.5" has no +Inf).
sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/slow"}[5m]))
Fix: Confirm the bucket series are complete and have traffic; for low-traffic services use a longer window.
found duplicate series for the match group {instance="…"} on the right hand-side of the operation
Cause:group_left The "one" side of on() label is not unique (for example, the same instance has two info series, possibly from a brief overlap around a version switch).
Fix: Aggregate and de-duplicate on the right side first: ... * on(instance) group_left(redis_version) max by (instance, redis_version) (redis_instance_info); or fill in the missing on() label.
A binary operation returns empty, but each side returns data when queried separately
Cause: the label sets are inconsistent (one side has an extra status,le,host and so on).
Fix: Use the same sum by (...), or use on()/ignoring().
query processing would load too many samples into memory in query execution
Cause: a subquery over a large time range or a high-cardinality selector exceeded --query.max-samples (default 50 million).
Fix: Narrow the range, increase the subquery step, or switch to recording rules; do not simply raise the limit.
1. Write a query for the share of requests longer than 1 second for each route.
1 - (
sum by (route) (rate(myapp_http_request_duration_seconds_bucket{le="1.0"}[5m]))
/ sum by (route) (rate(myapp_http_request_duration_seconds_count[5m]))
)Note that the le value output by prometheus_client is "1.0" (floating-point format), so writing le="1" will not match.
2. Find how many times myapp was restarted in the past 24 hours.
resets(myapp_http_requests_total{route="/healthz", status="200"}[24h])HEALTHCHECK hits /healthz every 15 seconds, so this series almost always grows, which makes it suitable as a restart detector.
The product manager wants "P99 latency < 300ms" as an SLO, but myapp's buckets are 0.25 and 0.5. What is wrong with using histogram_quantile(0.99) directly to decide whether the target is met? How should it be improved?
0.3 is not on a bucket boundary, so the P99 is interpolated within the (0.25, 0.5] bucket. The result depends on the uniform-distribution assumption, so it can wrongly indicate that the target is met or missed. Improvements: ① rewrite the SLO as "99% of requests complete within X", and make X equal a bucket boundary (0.25, or add a 0.3 bucket in the code); ② judge by the proportion SLI bucket{le="0.3"} / count ≥ 0.99, which is exact at a bucket boundary; ③ in languages that support it, such as Go, consider native histograms.
Verified teaching videos
No verified videos on histogram_quantile interpolation or group_left were found; please use the storyboard script below.
Official documentation
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.
Visual: a row of cumulative bucket bars; a horizontal line marks rank = 0.9 × total and intersects one bar; that bar is enlarged, and the balls inside it are spread evenly.
Narration: histogram_quantile first computes the rank, finds the bucket the rank falls into, and then assumes an even distribution within the bucket to interpolate linearly.
Visual: the rank line rises to the +Inf bar, and the result shows the upper bound of the highest finite bucket with a flashing warning.
Narration: when a value falls into the +Inf bucket, only the highest finite boundary can be returned. Be careful when P99 always equals the same integer.
Visual: on the left are several CPU series; on the right is one info series with a nodename label; an on(instance) zipper joins the two sides, and the result card gains a nodename label.
Narration: a PromQL join is a binary operation with matching rules. on decides what to pair on, and group_left brings the labels over from the right.
Module 6 · Grafana architecture: data sources, dashboards and panels
- Draw Grafana's components: the Go backend (HTTP API, data source plugins, alerting engine), the database (SQLite by default) and the React frontend; explain what it stores and what it does not store.
- Describe the full path of a panel query: browser →
/api/ds/query→ Prometheus data source plugin →/api/v1/query_range(start, end, step) → data frames → transformations → rendering. - Calculate
$__intervaland$__rate_interval, and explain why rate queries should use the latter, and what the data source's "Scrape interval" setting does. - Manage data sources and dashboards with file provisioning, and understand the main changes in Grafana 13 (dynamic dashboards and Git Sync GA, image name changes).
What: what Grafana is and what it stores
| Component | Responsibility | Location in this lab |
|---|---|---|
| Frontend (React single-page application) | Dashboard editing, panel rendering, Explore, variable UI | Browser |
| Backend (Go) | HTTP API, authentication and permissions,data source proxy and backend plugins, alerting engine, rendering service calls, provisioning | Container grafana |
| Database | users, organizations, teams, folders, dashboard JSON, data source configuration, alert rules, preferences | SQLite: /var/lib/grafana/grafana.db (production can use MySQL / PostgreSQL with HA) |
| Data sources (plugins) | translate panel queries into API calls for the target system | Prometheus (built-in plugin); there are also Loki, Tempo, Azure Monitor, CloudWatch, SQL and more |
Grafana does not store metric data. Deleting Grafana does not lose any Prometheus data; conversely, once Prometheus data expires, Grafana cannot query it either.
How: the path of a panel query
- The frontend calculates from the time range and the panel width to derive
maxDataPoints(default ≈ the panel's width in pixels) and$__interval= time range / maxDataPoints, then rounds to a "nice" value, and it is not less than the data source's Scrape interval (the timeInterval set in provisioningjsonData.timeInterval, 15s in this lesson) or the panel's Min interval. - Replace template variables:
$route,$__rate_interval=max($__interval + scrape_interval, 4 × scrape_interval)(the formula given in the Grafana documentation). - The browser POSTs the query to the Grafana backend
/api/ds/query(with the user session),the browser never accesses Prometheus directly (access mode Server / proxy). - The backend's Prometheus plugin calls
POST http://prometheus:9090/api/v1/query_range, with parametersquery,start,end,step(step and interval are aligned, and the number of points is kept under the limit). The time range is aligned to the step, which helps caching and stable graphs. - Prometheus returns a matrix, and the plugin converts it into Grafana's data frames (data frame); the legend is generated in the Legend format (such as
{{route}}). - The frontend then runs transformations (transformations), field configuration (units, decimals, thresholds, mappings, overrides), and renders time series graphs, Stat, Gauge, Table, Heatmap and so on.
Why: why rate must use $__rate_interval
When the time range is stretched from 1 hour to 7 days,$__interval changes from 15s to several minutes. If you write rate(x[$__interval]): zoomed in, the window may contain only 1 sample → no data; if you hard-code rate(x[5m]): when viewing 7 days, the step may be 10 minutes, and each point looks only at the last 5 minutes,so spikes in the 5 minutes in between are skipped entirely. $__rate_interval It ensures the window covers at least 4 scrape intervals and at least one scrape interval more than the step, so adjacent points' windows join end to end and no samples are missed. This assumes the data source's Scrape interval setting is correct.
When: provisioning, the UI and "dashboards as code"
| Method | Suitable for | Notes |
|---|---|---|
| Manual editing in the UI | exploration, prototyping | saved in the database; easy to "drift", with no review |
| File provisioning | this lesson, simple GitOps | /etc/grafana/provisioning/{datasources,dashboards,alerting,plugins}; loaded at startup; the dashboard directory is updateIntervalSeconds polled |
| HTTP API / Terraform provider / Grafonnet | scale, multiple instances | Lesson 5 |
| Git Sync (Grafana 13.0 GA) | edit in the UI and commit a PR directly | two-way sync of dashboards and folders with repositories such as GitHub / GitLab / Bitbucket |
Changes in Grafana 13 (relevant to this lesson)
- Dynamic dashboards GA and enabled by default: a new layout engine (rows, tabs, automatic grid) and a new dashboard structure; old dashboards are migrated to the new structure automatically when opened, with no manual action needed. The JSON in this lesson uses the classic structure, which Grafana 13 can load directly.
- Git Sync GA; "Recently deleted" restoration of deleted dashboards GA; the new Gauge panel GA; Ad hoc filters renamed to Filters.
- Docker images: since 12.4.0 use
grafana/grafana(grafana/grafana-ossis no longer updated);grafana/grafana-enterprisefree to use, and includes all OSS features.
http://prometheus:9090. ② "The more panels and the more precise they are, the better" — with a large maxDataPoints the step becomes small, and query cost grows linearly. ③ "Grafana alerts and Prometheus alerts are the same thing" — Grafana Alerting evaluates queries in the Grafana backend, while Prometheus alerting rules are evaluated inside Prometheus; Lesson 2 compares them. ④ "A provisioned dashboard can be permanently modified in the UI" —allowUiUpdates: true only allows temporary saves; after a file change or a restart, the file takes precedence.Grafana architecture and query path
$__interval and $__rate_interval
panel query path + interval calculator
Adjust the time range, panel width and scrape interval to see the $__interval and $__rate_interval that Grafana calculates, and the final request sent to Prometheus. The rounding rules follow Grafana's roundInterval simplified implementation.
Grafana HTTP API and container commands
| Command / endpoint | Purpose | Notes |
|---|---|---|
GET /api/health | Health and version | no authentication needed; includes database status |
GET /api/datasources | List data sources | requires admin; provisioned ones carry readOnly: true |
GET /api/datasources/uid/<uid>/health | Test data source connectivity | equivalent to the UI's "Save & test" |
POST /api/ds/query | Run a query as Grafana | to troubleshoot "Grafana cannot find it but Prometheus can" |
GET /api/search?type=dash-db | Search dashboards | after getting the uid, GET /api/dashboards/uid/<uid> |
grafana cli admin reset-admin-password | Reset the admin password | run inside the container |
docker compose logs grafana | grep -i provisioning | View provisioning logs | the first place to look when a data source or dashboard fails to load |
G=http://127.0.0.1:3000; A='admin:promlab-admin' curl -s $G/api/health | jq curl -s -u $A $G/api/datasources | jq -r '.[] | "\(.name)\t\(.type)\t\(.url)\treadOnly=\(.readOnly)"' curl -s -u $A $G/api/datasources/uid/prometheus/health | jq
{
"database": "ok",
"version": "13.3.1",
"commit": "…"
}
Prometheus prometheus http://prometheus:9090 readOnly=true
{
"message": "Successfully queried the Prometheus API.",
"status": "OK"
}
Run one query as Grafana
curl -s -u $A -H 'Content-Type: application/json' $G/api/ds/query -d '{
"from": "now-5m", "to": "now",
"queries": [{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (route) (rate(myapp_http_requests_total[$__rate_interval]))",
"range": true, "intervalMs": 15000, "maxDataPoints": 300
}]
}' | jq -r '.results.A.frames[] | "\(.schema.name // .schema.fields[1].labels.route)\t\(.data.values[1][-1])"'
/ 4.41 /error 0.233 /healthz 0.0667 /slow 0.467
How to verify: the result should match the same query in the Prometheus UI (with $__rate_interval replaced by 1m). Common errors: a wrong datasource uid returns data source not found. Production use: distinguish whether the problem lies in Grafana (permissions, variables, transformations) or in Prometheus (the data itself). The field structure of returned frames may differ slightly between Grafana versions, so use the actual output to determine the jq paths.
Lab 6: from Explore to a panel (about 6 min)
http://localhost:3000, and log in with admin / promlab-admin (the first login will not ask you to change the password, because the password was already set through an environment variable). Go to Connections → Data sources → Prometheus; the page says the data source is managed by provisioning and cannot be edited in the UI; Scrape interval shows 15s.myapp_http_requests_total, choose Rate for the operation, then Sum by route; switch to the Code mode to view the generated PromQL:
sum by(route) (rate(myapp_http_requests_total[$__rate_interval]))
Open Query inspector → Query to see the actual start,end,step (Grafana has already replaced $__rate_interval with concrete values, such as 1m).
Last 5 minutes: interval=15s (bounded below by the data source's Scrape interval), rate window 1m Last 6 hours: interval ≈ 20s–30s (depends on the panel width), rate window = max(interval+15s, 60s)
sum(rate(myapp_http_requests_total{route="/error"}[$__rate_interval]))
sum(rate(myapp_http_requests_total{route="/error"}[$__interval]))
With a short time range the second query may show gaps or empty values (fewer than 2 samples in the window); with a very long time range the two converge.
grafana:3000/metrics:
sum by (status_code) (rate(grafana_http_request_duration_seconds_count[5m]))
Refresh the Grafana page a few times and you can see the change in Grafana's own request volume; monitoring the monitoring system itself is essential in production.
Case 1: data source URL written as localhost
Problem: A developer opened http://localhost:9090 in a browser on their own machine and could see Prometheus, so they entered the same address in the Grafana data source; "Save & test" then reported connection refused. Approach: understand that in Server access mode the request is made by the Grafana backend, and change it to the service name on the container network http://prometheus:9090 (in Kubernetes this is a Service DNS name, such as http://kps-kube-prometheus-stack-prometheus.monitoring:9090, Lesson 5).
Case 2: a dashboard on a big screen overwhelms Prometheus
Problem: A NOC wall display had 30 panels, auto-refreshed every 5 seconds, and defaulted to a 7-day time range, so it fired 30 long-range queries every 5 seconds. Approach: change the refresh interval to 1 minute, change the default time range of the display to 6 hours, move heavy queries to recording rules, and set min_refresh_interval in Grafana's settings. Limitation: the real need for "real-time" must be discussed with the users.
Case 3: dashboard drift and provisioning
Problem: Several people modified a production dashboard in the UI; someone accidentally deleted a key panel, and nobody knew who did it or what changed. Approach: Move key dashboards to JSON in Git with file provisioning (or Grafana 13's Git Sync), and review changes through PRs; temporary changes made in the UI must be exported as JSON and then committed. Since 13.0 you can also restore accidentally deleted dashboards from "Recently deleted".
Common errors and fixes
Post "http://localhost:9090/api/v1/query": dial tcp [::1]:9090: connect: connection refused
Cause: the data source URL uses localhost; the request is sent from the Grafana container.
docker compose exec grafana wget -qO- http://prometheus:9090/-/ready # If wget is not in the image, test from the same network with a temporary container: docker run --rm --network promlab_default curlimages/curl -s http://prometheus:9090/-/ready
Fix: change the URL to http://prometheus:9090 (after editing the provisioning file, docker compose restart grafana).
Grafana log: Datasource provisioning error: data source not found / datasource names must be unique
Cause: the name or uid is duplicated in the provisioning file, or a manually created data source with the same name already exists.
docker compose logs grafana 2>&1 | grep -i -E "provision|datasource" | tail -5
Fix: make sure name and uid are unique; to clean up old data sources, you can use deleteDatasources in the provisioning file.
The panel shows "No data", but the same query returns data in Explore
Cause: the panel's time range or its "Relative time / Time shift" override is applied; a variable value does not match (for example, when the variable is All the query uses = instead of =~); the panel uses a different data source; or a transformation filtered the data out.
Fix: open the panel's Query inspector to check the actual query sent and the data returned, and rule out each item.
Login says Invalid username or password (even though GF_SECURITY_ADMIN_PASSWORD was set)
Cause: The admin password env var only takes effect during first database initialization; grafana-data the volume already has an old database.
docker compose exec grafana grafana cli admin reset-admin-password 'promlab-admin'
Fix: Reset with the CLI, or in the lab environment, docker compose down then delete the promlab_grafana-data volume and restart.
1. Use the Grafana API to test whether the data source with uid prometheus is healthy.
curl -s -u admin:promlab-admin http://127.0.0.1:3000/api/datasources/uid/prometheus/health | jq -r .status
2. With a scrape interval of 30s and $__interval of 10s, what is $__rate_interval? What if $__interval is 5m?
max(10s + 30s, 4 × 30s) = 2m; max(5m + 30s, 2m) = 5m30s. This assumes the data source's Scrape interval is set to 30s; otherwise Grafana uses the default 15s, making the window too small.
Security requires that “Prometheus must not be directly accessible from the office network,” but operators need to view graphs in Grafana. Does the current architecture meet this? What else must be considered?
Yes. In Server access mode, only the Grafana backend talks to Prometheus, so Prometheus only needs to be reachable from the Grafana network (the Compose network in this course). Things to note: ① Grafana itself must enable SSO/Entra ID or other authentication plus RBAC, because anyone who can log into Grafana can query every metric through the data source (fine-grained data source permissions require Enterprise/Cloud); ② Explore allows arbitrary PromQL, so restrict it by role; ③ Prometheus should still have network isolation or TLS/basic auth (--web.config.file) as defense in depth.
Verified instructional videos
Official docs
- Prometheus data source
- Prometheus template variables and $__rate_interval
- Provisioning
- What's new in Grafana v13.0
- Run Grafana Docker image
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided instead.
Visual: Inside the Grafana icon is a small database labeled “dashboards, users, data sources”; the metric data icon is drawn on the Prometheus side.
Narration: Grafana only stores dashboards and configuration; metrics always stay in Prometheus.
Visual: The browser sends the query to the Grafana backend, which asks Prometheus with start, end and step; the returned data becomes table frames and is then drawn as curves.
Narration: Every panel refresh is a range query proxied through the backend.
Visual: The time range is stretched from 1 hour to 7 days; gaps appear between fixed 5-minute windows, and after switching to rate_interval the windows join end to end.
Narration: Leave the rate window to the $__rate_interval variable, which guarantees at least four scrape intervals and never skips samples.
Module 7 · Build your first dashboard: variables and the RED method
- Use the RED method (Rate, Errors, Duration) to design dashboards for request-driven services, and the USE method (Utilization, Saturation, Errors) to design dashboards for resources.
- Create query variables
label_values(), with multi-select and All, and use them correctly in queries=~"$route". - Choose suitable visualizations for each panel (Time series, Stat, Gauge, Heatmap, Table), along with units (reqps, percentunit, s) and thresholds.
- Export the dashboard as JSON into
~/promlab/grafana/dashboards/, and load it through file provisioning (reused in Lesson 2).
What: RED and USE
| Method | Target | Three signals | PromQL on myapp / hosts |
|---|---|---|---|
| RED (Tom Wilkie) | Request-driven services | Rate: requests per second | sum(rate(myapp_http_requests_total[$__rate_interval])) |
| Errors: share of failed requests | sum(rate(…{status=~"5.."}[…])) / sum(rate(…[…])) | ||
| Duration: latency distribution | histogram_quantile(0.95, sum by (le) (rate(…_bucket[…]))) | ||
| USE (Brendan Gregg) | Resources (CPU, memory, disk, network) | Utilization: how busy | 1 - avg(rate(node_cpu_seconds_total{mode="idle"}[…])) |
| Saturation: amount of queueing | node_load1 / count without (cpu, mode) (node_cpu_seconds_total{mode="idle"}) | ||
| Errors: error events | rate(node_network_receive_errs_total[…]) |
Google SRE's “four golden signals” (latency, traffic, errors, saturation) are RED plus saturation; Module 6 of Lesson 2 covers dashboard design in depth. This lesson starts with a working RED dashboard.
How: variables
| Variable | Type | Definition | Key points |
|---|---|---|---|
job | Query | label_values(myapp_http_requests_total, job) | Single-select; add more later when multiple environments are needed env |
route | Query, multi-select + Include All | label_values(myapp_http_requests_total{job="$job"}, route) | Set Custom all value to .*; use in queries as route=~"$route" |
$__rate_interval etc. | Built-in | — | No definition needed |
Multi-select variables are substituted as a regex (/|/slow), so must use =~; set Custom all value to .* This avoids expanding All into a very long regex. Set the variable's Refresh to “On time range change” so new routes automatically appear in the dropdown.
Why: choosing a visualization for each panel
| Question | Visualization | Unit / settings |
|---|---|---|
| What are the current QPS, error rate and P95? | Stat (with mini trend) | reqps,percentunit,s; thresholds: error rate 1% yellow, 5% red |
| Traffic trend per route | Time series, legend {{route}} | stacking optional |
| Latency percentiles over time | Time series: P50 / P95 / P99 as three lines | s; log scale optional |
| Overall shape of the latency distribution | Heatmap, query Format set to Heatmap, legend {{le}} | Grafana converts cumulative buckets back to per-bucket counts |
| Are dependencies healthy? | Stat + value mappings (1 → UP green, 0 → DOWN red) | myapp_redis_up |
When: manual UI vs JSON file
Build it in the UI first (what you see is what you get). Once you're satisfied, export it via Share/Export → Export as JSON, save it to a Git-managed file, and load it with provisioning. This lab provides the complete JSON directly; you can also follow the steps in the UI first and compare.
=~. ② “The Stat panel shows an instantaneous value”: it reduces the series returned by the query (default Last not null), but the query itself is still a range query. ③ “Heatmap can just graph _bucket directly”: you need to sum by (le) add rate, set Format to Heatmap, otherwise you see cumulative counts. ④ “More dashboards are better”: one RED overview per service plus a few drill-down pages is more useful than dozens of unmaintained panels.myapp RED dashboard layout
Variable substitution process
RED dashboard fault-injection simulator
Drag the sliders to simulate traffic, error ratio and latency. The three panels update every “15 seconds”. P95 is estimated with histogram_quantile using the same buckets as myapp (0.005…5); note the gap between it and the “true P95”.
Dashboard-related API and PromQL
| Command | Purpose | Notes |
|---|---|---|
GET /api/search?query=myapp | Find dashboard uid | Provisioned dashboards are visible here too |
GET /api/dashboards/uid/myapp-red | Export JSON (with meta) | .dashboard the dashboard field is the dashboard itself |
POST /api/dashboards/db | Create/update via API | Choose either this or file provisioning to manage the same uid |
GET /api/annotations | Annotations (release markers) | Lesson 2 writes deployment events as annotations |
G=http://127.0.0.1:3000; A='admin:promlab-admin'
curl -s -u $A "$G/api/search?query=myapp" | jq -r '.[] | "\(.uid)\t\(.title)\t\(.folderTitle)"'
curl -s -u $A $G/api/dashboards/uid/myapp-red | jq '.meta | {provisioned, provisionedExternalId, canSave}'
myapp-red myapp · RED overview promlab
{
"provisioned": true,
"provisionedExternalId": "myapp-red.json",
"canSave": true
}
All queries used in the panels
# Rate
sum(rate(myapp_http_requests_total{job="$job", route=~"$route"}[$__rate_interval]))
# Errors (ratio; add 0 to avoid showing No data when there are no errors)
(sum(rate(myapp_http_requests_total{job="$job", route=~"$route", status=~"5.."}[$__rate_interval])) or vector(0))
/ sum(rate(myapp_http_requests_total{job="$job", route=~"$route"}[$__rate_interval]))
# Duration
histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job="$job", route=~"$route"}[$__rate_interval])))
# Heatmap (Format = Heatmap, Legend = {{le}})
sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job="$job", route=~"$route"}[$__rate_interval]))
Lab 7: Check the myapp RED dashboard into the repo (about 8 min)
cd ~/promlab
cat > grafana/dashboards/myapp-red.json <<'EOF'
{
"uid": "myapp-red",
"title": "myapp · RED overview",
"tags": ["promlab", "myapp", "red"],
"timezone": "browser",
"schemaVersion": 41,
"refresh": "30s",
"time": { "from": "now-30m", "to": "now" },
"templating": {
"list": [
{
"name": "job", "label": "job", "type": "query",
"datasource": { "type": "prometheus", "uid": "prometheus" },
"definition": "label_values(myapp_http_requests_total, job)",
"query": { "query": "label_values(myapp_http_requests_total, job)", "refId": "job" },
"refresh": 2, "includeAll": false, "multi": false, "sort": 1
},
{
"name": "route", "label": "route", "type": "query",
"datasource": { "type": "prometheus", "uid": "prometheus" },
"definition": "label_values(myapp_http_requests_total{job=\"$job\"}, route)",
"query": { "query": "label_values(myapp_http_requests_total{job=\"$job\"}, route)", "refId": "route" },
"refresh": 2, "includeAll": true, "multi": true, "allValue": ".*", "sort": 1
}
]
},
"panels": [
{
"id": 1, "type": "stat", "title": "Rate (req/s)",
"gridPos": { "h": 4, "w": 6, "x": 0, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "sum(rate(myapp_http_requests_total{job=\"$job\", route=~\"$route\"}[$__rate_interval]))" }],
"fieldConfig": { "defaults": { "unit": "reqps", "decimals": 2 }, "overrides": [] },
"options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "graphMode": "area", "colorMode": "value" }
},
{
"id": 2, "type": "stat", "title": "Errors (5xx ratio)",
"gridPos": { "h": 4, "w": 6, "x": 6, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "(sum(rate(myapp_http_requests_total{job=\"$job\", route=~\"$route\", status=~\"5..\"}[$__rate_interval])) or vector(0)) / sum(rate(myapp_http_requests_total{job=\"$job\", route=~\"$route\"}[$__rate_interval]))" }],
"fieldConfig": { "defaults": { "unit": "percentunit", "decimals": 2,
"thresholds": { "mode": "absolute", "steps": [
{ "color": "green", "value": null }, { "color": "yellow", "value": 0.01 }, { "color": "red", "value": 0.05 } ] } }, "overrides": [] },
"options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "graphMode": "area", "colorMode": "background" }
},
{
"id": 3, "type": "stat", "title": "Duration (P95)",
"gridPos": { "h": 4, "w": 6, "x": 12, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job=\"$job\", route=~\"$route\"}[$__rate_interval])))" }],
"fieldConfig": { "defaults": { "unit": "s", "decimals": 3,
"thresholds": { "mode": "absolute", "steps": [
{ "color": "green", "value": null }, { "color": "yellow", "value": 0.5 }, { "color": "red", "value": 1 } ] } }, "overrides": [] },
"options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "graphMode": "area", "colorMode": "value" }
},
{
"id": 4, "type": "stat", "title": "Redis dependency",
"gridPos": { "h": 4, "w": 6, "x": 18, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "min(myapp_redis_up{job=\"$job\"})" }],
"fieldConfig": { "defaults": {
"mappings": [{ "type": "value", "options": {
"0": { "text": "DOWN", "color": "red" }, "1": { "text": "UP", "color": "green" } } }],
"thresholds": { "mode": "absolute", "steps": [ { "color": "red", "value": null }, { "color": "green", "value": 1 } ] } }, "overrides": [] },
"options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "graphMode": "none", "colorMode": "background" }
},
{
"id": 5, "type": "timeseries", "title": "Request rate by route",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 4 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "sum by (route) (rate(myapp_http_requests_total{job=\"$job\", route=~\"$route\"}[$__rate_interval]))", "legendFormat": "{{route}}" }],
"fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] }
},
{
"id": 6, "type": "timeseries", "title": "Error rate by route, status",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 4 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "sum by (route, status) (rate(myapp_http_requests_total{job=\"$job\", route=~\"$route\", status=~\"5..\"}[$__rate_interval]))", "legendFormat": "{{route}} {{status}}" }],
"fieldConfig": { "defaults": { "unit": "reqps", "color": { "mode": "fixed", "fixedColor": "red" } }, "overrides": [] }
},
{
"id": 7, "type": "timeseries", "title": "Latency percentiles",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 12 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{ "refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job=\"$job\", route=~\"$route\"}[$__rate_interval])))", "legendFormat": "P50" },
{ "refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job=\"$job\", route=~\"$route\"}[$__rate_interval])))", "legendFormat": "P95" },
{ "refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job=\"$job\", route=~\"$route\"}[$__rate_interval])))", "legendFormat": "P99" }
],
"fieldConfig": { "defaults": { "unit": "s" }, "overrides": [] }
},
{
"id": 8, "type": "heatmap", "title": "Latency distribution (Heatmap)",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 12 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [{ "refId": "A", "expr": "sum by (le) (rate(myapp_http_request_duration_seconds_bucket{job=\"$job\", route=~\"$route\"}[$__rate_interval]))", "format": "heatmap", "legendFormat": "{{le}}" }],
"options": { "calculate": false, "yAxis": { "unit": "s" }, "cellGap": 1 }
}
]
}
EOF
python3 -m json.tool grafana/dashboards/myapp-red.json > /dev/null && echo "JSON OK"
JSON OK
sleep 35 docker compose logs grafana 2>&1 | grep -i dashboard | tail -3 echo "Open http://localhost:3000/d/myapp-red"
The dashboard is in the promlab folder. Grafana 13 automatically migrates it to the dynamic dashboard structure when opened. If you edit and save it in the UI, the next file change will overwrite your edits with the file contents, so to keep changes long term, export the JSON and write it back to the file.
/,/error,/healthz, and /slow; select only /slow when selected, the Errors panel should show 0% and P95 should be about 1–2.5 seconds. Open the Query inspector on any panel and confirm that route=~"/slow" is substituted correctly.for i in $(seq 1 200); do curl -s -o /dev/null 127.0.0.1:5000/error; done # error spike docker compose stop redis; sleep 60; docker compose start redis # dependency failure
The first command turns the Errors panel red; the second makes the Redis dependency panel show DOWN. Note: while Redis is down, / the app still returns 200 (it degrades rather than fails), so Errors does not rise—watching RED alone will miss “degradation”, which is why dependencies need separate monitoring.
~/promlab the file to Git:
cd ~/promlab && git init -q 2>/dev/null; git add -A && git commit -qm "promlab: hour 1 baseline" && git log --oneline | head -1
Case 1: one RED dashboard template per service
Problem: 40 microservices each draw their own graphs, with metric names, units and thresholds all over the place, so on-call engineers cannot compare them quickly. Approach: Standardize metric naming (for example, the <app>_http_requests_total), and build one generic RED dashboard template with service variables that all services share; service-specific panels go on drill-down pages. Limitations: Requires an instrumentation standard first; legacy services need name mapping via recording rules.
Case 2: Heatmap reveals bimodal latency
Problem: P95 looks stable at 300ms, but users report that it is “sometimes fast, sometimes slow.”Approach: The latency heatmap shows two distinct bands: about 20ms (cache hits) and about 280ms (cache misses). P95 falls right on the second band, masking the drop in hit rate. After adding a cache hit-rate panel, the cause was traced to Redis memory eviction.
Case 3: the All variable slows queries
Problem: The route variable has 600 values; when All is selected, Grafana joins all values into one huge regex, making queries slow and URLs too long. Approach: Set Custom all value to .*; also consider why one service has 600 route label values (parameters may have been baked into routes).
Common errors and fixes
Variable dropdown is empty / “No options found”
Cause:label_values() The metric name or dependent variable in the query is wrong; the wrong data source is selected; or the metric has no data in the time range.
Fix: Run myapp_http_requests_total{job="myapp"} in Explore to confirm it returns data; the Preview of values on the variable edit page shows the results live.
Panels show No data after selecting multiple routes
Cause: The query uses route="$route", which is substituted as route="(/|/slow)", so it matches nothing literally.
Fix: Change it to route=~"$route".
Grafana log: failed to load dashboard from ... Dashboard title cannot be empty / invalid character
Cause: JSON syntax error (extra comma, unescaped quotes) or a missing title.
python3 -m json.tool ~/promlab/grafana/dashboards/myapp-red.json > /dev/null
Fix: Correct the JSON; validate dashboard files as JSON in CI.
Heatmap shows only one bright band, and the shape is wrong
Cause: Query Format is not set to Heatmap (Grafana does not convert cumulative buckets into per-interval counts), or Calculate was enabled, re-bucketing data that is already bucketed.
Fix: In the query, set "format": "heatmap", legend {{le}}, and in the panel calculate: false.
1. Use the API to export the myapp-red dashboard body and save it to a file.
curl -s -u admin:promlab-admin http://127.0.0.1:3000/api/dashboards/uid/myapp-red | jq '.dashboard' > myapp-red.export.json
2. Write the query for “CPU saturation” in the USE method (load average per core).
node_load1 / on(instance) count by (instance) (node_cpu_seconds_total{mode="idle"})While on call, all three RED panels look normal, but customer support says “some users keep seeing the counter as N/A.” What is the dashboard missing? How can it be improved?
When Redis is unavailable, myapp returns 200 + “N/A”: it degrades without reporting an error, so the Errors metric in RED does not reveal it. Improvements: ① add dependency panels to the dashboard (myapp_redis_up,redis_up); ② the app can add business outcome metrics (such as myapp_hits_failures_total); ③ define degradation as part of the SLI (success = 200 with a valid result); ④ in Lesson 2, configure alerts for myapp_redis_up == 0 these metrics.
Verified instructional videos
No verified videos on Grafana 13 dynamic dashboards or the RED method were found; please use the storyboard script.
Official docs
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided instead.
Visual: the letters R, E and D turn in turn into three Stat cards: 5 req/s, 0.5%, 120ms.
Narration: The RED method judges a service with three questions: how many requests, how many failures, and how slow?
Visual: two values are multi-selected in the route dropdown, and the $route variable in the query turns into a regex in parentheses separated by pipes.
Narration: Multi-select variables become regexes, so the query must use the =~ operator.
Visual: the latency heatmap shows two bands, while the P95 curve stays flat.
Narration: Quantiles hide the shape of the distribution; the heatmap reveals the bimodal pattern.
Visual: the dashboard is exported as a JSON file, committed to the Git repo, and Grafana loads it automatically.
Narration: Once you're satisfied, turn the dashboard into a file: provisioning loads it and Git reviews it.
Module 8 · Introduction to myapp observability readiness and troubleshooting
- Use an “observability readiness checklist” to review whether a service (myapp) is ready to go live.
- Master the fixed troubleshooting order: Target → scrape → metric → query → panel, and the command to use to confirm each layer.
- Reproduce and fix six common problem types: target down (DNS / connection refused), scrape timeout, HTTP 404/500, multiprocess configuration errors, Grafana data source errors, and query syntax errors.
What: observability readiness checklist (myapp version)
| # | Check item | Current state of myapp | How to verify |
|---|---|---|---|
| 1 | Exposure /metrics, Content-Type correct | ✓ prometheus_client,text/plain; version=1.0.0 | curl -sI :5000/metrics |
| 2 | All three RED metrics present, with names following conventions | ✓ Three consistent names | promtool check metrics |
| 3 | Bounded labels (route templates, status codes) | ✓ url_rule.rule, unmatched → unmatched | count by (route) (…) |
| 4 | Histogram buckets cover the SLO threshold | △ 0.25/0.5 s present; if the SLO is 300ms, add buckets | Review |
| 5 | Multiprocess mode correct (directory cleanup,child_exit) | ✓ | counters restart from 0 after a restart, with no duplicates |
| 6 | Dependency status visible | ✓ myapp_redis_up (refreshed on scrape) | Stop Redis and observe |
| 7 | Health checks separate from metrics,/healthz not dependent on downstream services | ✓ | healthz still returns 200 when Redis is stopped |
| 8 | scraped by Prometheus,up with alerts | △ Scraping ✓, alerts covered in Lesson 2 | up{job="myapp"} |
| 9 | Dashboards managed as code | ✓ myapp-red.json | provisioned = true |
| 10 | Versions traceable (build info, release annotations) | ✗ To add: myapp_build_info{version} and release annotations (later lessons) | — |
How: the fixed troubleshooting order
- Target: is the target there?
/targetspage, or/api/v1/targets; if missing → service discovery / relabel issue (check dropped targets). - Scrape:
upIs it 1?lastErrorIf not, what is the error? DNS, connection refused, timeout, HTTP status code and Content-Type each produce distinctive error messages. - Metric: is this metric present in the target's output?
curlthe target's/metrics; comparescrape_samples_scrapedwithscrape_samples_post_metric_relabeling. - Query: run the same PromQL in the Prometheus UI; if the result is empty, remove conditions step by step (first keep only the metric name).
- Panel: use Query inspector to see the actual query sent, the variable substitution results and returned data; check the data source, time range and transformations.
Why: the reason to check the scrape layer first
Most “no data on the graph” problems happen on the collection side, and every collection failure leaves precise clues in up and lastError the corresponding places. Staring at panels and tweaking queries often wastes time at the wrong layer.
When: when to escalate to deeper investigation
This module covers introductory scenarios. Intermittent scrape failures across many targets, steadily rising Prometheus memory, query timeouts, alerts that don't fire and similar issues are covered systematically in Lesson 7 (troubleshooting methodology, cardinality, TSDB, query performance).
/healthz,/metrics which may be returning 500. ② “up=1 means the service is working”: it only means /metrics the target can be scraped; when Redis is down, myapp's up is still 1. ③ “No data must be a Prometheus problem”: most of the time it's variables, the time range or data source configuration.Five-layer troubleshooting funnel
myapp metric dependencies
Failure reproduction simulator: pick a failure and see how it appears at each layer
Each failure corresponds to steps that can be reproduced for real on the “Lab” tab. After clicking, it shows in sequence: the Targets page, PromQL, the Grafana panel, and the root cause and fix.
Five-layer troubleshooting command cheat sheet
| Layer | Command | What to check |
|---|---|---|
| ① Target | curl -s :9090/api/v1/targets?state=any | jq … | whether the target exists and whether it is dropped |
| ② Scrape | up{job="myapp"},scrape_duration_seconds,lastError | 0/1, scrape duration close to the timeout, raw error message |
| ② Scrape (network) | docker compose exec prometheus wget -qO- -T 5 http://myapp:5000/metrics | Run from the network where Prometheus runs |
| ③ Metrics | curl -s :5000/metrics | grep NAME | whether the metric is exposed and whether the labels are as expected |
| ④ Query | promtool query instant http://localhost:9090 'EXPR' | remove conditions step by step |
| ⑤ Panel | Query inspector; POST /api/ds/query | the expression after variable substitution, step, returned frames |
# One command to check the health, duration and errors of all targets curl -s '127.0.0.1:9090/api/v1/targets?state=active' | jq -r '.data.activeTargets[] | [.labels.job, .scrapeUrl, .health, (.lastScrapeDuration|tostring), .lastError] | @tsv' | column -t -s $'\t'
prometheus http://localhost:9090/metrics up 0.0049 alertmanager http://alertmanager:9093/metrics up 0.0031 grafana http://grafana:3000/metrics up 0.0102 node http://node-exporter:9100/metrics up 0.0211 myapp http://myapp:5001/metrics down 0.0012 Get "http://myapp:5001/metrics": dial tcp 172.18.0.6:5001: connect: connection refused redis http://redis-exporter:9121/metrics up 0.0079
myapp's own diagnostics
docker compose exec myapp env | grep PROMETHEUS_MULTIPROC_DIR
docker compose exec myapp ls /tmp/prom-multiproc | head
docker compose logs --tail=30 myapp | grep -iE "error|exception|Traceback"
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' 127.0.0.1:5000/metrics
PROMETHEUS_MULTIPROC_DIR=/tmp/prom-multiproc counter_7.db counter_8.db gauge_livemostrecent_7.db histogram_7.db histogram_8.db 200 text/plain; version=1.0.0; charset=utf-8
Lab 8: inject 4 faults and fix them (about 10 minutes)
Restore each fault to its original state once fixed; the final ~/promlab state matches the end of Module 7 (the starting point of Lesson 2).
cd ~/promlab sed -i 's/"myapp:5000"/"myapp:5001"/' prometheus/prometheus.yml curl -s -X POST 127.0.0.1:9090/-/reload; sleep 20 curl -s '127.0.0.1:9090/api/v1/targets' | jq -r '.data.activeTargets[] | select(.labels.job=="myapp") | .lastError'
Get "http://myapp:5001/metrics": dial tcp 172.18.0.6:5001: connect: connection refused
Interpretation: DNS resolves (an IP is returned), but nothing is listening on the port. At the same time, the Rate panel in the Grafana RED dashboard changes to No data — the staleness marker makes the old series disappear immediately. Fix:
sed -i 's/"myapp:5001"/"myapp:5000"/' prometheus/prometheus.yml && curl -s -X POST 127.0.0.1:9090/-/reload
metrics_path: /metric, after reload:
server returned HTTP status 404 NOT FOUND
Werkzeug's status-line text is uppercase NOT FOUND. Delete this line and reload to restore.
docker run -d --name mp-broken --network promlab_default --entrypoint sh myapp:1.0 \
-c 'unset PROMETHEUS_MULTIPROC_DIR; exec gunicorn -b 0.0.0.0:5000 app:app'
sleep 3; docker run --rm --network promlab_default curlimages/curl -s -o /dev/null -w '%{http_code}\n' http://mp-broken:5000/metrics
docker logs mp-broken 2>&1 | grep -m1 ValueError
docker rm -f mp-broken
500 ValueError: env PROMETHEUS_MULTIPROC_DIR is not set or not a directory
Bypassed gunicorn.conf.py (without using -c) and removed the environment variable: at import time, the client library decides whether to use multiprocess storage based on whether the variable exists decides to use multiprocess storage; in that case it falls back to single-process mode to record metrics, but MultiProcessCollector the directory is not found and an exception is raised. Note: if the variable is set to an empty string, the library still enters multiprocess mode and tries to write .db files. When run as a non-root user, the worker fails to start because of a permission error — this is another, more subtle failure. If this is a target scraped by Prometheus,lastError it would be server returned HTTP status 500 INTERNAL SERVER ERROR, while the container HEALTHCHECK still reports healthy.
rate(myapp_redis_up[5m])
It is normally 0, but when Redis recovers it shows a strange positive value, and during an outage (1→0 is treated as a counter reset) it also shows a positive value — completely meaningless. The correct approach: min_over_time(myapp_redis_up[5m]) or changes(myapp_redis_up[1h]).
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=count(up == 1)' | jq -r '.data.result[0].value[1]' git -C ~/promlab status --short
6
All 6 targets are up,git status no uncommitted changes (if you committed in Module 7), and the environment is ready forLesson 2.
Case 1: metrics “disappear” after a release
Problem: The new version replaced Flask with FastAPI,/metrics the ASGI application is mounted at /metrics/ (with a trailing slash), Prometheus requests /metrics gets a 307 redirect. Prometheus follows redirects by default, but the new path returns an HTML error page, and 3.x reports a Content-Type error. Approach: Add a “scrape smoke test” to the release pipeline: after deployment, query up{job="x"} == 1 and scrape_samples_scraped > 0, rolling back automatically on failure.
Case 2: a healthy container, a 500 from /metrics
Problem: During the image refactor, we dropped PROMETHEUS_MULTIPROC_DIR, so the service worked normally and HEALTHCHECK passed, but for 3 days there were no business metrics until someone noticed the blank dashboard. Approach: In Lesson 2, configure up == 0 and absent(myapp_http_requests_total) alerts; after the image is built, in CI curl /metrics and assert that it contains the unified metric names.
Case 3: the on-call runbook written as a troubleshooting tree
Problem: When new on-call engineers hit “the panel has no data”, they try things at random, with an average diagnosis time of 40 minutes. Approach: Write the five-layer order from this module into the on-call runbook (like the interactive troubleshooting tree below), giving a copy-paste command and expected output for each step; diagnosis time drops to under 10 minutes.
Interactive troubleshooting tree: Prometheus / Grafana basics
Start from the symptom you see, answer the questions step by step, and get diagnostic commands and fix suggestions.
Note: typical raw error messages from this module
Get "http://myapp:5000/metrics": dial tcp: lookup myapp on 127.0.0.11:53: no such host
Cause: The container does not exist or is not on the same network (service name misspelled, container stopped, or Prometheus not on the promlab network). Fix:docker compose ps; confirm the service name; when crossing Compose projects, add Prometheus to the target network.
server returned HTTP status 500 INTERNAL SERVER ERROR
Cause: The target's /metrics handler raises an exception. Fix: Check the Traceback in the target's logs; a multiprocess configuration is the most common cause.
node-exporter fails to start: path / is mounted on / but it is not a shared or slave mount (Docker Desktop)
Cause: The Docker Desktop (macOS/Windows) VM filesystem does not support rslave propagation. Fix: On Docker Desktop, remove ,rslave (the read-only mount /:/host:ro), and accept that you see metrics from the Docker VM; for production, use a Linux host.
1. List all down targets and their errors, showing only the job and the first 80 characters of the error.
curl -s 127.0.0.1:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.health=="down") | "\(.labels.job)\t\(.lastError[0:80])"'
2. Write a PromQL query for targets whose scrape duration exceeds 80% of the timeout (early warning of timeouts).
scrape_duration_seconds > 0.8 * 10
A more general form needs each job's timeout; Prometheus can extra_scrape_metrics additionally output scrape_timeout_seconds, in which case write scrape_duration_seconds / scrape_timeout_seconds > 0.8.
On Monday morning, all three Stat panels on the myapp RED dashboard show No data, but the Redis dependency panel shows UP. Give your troubleshooting steps following the five-layer order, along with the reasoning for each step.
① Target: the Redis dependency panel comes from myapp_redis_up, which is also a myapp metric; a value means the myapp target exists and can be scraped, so skip to ③; ② Scrape: confirm up{job="myapp"} is 1; ③ Metrics: curl :5000/metrics | grep myapp_http_requests_total— if not, it may be that there have been no requests since the weekend restart (labeled counters are not exposed until the first request), or loadgen has stopped; ④ Query: run the panel query in Prometheus; if it returns data, the problem is in Grafana; ⑤ Panel: use Query inspector to check $job/$route whether the variable is empty (a failed variable query causes all panels to show no data). Most likely cause: no traffic over the weekend + the metric the variable depends on does not exist → the variable is empty.
Verified instructional videos
No verified video on “Prometheus scrape troubleshooting” was found; please use the storyboard script below. For in-depth troubleshooting, see Lesson 7.
Official documentation
Video storyboard script (about 80 seconds)
This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Visual: a blank panel reads No data; the camera pulls back to reveal a five-layer funnel: Target, Scrape, Metrics, Query, Panel.
Narration: when a panel has no data, don't change the query first; check the five layers from top to bottom.
Visual: a row on the Targets page turns red, and the error message is highlighted word by word: lookup, connection refused, deadline exceeded, and HTTP 404 each pop up their matching icon.
Narration: each kind of scrape error has its own signature: resolution failure, nothing listening on the port, timeout, wrong path.
Visual: Grafana Query inspector opens, showing a before-and-after comparison of variable substitution; an “=” changes to “=~” and the curve appears.
Narration: the last layer is the panel: data source URL, variable syntax, time range. Once it's fixed, don't forget to add an alert for this kind of fault.
Command cheat sheet
cd ~/promlab docker compose up -d --build docker compose ps docker compose logs -f prometheus docker compose restart myapp docker compose stop redis && docker compose start redis docker compose down # keep data volumes docker compose down -v # delete all data
docker run --rm -v "$PWD/prometheus:/etc/prometheus:ro" \ --entrypoint promtool prom/prometheus:v3.16.0 \ check config /etc/prometheus/prometheus.yml docker run --rm -v "$PWD/alertmanager:/etc/alertmanager:ro" \ --entrypoint amtool prom/alertmanager:v0.35.0 \ check-config /etc/alertmanager/alertmanager.yml curl -X POST 127.0.0.1:9090/-/reload # Verify: prometheus_config_last_reload_successful == 1
P=127.0.0.1:9090
curl -s $P/-/ready
curl -s $P/api/v1/status/buildinfo | jq .data.version
curl -s $P/api/v1/targets | jq '.data.activeTargets[] | {job: .labels.job, health, lastError}'
curl -s "$P/api/v1/targets?state=dropped" | jq '.data.droppedTargets | length'
curl -s $P/api/v1/query --data-urlencode 'query=up'
curl -s -g "$P/api/v1/series?match[]=myapp_http_requests_total" | jq '.data|length'
curl -s "$P/api/v1/metadata?metric=myapp_redis_up"curl -s 127.0.0.1:5000/metrics | grep ^myapp_ curl -sI 127.0.0.1:5000/metrics | grep -i content-type curl -s 127.0.0.1:9100/metrics | grep ^node_load curl -s 127.0.0.1:9121/metrics | grep ^redis_up docker compose exec prometheus wget -qO- -T 5 http://myapp:5000/metrics | head curl -s 127.0.0.1:5000/metrics | docker run --rm -i \ --entrypoint promtool prom/prometheus:v3.16.0 check metrics
sum by (route) (rate(myapp_http_requests_total[5m]))
sum(rate(myapp_http_requests_total{status=~"5.."}[5m]))
/ sum(rate(myapp_http_requests_total[5m]))
histogram_quantile(0.95,
sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m])))
sum(rate(myapp_http_request_duration_seconds_bucket{le="0.25"}[5m]))
/ sum(rate(myapp_http_request_duration_seconds_count[5m]))
min_over_time(myapp_redis_up[10m])up == 0
scrape_duration_seconds > 8
scrape_samples_scraped - scrape_samples_post_metric_relabeling
1 - avg without (cpu, mode) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0
prometheus_tsdb_head_series
absent(up{job="myapp"})G=http://127.0.0.1:3000; A='admin:promlab-admin' curl -s $G/api/health curl -s -u $A $G/api/datasources | jq '.[].name' curl -s -u $A $G/api/datasources/uid/prometheus/health curl -s -u $A "$G/api/search?query=myapp" curl -s -u $A $G/api/dashboards/uid/myapp-red | jq .dashboard > export.json docker compose exec grafana grafana cli admin reset-admin-password 'NEW'
relabel_configs: # before scraping, applies to targets
- source_labels: [__address__]
regex: "([^:]+):\\d+"
target_label: host
replacement: "${1}"
- source_labels: [env]
regex: lab
action: keep
metric_relabel_configs: # after scraping, applies to samples
- source_labels: [__name__]
regex: "node_scrape_collector_.*"
action: dropQuick troubleshooting table
| Symptom / error | Layer | Most likely cause | First command |
|---|---|---|---|
lookup X on 127.0.0.11:53: no such host | Scrape | Container stopped / wrong service name / different network | docker compose ps |
connect: connection refused | Scrape | Wrong port / listening on 127.0.0.1 / not started | docker compose exec prometheus wget -qO- http://X/metrics |
context deadline exceeded | Scrape | Slow target / saturated workers | scrape_duration_seconds |
server returned HTTP status 404 NOT FOUND | Scrape | metrics_path Wrong | curl -I target path |
server returned HTTP status 500 … | Metrics | Multiprocess config / handler exception | docker compose logs myapp |
received unsupported Content-Type … | Scrape | Returns HTML / content-type error (3.x no longer falls back) | curl -sI; fallback_scrape_protocol |
Grafana dial tcp [::1]:9090 | Panel | Data source URL uses localhost | /api/datasources/uid/…/health |
| No data after selecting multiple variable values | Panel | Used = instead of =~ | Query inspector |
| rate over a window of hours gives intermittent data | Query | < 2 samples in the window | Switch to $__rate_interval |
| histogram_quantile returns NaN | Query | No traffic / dropped le | sum by (le) (rate(..._bucket[5m])) |
Recommended config snippet
# Safety fuse for production scrape jobs (adjust to actual scale)
- job_name: myapp
scrape_interval: 15s
scrape_timeout: 10s
sample_limit: 5000 # if exceeded, the whole scrape fails (up=0), preventing cardinality explosion
label_limit: 30
body_size_limit: 10MB
static_configs:
- targets: ["myapp:5000"]
labels: { env: lab, service: myapp }
Capstone lab + final quiz
cd ~/promlab
docker compose ps --format '{{.Service}}\t{{.Status}}'
curl -s 127.0.0.1:9090/api/v1/query --data-urlencode 'query=count(up == 1)' | jq -r '.data.result[0].value[1]'
alertmanager Up 2 hours grafana Up 2 hours myapp Up 40 minutes (healthy) node-exporter Up 2 hours prometheus Up 2 hours redis Up 41 minutes redis-exporter Up 2 hours 6
pgrep -f loadgen.sh || (./loadgen.sh &) for i in $(seq 1 30); do curl -s -o /dev/null 127.0.0.1:5000/slow; done
for q in \
'up{job="myapp"} == 1' \
'sum(rate(myapp_http_requests_total{job="myapp"}[5m])) > 1' \
'(sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m]))) < 0.10' \
'histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[5m]))) < 0.25' \
'min_over_time(myapp_redis_up[5m]) == 1'; do
n=$(curl -s 127.0.0.1:9090/api/v1/query --data-urlencode "query=$q" | jq '.data.result | length')
[ "$n" -gt 0 ] && echo "PASS $q" || echo "FAIL $q"
done
PASS up{job="myapp"} == 1
PASS sum(rate(myapp_http_requests_total{job="myapp"}[5m])) > 1
PASS (sum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m]))) < 0.10
PASS histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[5m]))) < 0.25
PASS min_over_time(myapp_redis_up[5m]) == 1
Comparison operators filter by default: when the condition is not met, the result is empty → FAIL. This “query returns non-empty means pass” pattern becomes an alerting rule in Lesson 2 and a promtool unit test in Lesson 5.
grafana/dashboards/node-redis.json (with uid set to node-redis):
# CPU usage (Utilization)
1 - avg(rate(node_cpu_seconds_total{mode="idle"}[$__rate_interval]))
# Load / cores (Saturation)
node_load1 / count(node_cpu_seconds_total{mode="idle"})
# Available memory ratio
node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes
# Redis commands per second
sum(rate(redis_commands_processed_total[$__rate_interval]))
# Redis memory and client count
redis_memory_used_bytes
redis_connected_clientspython3 -m json.tool grafana/dashboards/node-redis.json > /dev/null && git add -A && git commit -qm "hour1: node-redis dashboard" && git log --oneline | head -3
# A: sed -i 's/myapp:5000/myapp:5050/' prometheus/prometheus.yml && curl -s -X POST 127.0.0.1:9090/-/reload # B: docker compose stop redis-exporter # C: docker compose stop redis # D: in the RED dashboard panel query, change route=~"$route" to route="$route", then multi-select two routes
Reference answers: A → myapp target down,connection refused; B → redis job down,no such host; C → all targets up, but redis_up and myapp_redis_up is 0, and RED's Errors stays unchanged; D → scraping and queries work fine, and Query inspector shows route="(/|/slow)". Restore the original state after locating the fault.
kill %1 (stop loadgen), then run docker compose stop. Do not down -v, or Grafana and Prometheus data will be lost.Open-ended self-check (answer on your own first, then expand the reference answer)
1. What is the biggest operational advantage of the pull model over the push model? What is its cost?
Advantage: Prometheus knows the target list, and every failed scrape is written as up=0, so “target down” is itself alertable data; the target does not need to know the monitoring system's address. Cost: Prometheus must be able to reach the target (behind a firewall or NAT you need an Agent + remote_write); short-lived jobs may not be scraped (use Pushgateway / textfile).
2. In order, describe the steps of one scrape cycle.
Service discovery → relabel_configs (can drop targets) → set instance, remove __ labels → schedule with offset → HTTP GET (Accept negotiation, timeout header) → parse by Content-Type → metric_relabel_configs → attach target labels (honor_labels handles conflicts) → check limits → transactionally write to head and WAL → write synthetic metrics up/scrape_* → write staleness markers for series that disappeared.
3. Why must you “rate first, then sum”?
rate has to detect resets on each raw counter; if you sum first and then rate, one instance's reset only shows up as a drop in the total, which is treated as a whole-series reset, adding the entire sum back and producing a huge spike.
4. increase(x[1m]) Why does it return decimals like 93.3?
increase = observed increase within the window (including reset compensation) × (sampled span + extrapolated distance on both sides) / sampled span. Samples do not fall exactly on the window boundaries, so the extrapolation ratio is usually not an integer. In 3.16 you can use the anchored modifier to get an integer increase with no extrapolation.
5. How is Grafana's $__rate_interval calculated? Why must the data source's Scrape interval be set correctly?
max($__interval + scrape_interval, 4 × scrape_interval). scrape_interval is taken from the panel's Min interval or the data source's Scrape interval (default 15s); setting it wrong (e.g., actually scraping every 60s but keeping 15s) makes the window contain fewer than 2 samples, causing gaps.
6. Why does myapp use prometheus_client multiprocess mode? What limitations does it introduce?
Multiple gunicorn workers run as separate processes, and the default registry sees only the counts of the worker that received /metrics Multiprocess mode has each worker write mmap files, which MultiProcessCollector aggregates. Limitations: requires PROMETHEUS_MULTIPROC_DIR and the directory must be cleared before every start; no custom collectors (no process_*) and Gauge must choose multiprocess_mode, and it does not support Info/Enum/exemplar/Pushgateway; HELP shows as “Multiprocess metric”.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified findings | Source (accessed 2026-11-15) |
|---|---|---|
| Prometheus versions | Latest v3.16.0 (2026-11-05); v3.15.1 (2026-10-21); latest in the LTS 3.13 series is v3.13.5 (2026-10-21), and the 3.13.0 release notes label it Long Term Support; the previous LTS was 3.5 | prometheus/prometheus releases · Release cycle |
| Prometheus 3.x changes | 3.0: new UI, UTF-8 names by default, range selectors and lookback left-open, removed the implicit fallback for unknown Content-Type and added fallback_scrape_protocol, Agent mode became stable (--agent), automatic GOMAXPROCS/GOMEMLIMIT; 3.7: anchored/smoothed experimental; 3.8: native histograms became stable, added scrape_native_histograms; 3.9: native-histogram feature flags became no-ops; 3.10: distroless image variant (UID 65532), busybox still the default; 3.12: configuration auto-reload stable; 3.14: first_over_time stable, duration expressions enabled by default; 3.15: deprecated --log.level; 3.16: anchored/smoothed stable | Release notes for each version on GitHub |
| rate() algorithm | extrapolatedRate: ≥2 samples, reset compensation, 1.1× average interval threshold, otherwise extrapolate half an interval, counter zero-point truncation,factor /= range | promql/functions.go @ v3.16.0 · Query functions |
| Scrape mechanics | Default scrape_protocols order (OM 1.0.0 → OM 0.0.1 → text 1.0.0 → text 0.0.4; with native histograms enabled, protobuf takes priority); Accept header weights; X-Prometheus-Scrape-Timeout-Seconds; scrape offset by target hash; error text server returned HTTP status …,received unsupported Content-Type … no fallback_scrape_protocol specified for target; global defaults 1m/10s/1m | scrape/scrape.go,scrape/target.go,config/config.go,model/textparse/interface.go @ v3.16.0 · Configuration |
| PromQL details | regex fully anchored; lookback defaults to 5m (--query.lookback-delta); anchored and smoothed semantics; in rules they need query_offset | Querying basics |
| Alertmanager | v0.35.0 (2026-11-09) | alertmanager releases |
| Exporter | node_exporter v1.12.1 (2026-07-14); blackbox_exporter v0.29.1 (2026-10-21, used in Lesson 5); redis_exporter v1.97.0 (2026-11-04) | node_exporter · redis_exporter |
| Grafana | Latest 13.3.1 (2026-11-10, same day as 13.2.6 / 13.1.10 / 13.0.13 / 12.4.15); 13.0: dynamic dashboards GA and enabled by default, Git Sync GA, restore deleted dashboards GA, new Gauge GA; starting with 12.4.0, the image is grafana/grafana; $__rate_interval = max($__interval + scrape_interval, 4 × scrape_interval) | grafana releases · What's new in v13.0 · Docker installation · Prometheus template variables |
| prometheus_client (Python) | 0.26.0 (2026-07-24); multiprocess mode requirements and limitations,CollectorRegistry(support_collectors_without_names=True),mark_process_dead, Gauge multiprocess_mode (including livemostrecent); CONTENT_TYPE_LATEST = text/plain; version=1.0.0; charset=utf-8; during multiprocess aggregation HELP is “Multiprocess metric”; the environment variable being set is enough to enter multiprocess mode | Multiprocess mode docs · source code registry.py,exposition.py,multiprocess.py,values.py @ v0.26.0 |
| Image tags | Confirmed to exist on Docker Hub: prom/prometheus:v3.16.0,prom/alertmanager:v0.35.0,grafana/grafana:13.3.1,prom/node-exporter:v1.12.1,oliver006/redis_exporter:v1.97.0,python:3.13-slim; the latest stable Redis is 8.10.x, and this lesson keeps the Docker lesson's redis:7-alpine | Docker Hub tags API |
| myapp dependencies | Carried over from the Docker lesson: flask==3.1.*,redis==5.*,gunicorn==23.* (newer major versions are already on PyPI, kept for consistency with earlier lessons); added prometheus-client==0.26.* | PyPI · same repository as the Docker lesson |
Video verification notes
The following videos were verified on 2026-11-15 via the YouTube oEmbed API for title and channel: TechWorld with Nana, “How Prometheus Monitoring works | Prometheus Architecture explained” (h4Sl21AKiDg) and “Prometheus Monitoring - Steps to monitor third-party apps using Prometheus Exporter | Part 2” (mLPg49b33sA); Prometheus Monitoring with Julius | PromLabs, “Introduction to the Prometheus Monitoring System | Key Concepts and Features” (STVMGrYIlfg), “Understanding Prometheus Metric Types | Meaning and Usage (Gauge, Counter, Summary, Histogram)” (fhx0ehppMGM), and “Creating Grafana Dashboards for Prometheus | Grafana Setup & Simple Dashboard (Chart, Gauge, Table)” (EGgtJUjky8w); GOTO Conferences, “An Introduction to Systems & Service Monitoring with Prometheus • Julius Volz • GOTO 2019” (5O1djJ13gRU); CNCF, “Intro + Deep Dive: Prometheus - Julius Volz, Prometheus & Richard Hartmann, SpaceNet” (9GMWvFcQjYI); Grafana, “What is Observability? | Grafana for Beginners Ep. 1” (TQur9GJHIIQ); Christian Lempa, “Server Monitoring // Prometheus and Grafana Tutorial” (9TJx7QTrTyo); Eddie Zaneski, “Setting up Prometheus and Grafana for monitoring your servers” (4WWW2ZLEg74); edureka!, “Prometheus Tutorial | Monitoring with Prometheus And Grafana | Prometheus Grafana Tutorial | Edureka” (7gW5pSM6dlU) and “Grafana Tutorial For Beginners | Continuous Monitoring With Grafana | DevOps Training | Edureka” (w-c3KYKQQfs). oEmbed does not return durations or publish dates, so no durations are listed on the cards. Most of these videos were recorded in the Prometheus 2.x / older Grafana era; where they differ from 3.x and Grafana 13, this lesson takes precedence. No verified videos were found on the rate() extrapolation algorithm, the two-stage relabel process, client_python multiprocess mode, or Grafana 13 dynamic dashboards; the relevant modules provide storyboard scripts instead.
Narration notes
The “Narration” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US. Results depend on the voices installed on the operating system. This lesson has no embedded MP3; for offline audio, send the narration script to a TTS service.
Known limitations
- Commands in this lesson have not actually been executed in this environment; the numbers, IPs, timestamps, PIDs, series counts, Go version numbers and some error text in “Expected output” are sample values; your actual output takes precedence.
- The “Release cycle” page on prometheus.io could not be parsed directly for the LTS list at verification time; the LTS conclusions come from the GitHub release notes for 3.13.0 and 3.5.0.
- The Grafana 13 UI text, menu locations and dashboard JSON structure (dynamic dashboard schema) may change between minor versions; the dashboard JSON provided in this lesson uses the classic structure (
schemaVersion41), relying on Grafana's automatic migration and not actually imported and verified on 13.3.1. For the full list of breaking changes in Grafana 13.0, see the official upgrade guide. - This lesson is written for the latest Grafana 13.3.1 at the time of verification; UI locations in 12.x may differ slightly.
- node-exporter runs in the Compose network (not
network_mode: host), so network metrics reflect the container's network interfaces; on Docker Desktop you see the Docker VM rather than the host machine. - The rate calculator in Module 4 and the quantile visualization in Module 5 are implemented following the v3.16.0 source logic and cover the classic path for float counters; they do not cover native histograms,
use-start-timestampsfeatures andanchored/smoothedcalculation details. The interval calculator in Module 6 simplifies Grafana's rounding rules. - myapp uses classic histograms; the Python client 0.26's
Histogramdoes not output native histograms; see Lesson 7 for the migration discussion. - In the lab environment, Prometheus and Alertmanager have no authentication and Grafana uses a plaintext lab password; they bind only to 127.0.0.1. Never expose them to the public internet.