Prometheus & Grafana Hour 1: Core Fundamentals

From “installing Grafana to look at graphs” to “being able to explain where every number comes from”: the pull model, the data model, the scrape cycle, PromQL, the real algorithm behind rate(), Grafana's data flow, and your first RED dashboard
Prometheus v3.16.0Grafana 13.3.1Alertmanager v0.35.0node_exporter v1.12.1Native Histograms stable (since 3.8)Verified against prometheus.io / grafana.com / GitHub · 2026-11-15
Prerequisites This lesson assumes you have completed Docker 8-hour crash course(images, Compose, named volumes, custom networks, and the sample app myapp: Flask + gunicorn + Redis counter),Kubernetes 8 + 1 hour crash courseand Helm 8-hour crash course. The K8s courseLesson 6covered metrics-server, HPA and 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.
Overall learning objectives
  • 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_histograms before 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 → attach job/instance the target labels → write to the head block and WAL → generate up,scrape_duration_seconds and other synthetic metrics → series that disappear are written a staleness marker.
  • Use prometheus_client to 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_left joins and subqueries; be able to hand-calculate one rate() (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,$__interval and $__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

#TimeModuleCore contentAnimation / interactionLab (~/promlab)
0Before classEnvironment setupCreate ~/promlab: the seven Compose services, the instrumented myapp, Prometheus / Alertmanager / Grafana configuration and provisioningEnvironment self-check checklistdocker compose up -d,promtool check config
100–06Monitoring and observability: architecture and the pull modelMonitoring vs observability, Prometheus components, pull vs push, changes in Prometheus 3, when to use it and when not toPull vs push comparison simulator (who finds out first when a target goes down)Prometheus UI,/api/v1/targets,up
206–13Metric types and data modelTime series and samples, text exposition format, counter / gauge / histogram / summary, naming and units, native histogramsMetric type playground: events → live changes in the exposition formatRead myapp's /metrics
313–21scrape configuration, exporters and application instrumentationscrape_configs, target labels, the two relabel stages, synthetic metrics, protocol negotiation, node_exporter, redis_exporter, client_python multi-processCore animation A: one complete scrape cycle (including the relabel drop and staleness marker branches)relabel rewriting labels, hot reload,promtool
421–28PromQL basics: selectors, rate and aggregationfour types, matchers, lookback,offset/@,rate/increase/irate, aggregationCore animation B: rate() calculator (resets, extrapolation, missing samples)QPS, error rate, Top-N queries
528–35PromQL advanced: histogram_quantile, joins and subqueriesquantile interpolation,sum by (le), vector matching on/group_left,absent,predict_linear, subquerieshistogram_quantile interpolation visualizationP95 latency, joins with version information
635–42Grafana architecture: data sources, dashboards and panelsGrafana backend and database, data source proxy, query path,$__interval/$__rate_interval, provisioning, changes in Grafana 13panel query path + interval calculatorAPI data source checks, Explore
742–50Building your first dashboard: variables and the RED methodRED / USE, variables, units and thresholds, heatmap, dashboard JSON and file provisioningRED dashboard fault injection simulatorImporting the myapp RED dashboard
850–60myapp observability readiness and troubleshooting basicsReadiness checklist; for six common failures, the symptom → root cause → fixFailure reproduction simulator + interactive troubleshooting treeInject faults and fix them
—After classCheat sheet · Integrated labAdd /slow latency observability and node and Redis panels for myapp, and write acceptance queriesFinal quiz (12 questions)Integrated lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / queriesLab
Explain the Prometheus architecture and the pull model✓·✓····✓up,/api/v1/targetsM1 targets page
Read the data model and metric types·✓✓✓✓···curl :5000/metricsM2 interpret the exposition format
Configure scraping and relabel··✓····✓promtool check config,POST /-/reloadM3 relabel
Application instrumentation and exporters·✓✓····✓prometheus_client multi-processEnvironment setup + M3
PromQL: rate and aggregation···✓✓✓✓✓sum by (route) (rate(...[5m]))M4 queries
Quantiles, joins and subqueries····✓·✓·histogram_quantile,group_leftM5 P95
Grafana data sources and panel mechanics·····✓✓✓$__rate_interval,/api/datasourcesM6 Explore
RED dashboard and variables·····✓✓✓label_values(), provisioningM7 dashboard
Troubleshooting common collection and display problems✓·✓✓·✓·✓up == 0,scrape_duration_secondsM8 fault injection

Topics not covered in this lesson (and where to learn them)

TopicWhy it is not in this lessonWhere to learn it
Recording rules, alerting rules, Alertmanager routing / inhibition / silences, notification channels, Grafana AlertingThis lesson only deploys Alertmanager and connects it; alerting is a full topic in its own rightLesson 2
Storage capacity planning, retention policies, and an in-depth look at TSDB internals (head / WAL / compaction)This lesson only introduces the conceptsLesson 2 Module 7, Lesson 7 Module 5
Azure Monitor managed Prometheus / Azure Managed Grafana, AMP / AMGcloud-hosted servicesLessons 3 and 4
Prometheus Operator on Kubernetes, ServiceMonitor, kube-prometheus-stack, Grafana as codeRequires the local mechanisms to be understood firstLesson 5
High availability, federation, remote write, Thanos / Mimir, SLOs and burn rateArchitecture topicsLesson 6
Cardinality explosion, slow query optimization, deep dives into scrape failuresThis lesson only covers introductory troubleshootingLesson 7
Logs (Loki), distributed tracing (Tempo), profilingThis course focuses on metrics; the relationship between OpenTelemetry and Prometheus is covered in Lesson 6Lesson 6 Module 6; Grafana official documentation
Docker / Compose itself, metrics-server and HPAPrerequisitesDocker course · K8s course Lesson 6

How to use this courseware

The 10 pages of each module
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.
Learning progress
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).
Chinese narration
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.
Version notes This lesson uses Prometheus v3.16.0 (released 2026-11-05) as its baseline; the current long-term support (LTS) release is 3.13 series (latest patch 3.13.5, 2026-10-21). For production environments where stability matters more, choose LTS. Grafana The latest is 13.3.1 (2026-11-10; patches 13.2.6, 13.1.10, 13.0.13 and 12.4.15 were released the same day). This lesson is written for 13.x; readers still on 12.x will mainly notice differences in the dashboard editor UI. Other components: Alertmanager v0.35.0, node_exporter v1.12.1, redis_exporter v1.97.0, Python client prometheus_client 0.26.0. Since Grafana 12.4.0, the Docker image has been unified as grafana/grafana (grafana/grafana-oss is no longer updated).

Module 0 · Environment setup (Docker Compose: Prometheus + Grafana + myapp)

Create the lab directory ~/promlab shared by Lessons 1 and 2 of this series: seven services, one instrumented myapp, three configuration files and Grafana provisioning
Before class ≈ 20 minutesDocker Engine 29 + Compose v2Free, runs locally
Prerequisites
  • 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). promtool and amtool do 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,/metrics and two routes that produce latency and errors /slow,/error, with the port standardized as 5000, and rebuilt as myapp:1.0 (instrumented version). myapp:1.1 Reserved 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)ImagePortPurpose
prometheusprom/prometheus:v3.16.09090Scraping, storage, queries, rule evaluation
alertmanagerprom/alertmanager:v0.35.09093Alert grouping, routing and notification (this lesson only connects it; configured in Lesson 2)
grafanagrafana/grafana:13.3.13000Visualization; data sources and dashboards are provisioned through files
node-exporterprom/node-exporter:v1.12.19100Host CPU, memory, disk and network metrics
myappmyapp:1.0 (built locally)5000Sample application,/metrics exposing metrics via prometheus_client
redisredis:7-alpine (same as the Docker course)6379 (not published)myapp's counter storage
redis-exporteroliver006/redis_exporter:v1.97.09121Converts 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
Step 1: create the directory and write the myapp application code
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.

Step 2: gunicorn configuration, dependencies and Dockerfile
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.

Step 3: Prometheus configuration
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
EOF
Step 4: minimal Alertmanager configuration and Grafana provisioning
cat > 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
EOF
Step 5: Compose file (shared by Lessons 1 and 2 of this series)
cat > 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).

Step 6: traffic script, validate configuration, start
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.

Step 7: confirm all 6 scrape targets are up
./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

Cleanup (after class, or when you want to start over)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

00:00 – 06:00 · A time series database that actively "comes to collect the data": it knows first who is online and who has gone offline
6 minPrometheus 3.x · CNCF graduated project★★★★☆
Learning objectives
  • 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.
Prerequisites: Compose networking and DNS from the Docker course. Importance:★★★★☆ (the mental model for all the modules that follow)

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.

SignalData shapeBest at answeringTypical toolsCost
MetricsNumeric time series (name + labels + sample points)"How much, how fast, how long": QPS, error rate, P95 latency, saturation; trends and alertsPrometheus, Mimir, Thanos, Azure Monitor / AMPCheapest: each sample of each series compresses to about 1–2 bytes; but individual request details are not kept
LogsTimestamped event text / structured records"What exactly happened": exception stacks, request parameters, audit trailsLoki, Elasticsearch, Azure Log AnalyticsBilled by data volume; expensive at high volume
Distributed tracesThe span tree of one request across services"Which hop is slow": call chains and dependenciesTempo, Jaeger, OpenTelemetryUsually 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 up metrics.
  • 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

  1. Service discovery (SD): static_configs,file_sd_configs,kubernetes_sd_configs,azure_sd_configs,ec2_sd_configs etc. produce "target groups": a set of addresses + metadata labels (__meta_*).
  2. Scraping (scrape): each target has its own scrape loop, and every scrape_interval sends 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).
  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).
  4. 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.
  5. Rules: the rule manager evaluates every evaluation_interval recording rules (precomputed, written back to the TSDB) and alerting rules (when the condition holds continuously for the for period, the alert is pushed to Alertmanager).
  6. 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

ScenarioSuitable?Reason / alternative
Health, performance, capacity trends and alerting for services and infrastructure✓ First choiceThis 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)

Area2.x3.xImpact on you
Web UIOld React UINew UI (tree-style PromQL explanation, metrics explorer)Screenshots differ from older tutorials
Metric and label namesOnly [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"} quotesApplications should still use traditional naming to avoid incompatibility with downstream tools
Range selectors and lookbackClosed on both endsOpen on the left, closed on the right: samples exactly at the start of the window are no longer includedResults of a very few boundary queries may change
Scrape Content-TypeFalls back to the text format when unrecognizedNo longer falls back implicitly; the scrape fails. It can be set with fallback_scrape_protocol(see the Module 8 troubleshooting case)
Agent modeFeature flagStable; use --agent to start (scraping + remote write only, no queries)Edge / multi-cluster collection
Native histogramExperimentalStable since 3.8; but it must be set in the scrape configuration scrape_native_histograms: trueModule 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 stableLessons 6 and 7
Common misconceptions① "Prometheus is push-based, and applications send data to it" — the default is pull; push is used only at specific entry points such as Pushgateway, the remote write receiver and the OTLP receiver. ② "Prometheus provides long-term storage and high availability" — a single instance stores only on local disk and does not replicate; HA is achieved by running two identically configured instances that scrape in parallel, and long-term storage uses remote write (Lesson 6). ③ "Grafana stores metric data" — Grafana only stores dashboards, users and data source configuration; the metrics always stay in Prometheus, and Grafana re-queries on every refresh. ④ "The finer the metrics, the better, so put user_id into a label" — every distinct label value combination is a new series, and high cardinality makes memory balloon (Lesson 7).

Architecture diagram: Prometheus ecosystem components

Scrape targets myapp /metrics (instrumented) node-exporter :9100 redis-exporter :9121 Short-lived jobs → Pushgateway Service discovery static / file / DNSkubernetes / azure / ec2consul / http … Prometheus server (single binary) RetrievalScrape loop + relabel TSDBhead + WAL + blocks Rule managerRecording / alerting rules PromQL engineQuery execution HTTP API /api/v1/* + Web UI :9090 Local disk /prometheus wal/ · chunks_head/ · 01J… (2h block)Default retention 15d · no replication remote write → Mimir / Thanos / managed service HTTP GET Alertmanager :9093Grouping / inhibition / silencing / routing→ Email · Teams · PagerDuty push alerts Grafana :3000Data source proxy → PromQLDashboards / Explore API clientscurl / promtool / scripts
Figure 1-1: Prometheus actively pulls data from targets; Grafana and alerts both read through PromQL; Alertmanager is a separate process

Comparison diagram: pull vs push

Pull: Prometheus Prometheusknows the target list target A ✓ target B ✗ B pull fails → the next round immediately records up{instance="B"} = 0 Push: StatsD / OTLP push / remote write agent A agent B (dead) collectorpassive reception B is silent: did it die, did the network go down, or was there never any traffic? A "missing heartbeat" alert is needed
Figure 1-2: the pull model turns "is the target healthy" into a metric that can be queried and alerted on

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.

Prometheust = 0s myapp:5000 node-exporter:9100 redis-exporter:9121 Push model collector myapp last push: 0s ago Heartbeat timeout threshold: 60s Status: normal

Core commands and APIs

Command / endpointPurposeKey parameters / notes
GET /-/healthy,/-/readyLiveness / readiness checksDuring WAL replay at startup /-/ready returns 503
GET /api/v1/status/buildinfoVersion, Go version, build informationequivalent to prometheus_build_info metrics
GET /api/v1/targetsStatus of all targets, last error, scrape duration?state=active|dropped|any
GET /api/v1/query?query=upInstant querytime= specify the evaluation time
GET /api/v1/status/flags,/configStartup flags and configuration currently in effectCheck whether the configuration was actually loaded
POST /-/reloadHot-reload configurationrequires --web.enable-lifecycle; you can also send SIGHUP to the process
promtool check configValidate the configuration and the rule files it referencesMust 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)

Open the Targets page: in your browser, go to 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.
On the Query page, run (switch to the Graph tab):
up
count by (job) (up)
scrape_duration_seconds

Every target has these "synthetic metrics", even if the application itself exposes no metrics at all.

Take one target down and watch how up changes
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.

Restore
docker compose start redis-exporter
View TSDB status: open 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).

Command-line exercises
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).

Scenario analysis
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

▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · A classic introduction to architecture and the pull model (recorded in the Prometheus 2.x era; for UI and 3.x changes, follow this lesson)
▶
Introduction to the Prometheus Monitoring System | Key Concepts and Features — Prometheus Monitoring with Julius | PromLabs
English · Prometheus co-founder Julius Volz explains the core concepts
▶
An Introduction to Systems & Service Monitoring with Prometheus • Julius Volz • GOTO 2019 — GOTO Conferences
English · Conference talk explaining monitoring philosophy and the trade-offs of the pull model
▶
What is Observability? | Grafana for Beginners Ep. 1 — Grafana
English · Grafana Labs official channel, on the difference between monitoring and observability

Official documentation

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.

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

Module 2 · Metric types and the data model: counter, gauge, histogram, summary

06:00 – 13:00 · Everything is "name + labels + (timestamp, value)"; the type only determines which function you use to read it
7 minOpenMetrics / text formatNative histograms stable (3.8+)★★★★★
Learning objectives
  • 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.
Prerequisites: Module 1. Importance:★★★★★ (choosing the wrong type makes every query that follows wrong)

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

TypeMeaningExampleCorrect usageIncorrect usage
CounterA cumulative value that only goes up; resets to zero on process restartmyapp_http_requests_total,node_network_receive_bytes_totalrate(),increase() then aggregatePlot the raw value; using a counter for something that can decrease
GaugeThe current value, which can go up or downmyapp_redis_up,node_memory_MemAvailable_bytes, queue length, temperatureRead it directly; avg_over_time,max_over_time,deriv,predict_linearusing rate()
HistogramCounts observations into preset buckets (classic: one counter series per bucket)myapp_http_request_duration_secondshistogram_quantile(0.95, sum by (le) (rate(..._bucket[5m]))); average = rate(_sum)/rate(_count)Bucket boundaries unrelated to the SLO; forgetting sum by (le)
SummaryQuantiles computed directly on the client (sliding time window)Go runtime's go_gc_duration_secondsLooking 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 _created series: in single-process mode the Python client also emits _created timestamps 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 as myapp_http_requests, and adds _total when exposing it.

Naming conventions (official best practices)

RuleGoodBad
Application / domain prefixmyapp_http_requests_totalrequests
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 boundedroute="/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.

Common misconceptions① "A counter never gets smaller" — it goes back to zero after a process restart. 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

Series identity (label set, hashed after sorting) __name__="myapp_http_requests_total" job="myapp" instance="myapp:5000" (added at scrape time) method="GET" route="/" status="200" (output by the application) Sample stream (one every 15s) (1794736800000, 1780) (…815000, 1805) (…830000, 1823) (…845000, 1842) … timestamp int64 ms · value float64 (Gorilla / XOR compression) Cardinality: number of series = number of label value combinations counter: method(2) × route(5) × status(3) ≈ 30 series (only combinations that actually occur are stored) histogram: method(2) × route(5) × (10 buckets + +Inf + _sum + _count = 13) = 130 series per instance If user_id (100,000 values) is used as a label: × 100000 → memory and queries blow up completely
Figure 2-1: in Prometheus, "one metric" is often hundreds or thousands of series

Classic histogram buckets (cumulative counts)

0.00540 0.0162 0.02575 0.0581 0.185 0.2590 0.595 198 …5 / +Inf100 = _count Each bucket = "number of observations ≤ le", which never decreases; the 95th request falls in the (0.25, 0.5] bucket → P95 ≈ 0.5
Figure 2-2: each bucket of a classic histogram is one counter series; Module 5 explains the interpolation in detail

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.

Click the buttons above to generate events.

      

Inspect and understand the exposition format

CommandPurposeNotes
curl -s 127.0.0.1:5000/metricsLook at the application output directlyThe fastest check that instrumentation is working
curl -sI -H 'Accept: application/openmetrics-text' …Check Content-Typemyapp always returns this lesson's fixed value text/plain; version=1.0.0
promtool check metricsCheck the exposition format against best practices (naming, units, HELP)Read from stdin
/api/v1/metadata?metric=…The type, HELP and unit recorded by PrometheusThe 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)

Generate a known number of requests by hand and verify the counter
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
Verify the cumulative nature of the histogram:
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.

Verify the gauge and the Redis dependency
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.

Look at a summary (from Prometheus itself, written in Go):
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 247

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

Command-line exercises
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.

Scenario analysis
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

▶
Understanding Prometheus Metric Types | Meaning and Usage (Gauge, Counter, Summary, Histogram) — Prometheus Monitoring with Julius | PromLabs
English · the semantics and usage of the four types, fully matching this module
▶
Introduction to the Prometheus Monitoring System | Key Concepts and Features — Prometheus Monitoring with Julius | PromLabs
English · the data model section

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.

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

Module 3 · Scrape configuration, exporters and application instrumentation

13:00 – 21:00 · What happens every 15 seconds: discover targets, rewrite labels, HTTP GET, parse, write to the head and WAL
8 minscrape_config · relabelCore animation A★★★★★
Learning objectives
  • 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) and metric_relabel_configs (after scraping and before storage, acting on each sample); master replace,keep,drop,labelmap,labeldrop actions.
  • 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.
Prerequisites: Modules 1 and 2. Importance:★★★★★ (all collection problems happen here)

What: the components of a scrape configuration

FieldDefaultDescription
job_nameRequiredbecomes a target label job; globally unique
scrape_interval / scrape_timeoutinherits from global (global defaults: 1m / 10s)the timeout must be ≤ the interval; this lesson uses 15s / 10s
metrics_path / scheme / params/metrics / http / nonethe 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_configsnonerewrite / filter targets before scraping
metric_relabel_configsnonerewrite / drop samples after scraping (the last fuse; the cost of scraping and parsing has already been paid)
honor_labelsfalseWhen 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_limit0 (unlimited)if exceeded,the entire scrape fails,up=0; a fuse that prevents cardinality explosion
scrape_protocols / fallback_scrape_protocolOpenMetrics 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_histogramsfalsethe native histogram scraping switch, stable since 3.8

How: the internal steps of one scrape cycle

  1. 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" and labels: the ones written in env,service.
  2. relabel_configs Executed in order; if any step keep/drop decides to drop a target, the target enters "dropped targets" (visible in /api/v1/targets?state=dropped ), and it is not scraped.
  3. 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).
  4. 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.
  5. HTTP GET: the request headers include Accept (negotiated with scrape_protocols weights),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.
  6. 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.
  7. metric_relabel_configs Executed for each sample; it can be dropped or rewritten; then attaches target labels (job,instance,env...), conflicts are handled by honor_labels ; checks sample_limit and other limits.
  8. 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.
  9. 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.
  10. 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 foryour own codesoftware you cannot change: the Linux kernel, Redis, PostgreSQL, hardware
How it worksthe application keeps counters inside the process,/metrics and outputs them whena separate process; when it receives a scrape request,synchronously reads the target (/proc, Redis INFO, SQL queries) and translates it into metrics
up meaningwhether the application itself is scrapablewhether the exporter is scrapable; whether the monitored object is available is checked through the exporter's own metrics (redis_up,pg_up)
Deploymentno extra processusually 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 use set_function; Info and Enum are not available; Pushgateway cannot be used; exemplars are not supported.
  • Gauge requires choosing multiprocess_mode: the default all (one series per process, with a pid label),min/max/sum/mostrecent, and the variant that considers only live processes, live* . myapp uses myapp_redis_up uses livemostrecent.
Common misconceptions① "metric_relabel_configs reduces scraping overhead" — no; it runs after scraping and parsing and only reduces what is stored. To reduce scraping overhead, disable collectors on the exporter side. ② "relabel regexes are partial matches" — Prometheus relabel regexes are fully anchored (equivalent to ^(?: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

Service discovery__address____meta_* relabel_configsacts on targetscan drop targets HTTP GET/metrics Parsing metric_relabelacts on each sample+ attach target labels TSDBhead + WAL dropped targets (not scraped) dropped samples (scraping cost already paid) available: __meta_*, __address__, __param_* available: __name__ and sample labels
Figure 3-1: the earlier you drop, the cheaper it is. Exclude targets in the relabel_configs stage rather than waiting for metric_relabel

Process structure of myapp instrumentation (gunicorn multi-process)

gunicorn masteron_starting: empty the directory worker pid 7 (Flask app) worker pid 8 (Flask app) /tmp/prom-multiproc counter_7.db · counter_8.dbhistogram_7.db · histogram_8.dbgauge_livemostrecent_7.db … mmap write GET /metricslands on any one workerMultiProcessCollectorread all files and sum them
Figure 3-2: without multi-process mode, each scrape sees only the counts of "whichever worker happened to get the request", so the numbers jump back and forth

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.

Service discoverytarget group relabeltarget labels Schedulingoffset HTTP GET/metrics ParsingContent-Type metric_relabel+ target labels head + WALAppend and commit Synthetic metricsup · staleness marker

Scrape configuration commands

CommandPurposeDescription
promtool check config prometheus.ymlStatic validationalso checks rule_files the rule files it references
curl -X POST :9090/-/reloadHot reloadOn failure, the old configuration is kept; look at prometheus_config_last_reload_successful
/api/v1/targets?state=droppedtargets dropped by relabel, along with their original labelsa handy tool for debugging keep / drop rules
/api/v1/targets/metadatametric metadata exposed by each target?match_target={job="myapp"}
promtool query instantrun PromQL from the command lineacceptance assertions in CI
curl -s :9100/metrics | grep ^node_look at the exporter output directlyrule 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.

First, record a baseline: how many samples does the node job return per scrape?
scrape_samples_post_metric_relabeling{job="node"}
count({job="node", __name__=~"node_scrape_collector_.*"})
1093
96
Edit the configuration: add a label derived from the address to myapp ( 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.

Validate and hot-reload
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"}
Verify the effect of metric_relabel
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.

Observe a dropped target (temporary experiment, delete afterwards): at the end of 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).

See the exporter's "synchronous translation": redis_exporter only runs its queries when it receives a scrape 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 1

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

Command-line exercises
1. Write a relabel rule that keeps only targets that have env="lab" the target label.
relabel_configs:
  - source_labels: [env]
    regex: lab
    action: keep
2. 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
Scenario analysis
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

▶
Prometheus Monitoring - Steps to monitor third-party apps using Prometheus Exporter | Part 2 — TechWorld with Nana
English · Exporter concepts and deployment (examples based on Kubernetes)
▶
Server Monitoring // Prometheus and Grafana Tutorial — Christian Lempa
English · Deploying Prometheus, node_exporter and Grafana with Docker Compose, close to this lesson's lab approach
▶
Intro + Deep Dive: Prometheus - Julius Volz, Prometheus & Richard Hartmann, SpaceNet — CNCF [Cloud Native Computing Foundation]
English · KubeCon maintainer talk covering the scraping and service discovery mechanisms

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

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.

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

Module 4 · PromQL basics: selectors, rate and aggregation

21:00 – 28:00 · Rate first, then sum; rate is not "subtract two points and divide by time" but an estimate with reset compensation and boundary extrapolation
7 minPromQL · Prometheus 3.16Core animation B★★★★★
Learning objectives
  • 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 between increase and irate .
  • Use the aggregation operators sum/avg/max/count/topk plus by/without to write QPS, error rate and Top-N queries, following "rate first, then sum".
Prerequisites: Modules 2 and 3. Importance:★★★★★

What: the four types of expressions

TypeExampleMeaningCan it be plotted directly?
Instant vector instant vectormyapp_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 vectormyapp_http_requests_total[5m]for each series, over (t-5m, t] the all samples✗ (must be passed to rate and similar functions)
Scalar0.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); @ 1794736800 or @ 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)

  1. 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).
  2. 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).
  3. sampledInterval = last timestamp − first timestamp; avg = sampledInterval / (number of samples − 1); threshold = 1.1 × avg.
  4. 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 by avg / 2; otherwise extrapolate to the boundary.
  5. A counter is not extrapolated below zero: if result > 0 and the first value is ≥ 0, compute durationToZero = sampledInterval × (first value / result); if it is smaller than durationToStart , use it (the case of a new series starting from 0).
  6. 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
OperatorExampleDescription
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,countcount by (job) (up == 1)count count the number of series
topk(k, …),bottomktopk(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 seriesis not histogram_quantile
Comparison / filteringup == 0,... > 0.05by 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.

Common misconceptions① "rate(x[5m]) is the last value minus the first value over the last 5 minutes, divided by 300" — it also includes reset compensation and extrapolation. ② "increase returns integers" — extrapolation often makes it a decimal. ③ "an empty query result = value 0" — empty means there are no series (for example, fewer than 2 samples in the window, or a 500 status code has never appeared); error-rate queries must handle this case (Module 5's 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

t-6mt x[5m] → range vector: all samples in (t-5m, t] (open on the left, closed on the right) x → at 800 instant vector: the latest sample before evaluation time t (looking back at most 5 minutes, the lookback) range query = repeat the instant query at every step between start…end
Figure 4-1: range vectors cannot be plotted directly; they must be passed to rate / increase / *_over_time to become instant vectors

rate() extrapolation diagram

window start t-1m (excluded)evaluation time t 3s12s sample interval 15s, threshold 16.5s; both sides are within the threshold → extrapolate to the boundaries: increase = Δ × 60/45
Figure 4-2: Prometheus assumes evenly distributed samples and scales the increase observed within the window proportionally up to the whole window

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

Window:

Common queries (run in the Prometheus UI or API)

PurposePromQL
myapp total QPSsum(rate(myapp_http_requests_total{job="myapp"}[5m]))
QPS by routesum by (route) (rate(myapp_http_requests_total[5m]))
5xx error ratesum(rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum(rate(myapp_http_requests_total[5m]))
requests in the past 1 hoursum(increase(myapp_http_requests_total[1h]))
average latencysum(rate(myapp_http_request_duration_seconds_sum[5m])) / sum(rate(myapp_http_request_duration_seconds_count[5m]))
CPU utilization1 - avg without (cpu, mode) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
Top 3 Redis commandstopk(3, rate(redis_commands_total[5m]))
compare with 1 hour agosum(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)

Look at the raw samples: in the Table view of the Prometheus UI, run a range selector (only the table can display range vectors):
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]).

Create a counter reset: restart myapp (the multi-process directory is emptied and all counters go back to zero)
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
Compare rate, irate, increase: switch to the Graph view, set the time range to 15 minutes, and run in turn
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.

Experience a window that is too small:
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).

Aggregation and filtering:
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.

Command-line exercises
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.

Scenario analysis
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

▶
Intro + Deep Dive: Prometheus - Julius Volz, Prometheus & Richard Hartmann, SpaceNet — CNCF [Cloud Native Computing Foundation]
English · the PromQL and data model parts
▶
Introduction to the Prometheus Monitoring System | Key Concepts and Features — Prometheus Monitoring with Julius | PromLabs
English · PromQL overview

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

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video or MP3 files; the storyboard and narration script are provided.

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

Module 5 · PromQL advanced: histogram_quantile, joins and subqueries

28:00 – 35:00 · Quantiles are estimates from interpolation within buckets; a "join" is a binary operation with label-matching rules
7 minPromQL★★★★☆
Learning objectives
  • Write correct P95 / P99 queries: histogram_quantile(0.95, sum by (le) (rate(..._bucket[5m]))), and explain linear interpolation within buckets,+Inf and 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 operations and/or/unless.
  • Know how to use absent(),predict_linear(),label_replace(),*_over_time() and subqueries expr[range:resolution], and know the cost of subqueries.
Prerequisites: Modules 2 and 4. Importance:★★★★☆

What: how histogram_quantile estimates quantiles

  1. The input is a set of series that carry the le label, grouped by the other labels (usually already processed with rate rate, meaning "the number of requests per second falling into each bucket over the last 5 minutes").
  2. Total = le="+Inf" the value of the bucket; target rank rank = φ × total.
  3. 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).
  4. 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 +Inf the +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").
  5. With fewer than 2 buckets, or no +Inf buckets, it returns NaN; for native histograms, pass the histogram series directly, with no need for le.
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 methodSyntaxRuleTypical use
One-to-one (default)a / bthe label sets on both sides are exactly the same series are paired; those that do not match are droppedError rate: use the same sum by
restrict matching labelsa / on(route) b,a / ignoring(status) bpair only by the listed labels (or ignoring the listed labels)the numerator has one more status label than the denominator
Many-to-onea * on(instance) group_left(nodename) bmany series on the left match one on the right; the labels listed from the right are copied to the resultUse *_info an info metric to "add" metadata labels to the result
Seta and b,a or b,a unless bintersection / 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

FunctionExampleDescription
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) < 0linear regression predicts the value t seconds ahead (gauge)
*_over_timemax_over_time(myapp_redis_up[10m])takes avg / min / max / last / quantile etc. of a gauge within a time window
label_replacelabel_replace(up, "host", "$1", "instance", "([^:]+):.*")with labels derived at query time (regexes are likewise fully anchored)
Subquerymax_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,roundclamp_max(x, 1)trimmed for display
histogram_count/sum/fractionhistogram_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).

Common misconceptions① "The result of histogram_quantile is the latency of some real request" — it is an interpolated estimate. ② "P99 = 5 means the slowest request took 5 seconds" — when the quantile falls in the +Inf bucket, it returns the upper bound of the highest finite bucket. ③ "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

≤0.140 ≤0.2560 ≤0.593 ≤1100 +Inf100 rank = 0.9 × 100 = 90 Falls in the (0.25, 0.5] bucket: previous bucket 60, this bucket 93 P90 = 0.25 + 0.25 × (90 − 60) / (93 − 60) = 0.25 + 0.25 × 0.909 ≈ 0.477 s Assumption: requests within the bucket are evenly distributed
Figure 5-1: precision depends on the bucket boundaries; placing a boundary at the SLO threshold makes "does it meet the SLO" exact

group_left: add labels to the result

Left: many series (one per CPU mode) rate(node_cpu_seconds_total{mode="user"}) 0.12rate(…{mode="system"}) 0.05Labels: instance, cpu, mode * on(instance)group_left(nodename)Many on the left : one on the right Right: one info series (value = 1) node_uname_info{instance,nodename="lab-vm", release="6.8.0"} 1 Result: the value comes from the left side, labels = left-side labels + nodename="lab-vm"
Figure 5-2: on() decides what to pair on; the labels inside group_left() are copied from the right

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.

φ =0.95

Advanced query checklist

PurposePromQL
P95 per routehistogram_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_upredis_up * on(instance) group_left(redis_version) redis_instance_info
whether the myapp target has disappearedabsent(up{job="myapp"})
whether the disk will be full in 4 hourspredict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0
peak QPS over the past 1 hourmax_over_time(sum(rate(myapp_http_requests_total[5m]))[1h:1m])
whether Redis has dropped out at any point in the past 10 minutesmin_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)

Create a peak of slow requests:
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".

On the Graph view, compare (time range 15 minutes):
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.

SLI: proportion completed within 250ms
sum(rate(myapp_http_request_duration_seconds_bucket{le="0.25"}[5m]))
  / sum(rate(myapp_http_request_duration_seconds_count[5m]))
0.8813
Joined query:
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"}  1
Find the peak with a subquery:
max_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.

Missing-data detection:
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.

Command-line exercises
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.

Scenario analysis
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

▶
Understanding Prometheus Metric Types | Meaning and Usage (Gauge, Counter, Summary, Histogram) — Prometheus Monitoring with Julius | PromLabs
English · the histogram and summary parts are prerequisites for this module

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.

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

Module 6 · Grafana architecture: data sources, dashboards and panels

35:00 – 42:00 · Grafana does not store metrics: every refresh is a PromQL range query proxied through the backend
7 minGrafana 13.3.1Dynamic dashboards GA (13.0)★★★★☆
Learning objectives
  • 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 $__interval and $__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).
Prerequisites: Range queries from Module 4. Importance:★★★★☆

What: what Grafana is and what it stores

ComponentResponsibilityLocation in this lab
Frontend (React single-page application)Dashboard editing, panel rendering, Explore, variable UIBrowser
Backend (Go)HTTP API, authentication and permissions,data source proxy and backend plugins, alerting engine, rendering service calls, provisioningContainer grafana
Databaseusers, organizations, teams, folders, dashboard JSON, data source configuration, alert rules, preferencesSQLite: /var/lib/grafana/grafana.db (production can use MySQL / PostgreSQL with HA)
Data sources (plugins)translate panel queries into API calls for the target systemPrometheus (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

  1. 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 provisioning jsonData.timeInterval, 15s in this lesson) or the panel's Min interval.
  2. Replace template variables: $route,$__rate_interval = max($__interval + scrape_interval, 4 × scrape_interval) (the formula given in the Grafana documentation).
  3. 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).
  4. The backend's Prometheus plugin calls POST http://prometheus:9090/api/v1/query_range, with parameters query,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.
  5. 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}}).
  6. 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"

MethodSuitable forNotes
Manual editing in the UIexploration, prototypingsaved in the database; easy to "drift", with no review
File provisioningthis lesson, simple GitOps/etc/grafana/provisioning/{datasources,dashboards,alerting,plugins}; loaded at startup; the dashboard directory is updateIntervalSeconds polled
HTTP API / Terraform provider / Grafonnetscale, multiple instancesLesson 5
Git Sync (Grafana 13.0 GA)edit in the UI and commit a PR directlytwo-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-oss is no longer updated); grafana/grafana-enterprise free to use, and includes all OSS features.
Common misconceptions① "The data source URL is localhost:9090" — the URL is accessed from the Grafana server (container), and inside the container localhost is Grafana itself; in Compose you should write 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

Browser Dashboards / panelscompute $__intervalreplace variablestransform + render Grafana server :3000 (Go) HTTP API/api/ds/query authentication / RBACsessions · roles Prometheus data source plugin (backend)query_range(start, end, step) → data frame alerting engineprovisioningplugin management grafana.dbdashboard JSON · usersdata sources · alert rules Prometheus :9090/api/v1/query_rangemetric data exists only here POST HTTP frames
Figure 6-1 Server (proxy) access mode: the browser talks only to Grafana; credentials and network access both live in the backend

$__interval and $__rate_interval

now-6hnow 6h / 1000 px ≈ 21.6s → rounded to 20s = $__interval (≥ scrape 15s) $__rate_interval = max(20s + 15s, 4 × 15s) = 1m each point's window is 1m with a 20s step: the windows overlap, so no samples are missed the rate windows of adjacent points
Figure 6-2 a hard-coded [5m] "skips" samples over long time ranges; writing [$__interval] gives "no data" over short time ranges

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.

Time range:
Panel width (px):1000 Scrape interval:
Panelvariable substitution /api/ds/queryauthentication + permissions data source pluginalign step Prometheusquery_range data framestransform + render

Grafana HTTP API and container commands

Command / endpointPurposeNotes
GET /api/healthHealth and versionno authentication needed; includes database status
GET /api/datasourcesList data sourcesrequires admin; provisioned ones carry readOnly: true
GET /api/datasources/uid/<uid>/healthTest data source connectivityequivalent to the UI's "Save & test"
POST /api/ds/queryRun a query as Grafanato troubleshoot "Grafana cannot find it but Prometheus can"
GET /api/search?type=dash-dbSearch dashboardsafter getting the uid, GET /api/dashboards/uid/<uid>
grafana cli admin reset-admin-passwordReset the admin passwordrun inside the container
docker compose logs grafana | grep -i provisioningView provisioning logsthe 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)

Log in and check the data source: open 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.
Explore: in the left menu, open Explore, select Prometheus, use the Builder metric browser 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).

Change the time range and watch the step change: choose Last 5 minutes and then Last 6 hours, and record the step and interval in the Query inspector:
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)
Compare with the wrong approach: in Explore, place two queries side by side and choose the Last 24 hours time range:
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.

Look at Grafana's own metrics: Prometheus is already scraping 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.

Command-line tasks
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.

Scenario analysis
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

▶
Creating Grafana Dashboards for Prometheus | Grafana Setup & Simple Dashboard (Chart, Gauge, Table) — Prometheus Monitoring with Julius | PromLabs
English · Grafana connecting to Prometheus and basic panels (the interface is an older version; Grafana 13's editor layout differs)
▶
What is Observability? | Grafana for Beginners Ep. 1 — Grafana
English · Grafana Labs official introductory series, episode 1
▶
Grafana Tutorial For Beginners | Continuous Monitoring With Grafana | DevOps Training | Edureka — edureka!
English · an older comprehensive introduction, good for supplementing concepts

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided instead.

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

Module 7 · Build your first dashboard: variables and the RED method

42:00 – 50:00 · Three questions answer “is the service healthy”: how many requests per second, how many fail, and how slow they are
8 minGrafana 13 · file provisioning★★★★☆
Learning objectives
  • 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).
Prerequisites: Modules 4–6. Importance:★★★★☆

What: RED and USE

MethodTargetThree signalsPromQL on myapp / hosts
RED (Tom Wilkie)Request-driven servicesRate: requests per secondsum(rate(myapp_http_requests_total[$__rate_interval]))
Errors: share of failed requestssum(rate(…{status=~"5.."}[…])) / sum(rate(…[…]))
Duration: latency distributionhistogram_quantile(0.95, sum by (le) (rate(…_bucket[…])))
USE (Brendan Gregg)Resources (CPU, memory, disk, network)Utilization: how busy1 - avg(rate(node_cpu_seconds_total{mode="idle"}[…]))
Saturation: amount of queueingnode_load1 / count without (cpu, mode) (node_cpu_seconds_total{mode="idle"})
Errors: error eventsrate(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

VariableTypeDefinitionKey points
jobQuerylabel_values(myapp_http_requests_total, job)Single-select; add more later when multiple environments are needed env
routeQuery, multi-select + Include Alllabel_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

QuestionVisualizationUnit / 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 routeTime series, legend {{route}}stacking optional
Latency percentiles over timeTime series: P50 / P95 / P99 as three liness; log scale optional
Overall shape of the latency distributionHeatmap, 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.

Common misconceptions① “Using = for variables is enough”: with multi-select or All, the value is a regex, so you must =~. ② “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

Variables: job = myapp ▾ route = All ▾ Time: Last 30 minutes Refresh: 30s Rate (Stat)5.1 req/s Errors (Stat)4.6 % P95 (Stat)0.98 s Redis (Stat + mapping)UP Request rate by route (Time series) Error rate by route, status Latency P50 / P95 / P99 Latency distribution (Heatmap)
Figure 7-1: the first row answers “is it healthy now?”; the second and third rows answer “since when, and which route?”

Variable substitution process

Panel query (template)rate(myapp_http_requests_total{job="$job", route=~"$route"}[$__rate_interval]) Current variable value$job = myapp$route = / and /slow (multi-select)$__rate_interval = 1m Sent to Prometheusrate(myapp_http_requests_total{job="myapp", route=~"(/|/slow)"}[1m])
Figure 7-2: multi-select values are joined into a regex with special characters escaped, which is why =~ must be used

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

Traffic req/s5 Errors %2 Latency ms40

Dashboard-related API and PromQL

CommandPurposeNotes
GET /api/search?query=myappFind dashboard uidProvisioned dashboards are visible here too
GET /api/dashboards/uid/myapp-redExport JSON (with meta).dashboard the dashboard field is the dashboard itself
POST /api/dashboards/dbCreate/update via APIChoose either this or file provisioning to manage the same uid
GET /api/annotationsAnnotations (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)

Write the dashboard JSON (provisioning scans the directory every 30 seconds):
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
Wait for provisioning to load, then open:
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.

Verify variables: the route dropdown should list /,/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.
Inject faults and observe how RED reacts:
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.

Export and version control: in the top-right corner of the dashboard, go to Export → Export as JSON and compare with the file; add ~/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.

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

▶
Creating Grafana Dashboards for Prometheus | Grafana Setup & Simple Dashboard (Chart, Gauge, Table) — Prometheus Monitoring with Julius | PromLabs
English · Panels and visualization choices
▶
Setting up Prometheus and Grafana for monitoring your servers — Eddie Zaneski
English · End-to-end setup and dashboards

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.

Shot 1 · 0–20s
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?
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% on the Quiz

Module 8 · Introduction to myapp observability readiness and troubleshooting

50:00 – 60:00 · One readiness checklist + a fixed sequence for working back from “no data on the graph” to the root cause
10 minTroubleshooting decision tree★★★★★
Learning objectives
  • 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.
Prerequisites: Modules 1–7. Importance:★★★★★

What: observability readiness checklist (myapp version)

#Check itemCurrent state of myappHow to verify
1Exposure /metrics, Content-Type correct✓ prometheus_client,text/plain; version=1.0.0curl -sI :5000/metrics
2All three RED metrics present, with names following conventions✓ Three consistent namespromtool check metrics
3Bounded labels (route templates, status codes)✓ url_rule.rule, unmatched → unmatchedcount by (route) (…)
4Histogram buckets cover the SLO threshold△ 0.25/0.5 s present; if the SLO is 300ms, add bucketsReview
5Multiprocess mode correct (directory cleanup,child_exit)✓counters restart from 0 after a restart, with no duplicates
6Dependency status visible✓ myapp_redis_up (refreshed on scrape)Stop Redis and observe
7Health checks separate from metrics,/healthz not dependent on downstream services✓healthz still returns 200 when Redis is stopped
8scraped by Prometheus,up with alerts△ Scraping ✓, alerts covered in Lesson 2up{job="myapp"}
9Dashboards managed as code✓ myapp-red.jsonprovisioned = true
10Versions traceable (build info, release annotations)✗ To add: myapp_build_info{version} and release annotations (later lessons)—

How: the fixed troubleshooting order

  1. Target: is the target there? /targets page, or /api/v1/targets; if missing → service discovery / relabel issue (check dropped targets).
  2. Scrape: up Is it 1? lastError If not, what is the error? DNS, connection refused, timeout, HTTP status code and Content-Type each produce distinctive error messages.
  3. Metric: is this metric present in the target's output? curl the target's /metrics; compare scrape_samples_scraped with scrape_samples_post_metric_relabeling.
  4. 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).
  5. 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).

Common misconceptions① “The container is healthy, so monitoring is fine”: HEALTHCHECK checks /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

① Target: present in /targets? (service discovery, relabel, dropped targets) ② Scrape: is up == 1? lastError? (DNS / refused / timeout / HTTP / Content-Type) ③ Metric: is it in /metrics? Was it dropped by metric_relabel? ④ Query: label matching, rate target, window size ⑤ Panel: data source, variable =~, time range, transformations Top-down: a problem at an upper layer makes every check below it fail
Figure 8-1: each layer has a confirmation command that can be run directly; see the “Commands” tab

myapp metric dependencies

Dockerfile ENVMULTIPROC_DIR gunicorn hookscleanup / child_exit /metrics 200text/plain 1.0.0 Prometheusmyapp:5000 · 15s Grafanauid=prometheus missing → ValueError → 500no cleanup → stale counts remainwrong type → parse failurewrong port → refusedwrong URL → No data
Figure 8-2: a break anywhere in the chain may ultimately show up as just “no data on the panel”

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.

① Target ② Scrape ③ Metrics ④ Query ⑤ Panel
Select a fault first.

Five-layer troubleshooting command cheat sheet

LayerCommandWhat to check
① Targetcurl -s :9090/api/v1/targets?state=any | jq …whether the target exists and whether it is dropped
② Scrapeup{job="myapp"},scrape_duration_seconds,lastError0/1, scrape duration close to the timeout, raw error message
② Scrape (network)docker compose exec prometheus wget -qO- -T 5 http://myapp:5000/metricsRun from the network where Prometheus runs
③ Metricscurl -s :5000/metrics | grep NAMEwhether the metric is exposed and whether the labels are as expected
④ Querypromtool query instant http://localhost:9090 'EXPR'remove conditions step by step
⑤ PanelQuery inspector; POST /api/ds/querythe 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).

Fault 1: wrong scrape port
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
Fault 2: wrong metrics_path (HTTP 404): temporarily add a line under the myapp job 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.

Fault 3: forgot to set PROMETHEUS_MULTIPROC_DIR (reproduce with a throwaway container so the running myapp is not affected):
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.

Fault 4: rate used on a gauge:
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]).

Final check:
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.

Command-line task
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.

Scenario analysis question
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

▶
Prometheus Tutorial | Monitoring with Prometheus And Grafana | Prometheus Grafana Tutorial | Edureka — edureka!
English · Overview of how Prometheus and Grafana work together (older version)
▶
Server Monitoring // Prometheus and Grafana Tutorial — Christian Lempa
English · Hands-on Compose deployment, can be followed alongside this lesson's environment

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.

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

Command cheat sheet

Commands, PromQL and config snippets used in this lesson (~/promlab environment)
Environment management
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
Config validation and hot reload
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
Prometheus HTTP API
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"
Targets and applications
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
PromQL: RED
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])
PromQL: infrastructure and self-monitoring
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"})
Grafana API
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 snippet
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: drop

Quick troubleshooting table

Symptom / errorLayerMost likely causeFirst command
lookup X on 127.0.0.11:53: no such hostScrapeContainer stopped / wrong service name / different networkdocker compose ps
connect: connection refusedScrapeWrong port / listening on 127.0.0.1 / not starteddocker compose exec prometheus wget -qO- http://X/metrics
context deadline exceededScrapeSlow target / saturated workersscrape_duration_seconds
server returned HTTP status 404 NOT FOUNDScrapemetrics_path Wrongcurl -I target path
server returned HTTP status 500 …MetricsMultiprocess config / handler exceptiondocker compose logs myapp
received unsupported Content-Type …ScrapeReturns HTML / content-type error (3.x no longer falls back)curl -sI; fallback_scrape_protocol
Grafana dial tcp [::1]:9090PanelData source URL uses localhost/api/datasources/uid/…/health
No data after selecting multiple variable valuesPanelUsed = instead of =~Query inspector
rate over a window of hours gives intermittent dataQuery< 2 samples in the windowSwitch to $__rate_interval
histogram_quantile returns NaNQueryNo traffic / dropped lesum 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

Verify ~/promlab from scratch, add latency observation for /slow and the Node/Redis panels, and write acceptance assertions in PromQL
After class ≈ 35 minutesCovers all modules
Scenario You are responsible for the observability go-live review of myapp. Requirements: ① 7 services running and all 6 scrape targets up; ② scrape config validated with promtool and committed to Git; ③ under a load of 400 req/min for myapp, the RED dashboard shows correct QPS, error rate and P95; ④ add a new “Node & Redis” dashboard (USE perspective); ⑤ use 5 PromQL assertions as the acceptance criteria; ⑥ locate an injected unknown fault within 5 minutes.
1. Pre-checks (Modules 0, 1)
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
2. Generate steady load (Modules 2, 4): if loadgen is not running, restart it; also send some extra requests to /slow:
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
3. Write 5 acceptance assertions (Modules 4, 5), all of which should return non-empty results:
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.

4. Add a Node & Redis dashboard (Modules 6, 7): in the Grafana UI, create a new dashboard with at least the following 5 panels; when done, Export as JSON and save it as 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_clients
5. Commit to Git (Module 7)
python3 -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
6. Blind troubleshooting test (Module 8): have a peer (or pick one yourself at random with your eyes closed) run one of the commands below, then locate the fault using only the five-layer method:
# 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.

7. Wrap up: keep the environment for Lesson 2; to free resources: kill %1 (stop loadgen), then run docker compose stop. Do not down -v, or Grafana and Prometheus data will be lost.
Acceptance checklist

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

Sources for all technical facts in this lesson (verified on 2026-11-15)
TopicVerified findingsSource (accessed 2026-11-15)
Prometheus versionsLatest 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.5prometheus/prometheus releases · Release cycle
Prometheus 3.x changes3.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 stableRelease notes for each version on GitHub
rate() algorithmextrapolatedRate: ≥2 samples, reset compensation, 1.1× average interval threshold, otherwise extrapolate half an interval, counter zero-point truncation,factor /= rangepromql/functions.go @ v3.16.0 · Query functions
Scrape mechanicsDefault 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/1mscrape/scrape.go,scrape/target.go,config/config.go,model/textparse/interface.go @ v3.16.0 · Configuration
PromQL detailsregex fully anchored; lookback defaults to 5m (--query.lookback-delta); anchored and smoothed semantics; in rules they need query_offsetQuerying basics
Alertmanagerv0.35.0 (2026-11-09)alertmanager releases
Exporternode_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
GrafanaLatest 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 modeMultiprocess mode docs · source code registry.py,exposition.py,multiprocess.py,values.py @ v0.26.0
Image tagsConfirmed 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-alpineDocker Hub tags API
myapp dependenciesCarried 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 (schemaVersion 41), 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-timestamps features and anchored/smoothed calculation details. The interval calculator in Module 6 simplifies Grafana's rounding rules.
  • myapp uses classic histograms; the Python client 0.26's Histogram does 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.