Prometheus & Grafana Hour 6: Monitoring Architecture in Practice

From “one Prometheus is enough” to “multi-cluster, multi-tenant, long-term storage, SLO-driven alerting”: choices, high availability, Thanos / Mimir, burn rate, OpenTelemetry and scaling Grafana
Prometheus v3.16.0Alertmanager v0.35.0Thanos v0.42.5Mimir 3.2.5Grafana 13.3.1Verified against official sources · 2026-11-15
Overall learning objectives
  • Be able to justify a choice between single instance, federation, remote write and Agent mode, and state the scale limit and failure modes of each.
  • Build an HA setup of “2 Prometheus replicas + a 3-node Alertmanager cluster”, and explain why Prometheus must send alerts to all Alertmanager, and where deduplication happens.
  • Draw the write and query paths for Thanos (sidecar / store / compactor / query) and Grafana Mimir (distributor / ingester / store-gateway / compactor / querier), and run a laptop-scale single-binary Mimir instance and Thanos Query deduplication on kind.
  • Use external_labels + tenant header X-Scope-OrgID to design a multi-cluster, multi-tenant metrics platform and configure per-tenant limits.
  • Define an availability SLO for myapp, write multi-window, multi-burn-rate (14.4 / 6 / 1) recording rules and alerts, and be able to calculate error budget consumption by hand.
  • Explain the division of labor between OpenTelemetry and Prometheus: OTLP ingestion, resource attributes and target_info, metric name translation, delta and cumulative.
  • Use organizations, nested folders, teams and basic roles (plus RBAC on Enterprise/Cloud) to organize hundreds of dashboards and teams, and manage them as code with Git Sync / Terraform / Operator.

1-hour time plan

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: multi-cluster sample environmentReuse the kind cluster from Hour 5 lab + kps (release: kps) + myapp; add a second kind cluster lab-b; resource estimates—kind create / helm list
100–06Architecture choicesSingle instance, vertical / functional sharding, federation /federate, remote write (1.0 / 2.0), Agent mode (--agent)Topology selector: data flow in the four architecturesFederation scrape + Agent-mode container remote write
206–13High availabilityReplica pair + prometheus_replica, Alertmanager gossip cluster (9094), notification log deduplication, shardsHA failure simulation: kill replica / kill AM / network partitionkps: Prometheus ×2, Alertmanager ×3
313–21Thanos and Mimirsidecar/receive/store/compactor/query and distributor/ingester/store-gateway/querier; object storage, downsampling, Mimir 3 ingest storageCore animation: write and query paths (switchable between Thanos / Mimir)Thanos Query deduplication + single-binary Mimir (filesystem backend)
421–28Multi-cluster and multi-tenancycluster external labels,X-Scope-OrgID, cross-tenant federated queries, per-tenant limits, prom-label-proxyTenant routing and limits simulatorlab-b Agent → Mimir tenant cluster-lab-b
528–35SLO and burn rateSLI/SLO/error budget, multi-window multi-burn-rate (14.4/6/1), recording rules, Sloth/PyrraCore interaction: burn rate calculatormyapp SLO PrometheusRule + fault injection
635–42OpenTelemetry and PrometheusOTLP ingestion (/api/v1/otlp/v1/metrics),promote_resource_attributes, translation_strategy,target_infoOTel metric name translatorOTel Collector → Prometheus OTLP
742–50Scaling GrafanaOrganizations, nested folders, teams, basic roles, RBAC (Enterprise/Cloud), service accounts, Git Sync, Terraform / OperatorEffective permissions calculatorAPI: create teams / folders / permissions
850–60Comprehensive architecture reviewReview checklist, capacity estimate, cost, failure domains, interactive troubleshooting treeArchitecture scorecard + troubleshooting treeCapacity and cardinality estimate
—After classCheat sheet · Integrated labTwo clusters → Mimir multi-tenancy → SLO alerts → Grafana team permissionsFinal quiz, 12 questionsAcceptance checklist

Knowledge coverage matrix

Target skillModuleKey commands / configurationLabProduction case
Architecture choices (federation / remote write / Agent)M1/federate?match[]=,remote_write,--agent✓✓
Prometheus HA and alert deduplicationM2replicas: 2,external_labels,--cluster.peer✓✓
Long-term storage (Thanos)M3thanos sidecar / query --query.replica-label, objstore.yml✓✓
Long-term storage (Mimir)M3 · M4/api/v1/push,/prometheus,-target=all✓✓
Multi-cluster / multi-tenancyM4X-Scope-OrgID,tenant_federation,overrides✓✓
SLO and burn rate alertsM5PrometheusRule,promtool test rules✓✓
OpenTelemetry ingestionM6--web.enable-otlp-receiver, otelcol otlphttp✓✓
Grafana organizations and permissionsM7/api/teams,/api/folders/:uid/permissions✓✓
Architecture review and capacity estimationM8prometheus_tsdb_head_series,rate(prometheus_tsdb_head_samples_appended_total[5m])On paper✓

Out of scope for this hour

TopicReasonWhere to learn
Full parameter set for production Helm deployments of Mimir / Thanos (mimir-distributed, bitnami thanos chart), memcached cache tuningNeeds hours and lots of resources; this hour only covers laptop scalemimir-distributed documentation · Thanos Getting started
Managed long-term storage (Azure Monitor managed Prometheus, Amazon Managed Service for Prometheus)Covered in Hours 3 and 4Hour 3 · Hour 4
Cardinality explosion, TSDB head/WAL/compaction internals, query performance tuningA topic for Hour 7Hour 7
Logs (Loki) and traces (Tempo) backends, end-to-end exemplarsBeyond the scope of metrics monitoringGrafana Loki / Tempo documentation
Detailed comparison of Cortex and VictoriaMetricsTime constraints; mentioned only in the comparison tableOfficial project documentation

How to use this courseware

10 pages per module
Theory · diagrams · animation · commands · labs · production cases · troubleshooting · quizzes · audio · video. Within the hour, go through “theory + animation” first; complete the labs on kind after class.
Progress
A quiz score ≥ 70% or clicking “Mark module complete” counts toward progress, saved in this browser (key name prom60-part6-progress-v1).
Laptop scale
All labs run on kind on this machine: cluster lab (kps from Hour 5) + a second cluster lab-b + single-binary Mimir. 16 GiB RAM recommended, 8 GiB minimum (skip lab-b). Zero cloud cost.
Version notes This hour uses versions verified on 2026-11-15: Prometheus v3.16.0 (2026-11-05; native histograms stable since v3.8.0, but scraping still requires scrape_native_histograms), Alertmanager v0.35.0, Thanos v0.42.5 (2026-10-27), Grafana Mimir 3.2.5 (2026-11-13; 3.0 was released 2025-10-31 and introduced Kafka-based ingest storage and the Mimir Query Engine as default), Grafana 13.3.1 (2026-11-10; 12.4.x still receives patches), kube-prometheus-stack 93.3.0, Prometheus Operator v0.95.2, OpenTelemetry Collector v0.165.0. The Remote-Write 2.0 spec is still labeled Experimental (2.0-rc). The MinIO Community Edition repository is archived and no longer maintained, so this hour's long-term storage labs use Mimir's filesystem backend and do not depend on MinIO.

Module 0 · Setup: multi-cluster sample environment

Reuse the kind cluster from Hour 5 lab + kube-prometheus-stack (release kps, namespace monitoring) + myapp, plus one “remote cluster” lab-b
Before class ≈ 15 minkind · kps 93.3.0 · zero cloud cost
Prerequisites
  • Completed Hour 5: kind cluster lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring installed; myapp (Flask + gunicorn, port 5000,/metrics) running in namespace myapp, ServiceMonitor with label release: kps.
  • myapp exposes unified metrics: myapp_http_requests_total{method,route,status},myapp_http_request_duration_seconds (histogram),myapp_redis_up.
  • Local machine: Docker Engine, kubectl, kind, helm (Helm 4 or 3.x both work), curl, jq. 16 GiB RAM recommended.
  • If the Hour 5 environment has been deleted, see “Quick rebuild” below.

Step 1: confirm the Hour 5 environment

kubectl config use-context kind-lab
helm -n monitoring list
kubectl -n monitoring get prometheus,alertmanager
kubectl -n myapp get deploy,svc,servicemonitor
kubectl -n monitoring get svc | grep -E 'prometheus|alertmanager|grafana'
NAME  NAMESPACE   REVISION  STATUS    CHART                          APP VERSION
kps   monitoring  3         deployed  kube-prometheus-stack-93.3.0   v0.95.2
NAME                                                     VERSION   DESIRED   READY   ...
prometheus.monitoring.coreos.com/kps-kube-prometheus-stack-prometheus   v3.x   1   1
alertmanager.monitoring.coreos.com/kps-kube-prometheus-stack-alertmanager  v0.3x  1   1
deployment.apps/myapp   2/2     2            2
servicemonitor.monitoring.coreos.com/myapp   ...
kps-grafana                                 ClusterIP   10.96.x.x   80/TCP
kps-kube-prometheus-stack-alertmanager      ClusterIP   10.96.x.x   9093/TCP,8080/TCP
kps-kube-prometheus-stack-prometheus        ClusterIP   10.96.x.x   9090/TCP,8080/TCP
Object name kps resource names are built from the release name + chart name and truncated; commonly kps-kube-prometheus-stack-prometheus. Use the output of kubectl get svc in your cluster as the reference; service names in this hour's commands can be replaced with the actual ones.

Step 2: quick rebuild (only if the Hour 5 environment is gone)

kind create cluster --name lab
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm upgrade --install kps prometheus-community/kube-prometheus-stack \
  -n monitoring --create-namespace --version 93.3.0 --wait
# myapp: as in Hour 5, kind load the myapp:1.1 image into the cluster and deploy it to namespace myapp,
# the ServiceMonitor needs metadata.labels.release: kps
kind load docker-image myapp:1.1 --name lab

Step 3: prepare a fixed values file for this hour

This hour changes the kps values several times. To avoid losing the Hour 5 settings, first export the current values, then keep layering on top of ~/promlab/k8s/kps-part6.yaml .

mkdir -p ~/promlab/k8s ~/promlab/part6
helm -n monitoring get values kps -o yaml > ~/promlab/k8s/kps-part5-values.yaml
cat > ~/promlab/k8s/kps-part6.yaml <<'EOF'
# Hour 6 overlay: add only the cluster identity label first; later modules append more gradually
prometheus:
  prometheusSpec:
    externalLabels:
      cluster: lab
EOF
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait

externalLabels It does not appear in local query results; it is only attached when data leaves this Prometheus (federation, remote write, alerting, Thanos). This is exactly what lets a multi-cluster architecture tell data sources apart.

Step 4: create a second cluster lab-b (used in Module 4, optional)

kind create cluster --name lab-b
kubectl config get-contexts
docker network inspect kind -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
lab-control-plane 172.18.0.2/16
lab-b-control-plane 172.18.0.3/16

The node containers of both kind clusters are attached to the Docker network kind so they can reach each other via node IP + NodePort. This is the network path this hour uses to simulate “cross-cluster remote write”.

Resources and cost

ComponentMemory (approx.)Notes
kind lab + kps (after Prometheus ×2 and Alertmanager ×3)2.5–3.5 GiBIncreases after Module 2 scales up the replica count
Mimir single binary (filesystem backend)0.3–0.8 GiBFrom Module 3
Thanos Query≈ 0.1 GiBModule 3
kind lab-b + kps (agent mode)1–1.5 GiBModule 4, optional
OTel Collector≈ 0.1 GiBModule 6
Safety and cleanup To demonstrate, this hour enables Prometheus's remote write / OTLP receiver endpoints and uses NodePort; these endpoints have no authentication, so they may only be used in a local lab environment. When the course ends: kind delete cluster --name lab-b; kubectl delete ns mimir; helm upgrade kps ... -f ~/promlab/k8s/kps-part5-values.yaml restore the Hour 5 configuration (Hour 7 continues using lab).
Self-check list

Module 1 · Monitoring architecture choices: single instance, federation and remote write

00:00 – 06:00 · When one Prometheus is enough, and when you need federation, remote write or Agent mode
6 minPrometheus v3.16.0 · Agent mode GA (--agent) · RW 2.0 experimental★★★★★ Architecture fundamentals
Learning objectives
  • State the bottlenecks of a single Prometheus (active series count → memory, query range → disk and CPU, local retention → single-disk capacity) and the order of “scale vertically first, then shard by function”.
  • Can configure federation scraping (/federate + match[] + honor_labels: true), and knows it only suits a few aggregated series.
  • Can configure remote_write (queue parameters,write_relabel_configs), and understands the WAL → sharded queue → remote endpoint mechanism and the differences in Remote-Write 2.0.
  • Knows Agent mode (--agent) strips out local queries, rules and alerting, and suits edge and multi-cluster collection.
Prerequisites: Scraping and TSDB (Hour 1), kps and ServiceMonitor (Hour 5). Importance:★★★★★

What: four basic topologies

TopologyApproachWhere the data livesTypical scale
Single instanceOne Prometheus scrapes all targets, with local TSDB storage + rules + alertsLocal disk (15-day retention by default,--storage.tsdb.retention.time)Up to millions of active series, depending on memory (rule of thumb: GiB per million active series)
Functional shardingSplit into several Prometheus servers by team/domain (infrastructure, app A, app B), each independentEach stores locallyTeams are autonomous, but there is no global view
FederationAn upper-level Prometheus scrapes the lower-level /federate endpoint, pulling only series matching match[] series'latest valueBoth layers store a copyOnly suits thousands to tens of thousands of series aggregated series (such as job: prefixed recording rules)
Remote writeEach Prometheus pushes new samples from its WAL to central storage (Thanos Receive, Mimir, managed services)Central storage (long-term retention) + short local retentionCentral storage scales horizontally to hundreds of millions of series
Agent modeprometheus --agent: scrape + remote write only; no local queries, rules or alerts; the WAL is truncated as soon as it is sent successfullyRemote onlyEdge, IoT, one lightweight collector per cluster

Why: why a single instance is ultimately not enough

  • Memory and active series: the head block keeps all active series from roughly the last 2–3 hours in memory; doubling the series count roughly doubles memory (covered in detail in Hour 7).
  • Single point of failure: if one process dies, scraping and alerting stop together; if the local disk is damaged, historical data is lost.
  • Retention period: local TSDB is not designed for “13 months of retention”; single-disk capacity and I/O when querying long ranges both become problems.
  • Global view: with multiple clusters and regions, you need one place to query and alert across clusters.

How: mechanical differences between federation and remote write

DimensionFederation /federateRemote write remote_write
DirectionPull (the upper layer does a scheduled GET)Push (the lower layer does HTTP POST of snappy-compressed protobuf)
DataEach request fetches only the current latest sample (an instantaneous value at scrape time); intermediate samples are lostIn the WAL,every sample is sent (can be filtered with write_relabel_configs )
OutageData during the outage is permanently lostWithin the WAL retention window (about 2 hours), data is resent after recovery
LabelsRequires honor_labels: true keeping the original job/instance; the lower layer's external_labels external_labels are appended; the sender adds its external_labels
Applies toCross-layer aggregation of a few metrics, and migrationLong-term storage, global queries, managed services (the AMW and AMP from Hours 3/4 both work this way)

Remote-Write 2.0: message type io.prometheus.write.v2.Request, uses a symbol table (string interning) to compress label strings, natively carries metadata (type, help, unit), exemplars and start timestamps (formerly created timestamp), and the receiver X-Prometheus-Remote-Write-*-Written reports the number written in its response header. The sender is configured with protobuf_message: io.prometheus.write.v2.Request, and the receiver (Prometheus) uses --web.remote-write-receiver.accepted-protobuf-messages to declare it accepts it. The spec on prometheus.io is still labeled Experimental (2.0-rc), production keeps defaulting to 1.0 (prometheus.WriteRequest), unless the receiver clearly supports 2.0.

When: making the choice

  • Single cluster, retention ≤ 30 days, active series < a few million: a single instance + an HA replica pair (Module 2) is enough.
  • Need a global view but small data volume, aggregates only: federation can serve as a transition; do not use federation to pull everything.
  • Need long-term retention, cross-cluster queries, centralized alerting: remote write to Mimir / Thanos Receive / a managed service, or Thanos sidecar (Module 3).
  • Many clusters, and you don't want to run a full Prometheus in each: Agent mode + central storage (Module 4).
Common misconceptions① “Federation can roll all of the lower layer's data up into the upper layer” — federation only fetches instantaneous values each time, and when the data volume is large, /federate the requests themselves time out; the official docs state it is suited to aggregated data. ② “Agent mode saves resources, so it is always better” — an Agent cannot evaluate alerts locally, so if central storage is unavailable, the alerts are gone too; for alert-sensitive clusters, either keep a local Prometheus or make sure the central Ruler is highly available. ③ “A remote_write failure blocks scraping” — it does not: scraping writes to the WAL, and sending runs in an independent sharded queue; but once the backlog exceeds the WAL retention window, data is lost.

Architecture diagram: four topologies side by side

① Single instance Prometheusscrape + TSDB + rules + alerting myapp node Arrow = scrape (pull) ② Federation Global PrometheusGET /federate?match[]= Prom cluster Ajob:* rules Prom cluster Bjob:* rules Pulls only the latest values of aggregated serieshonor_labels: true ③ Remote write Central storageMimir / Thanos Receive Prom AWAL→queue Prom BWAL→queue POST /api/v1/push (push)each sample + external_labels ④ Agent mode Central storage + RulerQueries / alerts happen here --agentCluster A --agentCluster B No local queries / rules / alertsWAL truncated once sent successfully
Figure 1-1 Pull vs. push: federation is the upper layer “pulling” instantaneous values from the lower layer; remote write is the lower layer “pushing” every sample to the center

Data flow: inside remote_write

Scrape / rulesAppender WAL segment filesdata/wal/0000xx WAL Watchertail reads new records Sharded queuesmin/max_shardscapacity · max_samples_per_sendwrite_relabel_configs HTTP POSTsnappy+protobuf Receiver2xx / 4xx / 5xx 5xx / 429 → retry with exponential backoff; other 4xx → drop the batch (counted as failed)
Figure 1-2 Sending is decoupled from scraping: when the remote end slows down, the number of queue shards grows automatically (up to max_shards), and the backlog shows up in prometheus_remote_storage_highest_timestamp_in_seconds - prometheus_remote_storage_queue_highest_sent_timestamp_seconds

Interactive: choose a topology and step through how data flows

After choosing a topology, click “Play” or “Next step”. Each step highlights the real components, and the log area shows the matching HTTP requests, configuration or metrics.

Target myapp:5000/metrics Cluster Prometheusscrape → WAL → head Transport— Central / upper layer— Grafana / alertingWhere queries and rules live Topology: single instance
Choose a topology and click “Play”.

Core commands and configuration

Command / configurationPurposeKey parameters
curl -G /federate --data-urlencode 'match[]=…'Manually inspect what the federation endpoint returnsat least one match[]; returns text format
scrape_configs[].metrics_path: /federateUpper layer scrapes lower layerhonor_labels: true,params.match[]
remote_write[]pushes to remoteurl,headers,queue_config,write_relabel_configs,protobuf_message
prometheus --agentAgent mode--storage.agent.path (default data-agent/),--storage.agent.retention.max-time (default 4h)
--web.enable-remote-write-receiverMakes Prometheus act as a remote write receiver (/api/v1/write)Off by default, no authentication
promtool check configValidate configurationThe Agent config must not contain rule_files/alerting

1. Federation: scrape config on the upper-layer Prometheus

scrape_configs:
  - job_name: federate-lab
    scrape_interval: 30s
    scrape_timeout: 25s
    honor_labels: true            # keep the lower layer's job/instance; do not rewrite to federate-lab
    metrics_path: /federate
    params:
      'match[]':
        - '{__name__=~"job:.*|namespace:.*"}'     # pull only recording rules (aggregated series)
        - 'myapp:sli_errors:ratio_rate5m'
    static_configs:
      - targets: ['prom-lab.example.internal:9090']
        labels:
          federated_from: lab

How to verify: Global layer up{job="federate-lab"} is 1,scrape_samples_scraped{job="federate-lab"} should stay within a few thousand. Common mistake: Writing match[]={__name__=~".+"} pulls everything → scrape timeout (context deadline exceeded). Production use: Temporary roll-ups during migration and sharing a few SLIs across teams.

2. Remote write: with queue parameters and filtering

global:
  external_labels:
    cluster: lab                  # central storage uses this to tell sources apart
remote_write:
  - url: http://mimir.mimir.svc:9009/api/v1/push
    headers:
      X-Scope-OrgID: cluster-lab  # Mimir tenant (Module 4)
    queue_config:
      capacity: 10000             # number of buffered samples per shard
      max_shards: 50              # up to 50 shards in parallel when the remote end is slow
      max_samples_per_send: 2000
      batch_send_deadline: 5s
    write_relabel_configs:
      - source_labels: [__name__]
        regex: 'go_gc_.*|apiserver_request_sli_.*'
        action: drop              # do not send high-cardinality, useless metrics to the center
    # protobuf_message: io.prometheus.write.v2.Request   # RW 2.0 (experimental), enable only if the receiver supports it
rate(prometheus_remote_storage_samples_failed_total[5m])
rate(prometheus_remote_storage_samples_retried_total[5m])
prometheus_remote_storage_shards
# send latency (seconds): latest WAL timestamp - latest sent timestamp
max_over_time(prometheus_remote_storage_highest_timestamp_in_seconds[5m])
  - ignoring(remote_name, url) group_right
max_over_time(prometheus_remote_storage_queue_highest_sent_timestamp_seconds[5m])

Metric names have changed across versions (for example samples_* and *_total), go by the names in your instance's /metrics /metrics output prometheus_remote_storage_ for the prefix in question.

3. Agent mode

prometheus --agent \
  --config.file=/etc/prometheus/agent.yml \
  --storage.agent.path=/prometheus \
  --storage.agent.retention.max-time=4h
promtool check config --agent /etc/prometheus/agent.yml
time=2026-11-16T15:17:03.680Z level=INFO source=main.go:939 msg="Starting Prometheus Agent" mode=agent version="(version=3.16.0, branch=HEAD, revision=e2e28ad…)"
…
time=… level=INFO … component=remote msg="Starting WAL watcher" …

Common mistake: agent.yml still contains rule_files or alerting section → startup error err="field rule_files is not allowed in agent mode"; use promtool check config --agent to catch it early. The Agent UI only has Targets / Status and similar pages; the Graph page queries are unavailable.

4. In kube-prometheus-stack

prometheus:
  agentMode: false              # true = have the Operator create a PrometheusAgent instead of a Prometheus
  prometheusSpec:
    enableRemoteWriteReceiver: false
    remoteWrite: []             # maps one-to-one to the remote_write field in prometheus.yml (camelCase)
    externalLabels:
      cluster: lab

Lab: federation scrape + Agent-mode remote write (kind lab)

Goal and environment: on kind lab ① observe the /federate output and external_labels; ② temporarily have the kps Prometheus act as a remote write receiver, and push to it from an Agent-mode Prometheus running in Docker. About 10 minutes, zero cost.
View the federation endpoint
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090 &
curl -sG localhost:9090/federate \
  --data-urlencode 'match[]=up{namespace="myapp"}' | head
# TYPE up untyped
up{cluster="lab",container="myapp",endpoint="http",instance="10.244.1.12:5000",job="myapp",namespace="myapp",pod="myapp-6f9c...",prometheus="monitoring/kps-kube-prometheus-stack-prometheus",prometheus_replica="prometheus-kps-kube-prometheus-stack-prometheus-0",service="myapp"} 1 1763190000000

Note: the federation output already includes cluster="lab",prometheus,prometheus_replica three external labels (the last two are added automatically by the Prometheus Operator), and each series has only one latest sample and timestamp.

Enable the remote write receiver and expose it via NodePort
# override the values overlay for this hour (service and prometheusSpec are at the same level, both under prometheus:)
cat > ~/promlab/k8s/kps-part6.yaml <<'EOF'
prometheus:
  service:
    type: NodePort
    nodePort: 30090
  prometheusSpec:
    externalLabels:
      cluster: lab
    enableRemoteWriteReceiver: true    # lab only: no authentication
EOF
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait
LAB_IP=$(docker inspect -f '{{.NetworkSettings.Networks.kind.IPAddress}}' lab-control-plane)
echo $LAB_IP
Start an Agent-mode Prometheus (Docker, attached to the kind network)
cat > ~/promlab/part6/agent.yml <<EOF
global:
  scrape_interval: 15s
  external_labels:
    cluster: laptop-agent
scrape_configs:
  - job_name: agent-self
    static_configs:
      - targets: ['localhost:9090']
remote_write:
  - url: http://${LAB_IP}:30090/api/v1/write
EOF
docker run -d --name prom-agent --network kind \
  -v ~/promlab/part6/agent.yml:/etc/prometheus/agent.yml:ro \
  prom/prometheus:v3.16.0 --agent --config.file=/etc/prometheus/agent.yml \
  --storage.agent.path=/prometheus
docker logs prom-agent 2>&1 | grep -iE 'mode=agent|remote|error' | head
Verify: data arrives at the lab Prometheus
sleep 30
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=up{cluster="laptop-agent"}' | jq '.data.result[] | {metric: .metric, value: .value[1]}'
{
  "metric": { "__name__": "up", "cluster": "laptop-agent", "instance": "localhost:9090", "job": "agent-self" },
  "value": "1"
}

Series arriving via remote write do not go through the lab Prometheus's scraping, so the lab's external_labels label is not attached (external_labels are not shown in local queries anyway).

Simulate an outage and observe the catch-up
docker network disconnect kind prom-agent; sleep 120; docker network connect kind prom-agent
sleep 30
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=count_over_time(up{cluster="laptop-agent"}[5m])' | jq '.data.result[0].value[1]'

Expect about 20 (5 min / 15 s): samples from the 2-minute outage are in the WAL and are resent after recovery. Compare with federation: data during the outage is lost forever.

Cleanup
docker rm -f prom-agent
kill %1   # stop the port-forward
# turn off enableRemoteWriteReceiver before Module 2 (see the values in the Module 2 lab)

Case 1: migrating from “full federation” to remote write

Problem: A company's global Prometheus used match[]={job=~".+"} federation over 12 clusters; the global instance used 120 GiB of memory, and scrapes /federate often exceeded scrape_timeout, leaving sawtooth gaps on the dashboards.

Approach: Each cluster's Prometheus adds external_labels.cluster and remote_write to Mimir; the global Grafana queries Mimir directly; federation keeps only 30 job: recording rules for one month as a comparison, then was retired.

Limitation: Remote write doubles the network egress for every sample (cross-region traffic costs money), so you need to use write_relabel_configs to drop metrics that do not need central storage.

Case 2: Agent mode at edge sites

Problem: 200 retail stores each have a small host; running a full Prometheus means maintaining rules and local disks.

Approach: Each store runs prometheus --agent,external_labels: {store: "s-0142"} remote-writing to the center; alert rules are evaluated centrally in the Ruler. The WAL keeps up to 4 hours by default (--storage.agent.retention.max-time), which covers the short outages common on store networks.

Limitation: If the center is unavailable, there are no alerts at all; each store needs a separate “watchdog” locally (for example, the center sets up a absent_over_time(up{store="s-0142"}[10m]) alert for each store).

Case 3: a mix of functional sharding and remote write

In a large cluster, kube-state-metrics / cAdvisor (high cardinality) and business metrics are split across two Prometheus instances (kps can do this with multiple Prometheus CRs plus different serviceMonitorSelector selectors), and both remote-write to the same center. Benefit: business alerts are not affected by infrastructure metric spikes.

Common errors and fixes

err="server returned HTTP status 404 Not Found: remote write receiver needs to be enabled with --web.enable-remote-write-receiver"

Cause: The receiving Prometheus has not enabled the receiver (in kps, prometheusSpec.enableRemoteWriteReceiver defaults to false).

kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.enableRemoteWriteReceiver}{"\n"}'
kubectl -n monitoring get sts -o yaml | grep -n 'enable-remote-write-receiver'

Fix: Turn on the parameter. In production, it is better to point remote write at Mimir / Thanos Receive rather than having Prometheus act as the receiver.

Get "http://…/federate?match%5B%5D=…": context deadline exceeded

Cause: Federation matches too many series, and the lower layer's response exceeds scrape_timeout.

curl -sG http://lower:9090/federate --data-urlencode 'match[]={__name__=~"job:.*"}' | wc -l

Fix: Federate only the aggregated series produced by recording rules, or switch to remote write.

msg="Failed to send batch, retrying" err="server returned HTTP status 429 Too Many Requests"

Cause: The receiver (Mimir / managed service) rate-limits per tenant, and the sample rate exceeds ingestion_rate.

sum by (cluster) (rate(prometheus_remote_storage_samples_total[5m]))   # send rate; the name follows the instance's /metrics
rate(prometheus_remote_storage_samples_retried_total[5m])

Fix: Raise the tenant limit (Module 4) or use write_relabel_configs to reduce the send volume. Note that 429 is retried by default (depending on queue_config.retry_on_http_429, for Prometheus 3, check the official configuration docs for the default).

msg="Skipping resharding, last successful send was beyond threshold" / remote write latency keeps growing

Cause: The remote end is persistently unreachable or very slow; the WAL backs up. Once the backlog exceeds WAL retention (when the head is truncated), data is lost.

prometheus_remote_storage_shards
prometheus_remote_storage_shards_desired
prometheus_wal_watcher_current_segment

Fix: First restore the remote end; if shards_desired stays longer than max_shards, raise max_shards or check network bandwidth.

msg="Error loading config (--config.file=…)" err="field rule_files is not allowed in agent mode"

Cause: Agent mode does not support fields such as rules, alerting and remote read (error text observed on v3.16.0).

promtool check config --agent agent.yml     # FAILED: field rule_files is not allowed in agent mode

Fix: Move the rules to a central Ruler (Mimir ruler / Thanos Ruler); keep only global,scrape_configs,remote_write etc.

Command-line exercises

1. Use curl to fetch from localhost:9090 the federation endpoint only the recording-rule series whose names begin with job: .

Reference answer
curl -sG localhost:9090/federate --data-urlencode 'match[]={__name__=~"job:.*"}'

2. Write a remote_write configuration that sends to https://mimir.example.com/api/v1/push, with the tenant header cluster-prod, and drops all metrics beginning with go_ .

Reference answer
remote_write:
  - url: https://mimir.example.com/api/v1/push
    headers:
      X-Scope-OrgID: cluster-prod
    write_relabel_configs:
      - source_labels: [__name__]
        regex: 'go_.*'
        action: drop

Scenario analysis: You have 8 Kubernetes clusters, each with about 800,000 active series. You must retain 13 months of data and query across clusters in one Grafana. The security team does not allow the central system to connect into each cluster. Which topology should you pick? Why not federation?

Reference answer

Choose “a Prometheus per cluster (or Agent) + remote write to a central Mimir / Thanos Receive”. Remote write is pushed outward from each cluster, so the center never has to connect in, which meets the security requirement. Central storage is backed by object storage, can retain 13 months, and scales horizontally to 6,400,000+ series. Federation is pull from the center, which violates the no-inbound-connection rule, and it only fetches instantaneous values, so a full federation would time out. The Thanos sidecar approach also requires the Querier to connect to each cluster's sidecar gRPC, which does not satisfy the requirement either. If a cluster needs local alerting, keep a full Prometheus rather than an Agent.

Verified teaching videos

▶
Why Prometheus 3.0 Will Change How You Do Observability: OTel Support, Remote Write 2.0, and More — Grafana
English · Prometheus 3 features such as remote write 2.0 and OTLP (for version details in this hour, the v3.16 docs take precedence)
▶
PromCon EU 2019: Remote Write Storage Wars — Prometheus Monitoring
English · comparison of various remote write backends (older, useful for understanding the mechanics)
▶
From Manual to Managed: Prometheus Agent Deployment at Scale - Mihail Mihaylov — CNCF [Cloud Native Computing Foundation]
English · practices for large-scale Agent mode deployments

Official documentation

Video storyboard script (for use with video generation tools)

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: One Prometheus's memory curve climbs steadily as clusters are added, and finally a red alarm appears.
Narration: How far can one Prometheus go? It depends on the number of active series, the retention period, and whether you need a global view.
Shot 2 · 0:20–0:50
Visual: Federation: the upper Prometheus periodically does GET /federate and only gets one point per series.
Narration: Federation is a pull, and it only pulls the latest value, so it suits a small number of aggregated metrics.
Shot 3 · 0:50–1:30
Visual: remote write: WAL segment files → watcher → multiple sharded queues → POST to the center. During an outage the queues back up; they are resent after recovery.
Narration: Remote write is a push: every sample in the WAL is sent out, and a brief outage can be caught up afterward.
Shot 4 · 1:30–2:00
Visual: Agent mode: the Prometheus icon drops the query, rules and alerting modules, leaving only scraping and sending.
Narration: Agent mode is lighter, but alerting has to be handed to the center. Choosing an architecture means making decisions among these trade-offs.
or score ≥ 70% on the “Quiz”

Module 2 · High availability: Prometheus replicas and an Alertmanager cluster

06:00 – 13:00 · Two identical Prometheus instances + three Alertmanagers that gossip with each other; alerts are sent only once
7 minAlertmanager v0.35.0 · Operator v0.95.2★★★★★ Production essential
Learning objectives
  • Understand the Prometheus HA model: no replication, but two replicas scrape the same targets independently; the query layer handles deduplication (Module 3).
  • Understand the Alertmanager cluster: gossip (default 9094) shares silences and the notification log (nflog), and deduplication is achieved by staggering sends according to peer position.
  • Know that Prometheus must send alerts to every Alertmanager, rather than sending to just one through a load balancer.
  • Can configure in kps replicas,shards, PodDisruptionBudget, anti-affinity, and verify cluster membership.
Prerequisites: Alert lifecycle (Hour 2), kps CRDs (Hour 5). Importance:★★★★★

What: HA at the two layers uses two different mechanisms

ComponentHA approachState syncDeduplication happens in
PrometheusN identically configured replicas, each scraping, storing and evaluating rules independentlyNone (replicas do not talk to each other; sample timestamps differ slightly)Query layer: Thanos Query --query.replica-label, Mimir HA tracker (by cluster/__replica__ accepts only one replica)
AlertmanagerN instances form a cluster (memberlist gossip)silences and the notification log (nflog)Alertmanager itself: every instance receives the alert and computes grouping, but nflog and staggered waits ensure one notification is sent (best effort; may duplicate during network partitions)

Why: why you can't just run “one Prometheus + one Alertmanager”

  • During a Prometheus restart (upgrade, OOM, node eviction) there is no scraping and no alert evaluation; WAL replay can take several minutes.
  • When Alertmanager goes down, no alerts can be sent at all —a failure of the monitoring system itself happens exactly when you need it most.
  • Silences exist only in one instance's memory plus a local snapshot; if the instance is lost, the silences are lost too, and on-call gets paged again.

How: the Alertmanager cluster's deduplication mechanism

  1. Each Prometheus replica sends the same alert to all Alertmanagers (kps gets each Pod IP through endpoints service discovery on the alertmanager Service).
  2. Each AM instance groups independently and waits group_wait. When it is time to send, each instance waits according to its position in the cluster position × --cluster.peer-timeout (default 15s): position 0 sends immediately, position 1 waits 15 seconds, position 2 waits 30 seconds.
  3. After position 0 sends successfully, it writes the record to nflog and gossips it to the other instances; positions 1 and 2 check nflog when their wait ends and skip if it was already sent.
  4. The alert's prometheus_replica label must be removed before sending (the Prometheus Operator generates alert_relabel_configs to do a labeldrop), otherwise the alerts from the two replicas have different labels and are treated as two alerts.

When: deciding the number of replicas

  • Prometheus: 2 replicas is the industry convention; use anti-affinity across availability zones. When beyond single-instance capacity, use shards (split targets into shards by hashmod, with 2 replicas per shard).
  • Alertmanager: 3 instances (odd number, tolerates one failure and gossip converges quickly); 2 also works but has a higher chance of duplicates during partitions.
  • Grafana: stateless + shared database (MySQL/PostgreSQL), multiple replicas; for Grafana Alerting HA, see Module 7.
ComparisonPrometheus replica pairThanos Receive / Mimir (replication factor 3)
Data replicationTwo independent replicas, each scrapingreplicated to 3 ingesters/receivers on the write path (acknowledged once a majority succeeds)
At query timerequires deduplication (replica label)the query layer merges automatically
Costscraping ×2, storage ×2storage ×3 (in memory); object storage keeps only 1 copy (compactor deduplicates)
Common misconceptions① “Put Alertmanager behind one Service and let Prometheus send to the Service — that's enough”: this means each alert reaches only one instance, alerts are lost when that instance restarts, and the cluster semantics are lost too; send to all instances. ② “Two Prometheus replicas have exactly the same data”: scrape times differ, so sample timestamps and values differ slightly, and counter reset times may also differ; that's why, when Grafana polls the two replicas directly through a Service, the curves jump on refresh. ③ “An Alertmanager cluster guarantees exactly-once”: it can only achieve “at most about once”; during a network partition it prefers duplicates over missed alerts.

Architecture diagram: the HA topology in kps

Targetsmyapp ×2 · node · ksm prometheus-…-0prometheus_replica=…-0Availability zone 1 prometheus-…-1prometheus_replica=…-1Availability zone 2 Each scrapes independently alertmanager-0Position 0 · send immediately alertmanager-1Position 1 · wait 15s alertmanager-2Position 2 · wait 30s gossip :9094silences + nflog Slack / PDReceived only once Each Prometheus replica → each Alertmanager (2 × 3 = 6 connections); the prometheus_replica label is removed before sending
Figure 2-1 The Prometheus layer has no replication and each instance scrapes independently; the Alertmanager layer shares the notification log via gossip to achieve deduplication

Sequence diagram: deduplicating one alert

Prom-0/1AM-0AM-1AM-2Slack POST /api/v2/alerts group_wait 30sgroup_wait 30sgroup_wait 30s t+0s: AM-0 sends gossip nflog record t+15s: check nflog → skipt+30s: check nflog → skip
Figure 2-2 Wait time = position × peer-timeout; if AM-0 fails to send or is down, AM-1 takes over after 15 seconds

HA failure simulator

Choose a failure scenario and step through it to watch how scraping, alert evaluation, sending and deduplication change. The log shows real Alertmanager / Prometheus metrics or log lines.

prometheus-0
Scraping
prometheus-1
Scraping
alertmanager-0
Position 0
alertmanager-1
Position 1
alertmanager-2
Position 2
Slack received:0 alert(s)
Choose a scenario, then click “Play”.

Core commands and configuration

Command / configurationPurposeKey parameters
prometheusSpec.replicasPrometheus replica countOperator adds external label prometheus_replica (the name can be replicaExternalLabelName changed)
prometheusSpec.shardshorizontal sharding by target hashmodeach shard has replicas replicas; queries need an aggregation layer
alertmanagerSpec.replicasAlertmanager cluster sizeThe Operator adds it automatically --cluster.peer
alertmanager --cluster.listen-address / --cluster.peer / --cluster.peer-timeoutcluster parameters for manual deploymentslistens on default 0.0.0.0:9094, peer-timeout defaults to 15s
amtool cluster showView cluster status and members--alertmanager.url
alertmanager_cluster_memberscluster member count metricshould equal the number of replicas

1. kps values: HA configuration

prometheus:
  service:
    type: NodePort
    nodePort: 30090
  prometheusSpec:
    replicas: 2
    externalLabels:
      cluster: lab
    enableRemoteWriteReceiver: false          # Module 1 lab is finished; turn it off
    podAntiAffinity: soft                     # use hard + topologyKey for availability zones in production
    podAntiAffinityTopologyKey: kubernetes.io/hostname
    retention: 2d
alertmanager:
  alertmanagerSpec:
    replicas: 3
    podAntiAffinity: soft
  podDisruptionBudget:
    enabled: true
    minAvailable: 2

In kps, podDisruptionBudget the exact key names and locations vary by chart version; go by the helm show values prometheus-community/kube-prometheus-stack --version 93.3.0 output.

2. Alertmanager cluster parameters for manual deployment

alertmanager --config.file=/etc/alertmanager/alertmanager.yml \
  --storage.path=/alertmanager \
  --cluster.listen-address=0.0.0.0:9094 \
  --cluster.peer=am-1.am-headless:9094 \
  --cluster.peer=am-2.am-headless:9094 \
  --cluster.peer-timeout=15s
alerting:
  alert_relabel_configs:
    - action: labeldrop
      regex: replica
  alertmanagers:
    - static_configs:
        - targets: ['am-0:9093', 'am-1:9093', 'am-2:9093']

3. Verify

kubectl -n monitoring get pods -l app.kubernetes.io/name=alertmanager -o wide
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-alertmanager 9093 &
amtool cluster show --alertmanager.url=http://localhost:9093
curl -s localhost:9093/api/v2/status | jq '.cluster.status, (.cluster.peers|length)'
Cluster Status:  ready
Node Name:       01J...ABC
Peers:
  - Name: 01J...ABC  Address: 10.244.1.21:9094
  - Name: 01J...DEF  Address: 10.244.2.17:9094
  - Name: 01J...GHI  Address: 10.244.1.22:9094
"ready"
3
alertmanager_cluster_members                 # each instance should show 3
alertmanager_cluster_failed_peers            # should be 0
sum by (pod) (rate(alertmanager_notifications_total[10m]))   # normally only one instance sends heavily
count by (cluster) (prometheus_build_info)   # each cluster should have 2 replicas online

Production use: Add alerts for “the monitoring itself”: alertmanager_cluster_members < 3,up{job=~".*prometheus.*"} == 0, and set up an external Watchdog/dead man's switch (kps ships with Watchdog alerts; connect it to an external heartbeat service).

Lab: upgrade kps to Prometheus ×2 + Alertmanager ×3 and run failure drills

Goal and environment: kind lab, kps release kps, namespace monitoring. About 10 minutes; memory increases by about 0.8 GiB.
Apply HA values: write the first section of the “Commands” page into ~/promlab/k8s/kps-part6.yaml (the PDB part can be omitted at first).
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait
kubectl -n monitoring get pods -l 'app.kubernetes.io/name in (prometheus,alertmanager)'
alertmanager-kps-kube-prometheus-stack-alertmanager-0   2/2   Running
alertmanager-kps-kube-prometheus-stack-alertmanager-1   2/2   Running
alertmanager-kps-kube-prometheus-stack-alertmanager-2   2/2   Running
prometheus-kps-kube-prometheus-stack-prometheus-0       2/2   Running
prometheus-kps-kube-prometheus-stack-prometheus-1       2/2   Running
Confirm the deduplication configuration generated by the Operator
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -A6 -E 'external_labels|alert_relabel_configs'
  external_labels:
    cluster: lab
    prometheus: monitoring/kps-kube-prometheus-stack-prometheus
    prometheus_replica: $(POD_NAME)
alerting:
  alert_relabel_configs:
  - action: labeldrop
    regex: prometheus_replica

$(POD_NAME) is expanded from environment variables at container startup, so the two replicas' prometheus_replica differ. Use the Secret name shown by kubectl -n monitoring get secret | grep prometheus-kps .

Check the Alertmanager cluster: run the third section of the “Commands” page to confirm 3 peers and ready.
Failure drill 1: delete one Prometheus replica
kubectl -n monitoring delete pod prometheus-kps-kube-prometheus-stack-prometheus-0
# the other replica is still evaluating rules and sending the Watchdog alert:
curl -s localhost:9093/api/v2/alerts | jq -r '.[] | select(.labels.alertname=="Watchdog") | .labels | keys | join(",")'
alertname,cluster,namespace,prometheus,severity

Note that the Watchdog alert's labels do not include prometheus_replica— the two replicas send the “same” alert.

Failure drill 2: delete alertmanager-0; silences are not lost
amtool silence add alertname=Watchdog --comment="ha test" --duration=30m --alertmanager.url=http://localhost:9093
kubectl -n monitoring delete pod alertmanager-kps-kube-prometheus-stack-alertmanager-0
sleep 60; kubectl -n monitoring port-forward pod/alertmanager-kps-kube-prometheus-stack-alertmanager-2 9094:9093 &
amtool silence query --alertmanager.url=http://localhost:9094
ID                                    Matchers              Ends At                  Created By  Comment
4f1c2b0e-...                          alertname="Watchdog"  2026-11-15 10:42:00 UTC  you         ha test

Silences were synced to alertmanager-2 via gossip, and the rebuilt alertmanager-0 also pulls the silences from its peers.

Observe the Grafana “jumping” problem: in Grafana Explore, repeatedly run rate(prometheus_tsdb_head_samples_appended_total[1m]) against the kps default data source; the Service rotates requests across the two replicas, and results differ slightly. Module 3 fixes this with Thanos Query deduplication.
Cleanup: amtool silence expire $(amtool silence query -q --alertmanager.url=http://localhost:9093) --alertmanager.url=http://localhost:9093; end the port-forward. Keep the HA configuration for the later modules.

Case 1: alerts sent 3 times

Problem: On-call received 3 identical Slack messages per alert. Investigation showed the three Alertmanagers were deployed as 3 independent Deployments, without --cluster.peer,alertmanager_cluster_members all showing 1 peer.

Approach: Changed to a StatefulSet + headless Service,--cluster.peer pointing at each other (or using the Operator); the NetworkPolicy allows 9094 TCP and UDP (memberlist uses both).

Limitation: When deploying an AM cluster across regions, gossip latency is high and partitions are common; usually use one cluster per region + different receivers.

Case 2: alerts “doubled” because replica labels differed

Problem: Two manually deployed Prometheus instances set external_labels.replica: a/b, but did not configure alert_relabel_configs, so Alertmanager treated them as two alerts (2 shown in the group).

Approach: Add labeldrop: replica. The Operator handles this automatically at deploy time.

Case 3: sharding in very large clusters

Problem: A single Prometheus with 20 million active series used over 100 GiB of memory, and WAL replay took over 20 minutes.

Approach:shards: 4 (2 replicas per shard), about 5 million series per shard; Thanos sidecar + Query merges 4 shards and deduplicates replicas; alert rules that need global data move to Thanos Ruler or Mimir Ruler.

Limitation: After sharding, recording rules in a single shard can only see their own targets; sum() global-style aggregations must be done at the query layer. For several shard behaviors in the Prometheus Operator docs (such as data handling when scaling in), go by the official docs.

Common errors and fixes

msg="Failed to join cluster" err="1 error occurred:\n\t* Failed to resolve alertmanager-…-1.alertmanager-operated:9094: lookup … no such host"

Cause: The headless Service is not ready or the Pod has not been created yet, so the DNS record does not exist; this usually appears briefly on first startup. If it persists, it may be a NetworkPolicy block or a DNS problem.

kubectl -n monitoring get svc alertmanager-operated
kubectl -n monitoring run dns --rm -it --image=busybox:1.36 -- nslookup alertmanager-operated
alertmanager_cluster_members only shows 1 / cluster status "settling" never finishes

Cause: Port 9094 is denied by a NetworkPolicy (note that both TCP and UDP must be allowed), or --cluster.advertise-address an unreachable address was entered.

kubectl -n monitoring logs alertmanager-kps-kube-prometheus-stack-alertmanager-0 -c alertmanager | grep -i cluster
kubectl -n monitoring get networkpolicy
The same alert arrives as two notifications whose labels differ only in prometheus_replica

Cause: The replica label was not removed before the alert was sent (manual configuration or a custom additionalAlertRelabelConfigs overrode it).

curl -s localhost:9093/api/v2/alerts | jq '.[].labels' | grep -c prometheus_replica

Fix:alert_relabel_configs: [{action: labeldrop, regex: prometheus_replica}].

Grafana panels show slightly different curves on each refresh / occasional gaps

Cause: The data source points to a load-balanced Service, so requests rotate across different replicas; a replica that has just restarted is missing data.

Fix: Change the data source to Thanos Query (--query.replica-label=prometheus_replica) or Mimir; as a temporary workaround, set sessionAffinity: ClientIP on the Service.

Command-line exercises

1. Write a query that lists instances whose Alertmanager cluster member count is not equal to 3.

Reference answer
alertmanager_cluster_members != 3

2. Use amtool to view http://localhost:9093 the cluster status.

Reference answer
amtool cluster show --alertmanager.url=http://localhost:9093

Scenario analysis: To “simplify”, the team changed Prometheus's alertmanagers configuration to point only at one LoadBalancer Service (backed by 3 AMs). It ran fine for a week, but after one rolling upgrade of the AMs, 2 critical alerts were lost. Explain the cause and the fix.

Reference answer

When sending through a Service, each POST reaches only one AM instance. During the rolling upgrade, the instance that received the alerts was restarted, and alerts still waiting to be sent in its memory (in group_wait) were lost; the other instances never received them and cannot take over. Prometheus periodically resends firing alerts (resend interval about 1 minute), so the alerts usually recover, but if an alert was already resolved in that window, or the receiving instance keeps restarting, it will be missed. Fix: configure Prometheus to send to every AM instance (the endpoints role of Kubernetes SD, or the Operator's default), and give the AMs a PDB so at least 2 stay online during upgrades.

Verified teaching videos

▶
PromCon 2017: Alertmanager and High Availability - Frederic Branczyk — Prometheus Monitoring
English · explanation from the designer of the Alertmanager cluster (gossip, nflog, deduplication); for parameter details, the current docs take precedence
▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · review of the overall architecture of Prometheus and Alertmanager

Official documentation

Video storyboard script

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0:00–0:20
Visual: A single Alertmanager icon turns grey; the on-call phone is silent, while production is on fire.
Narration: The monitoring system is most likely to fail exactly when you need it most.
Shot 2 · 0:20–0:50
Visual: Two Prometheus replicas scrape the same set of targets side by side, and each small disk keeps growing.
Narration: Prometheus high availability is simple: two replicas, each scraping on its own, with no replication.
Shot 3 · 0:50–1:40
Visual: Six arrows run from 2 Prometheus instances to 3 Alertmanagers; AM-0 sends immediately, and AM-1 counts down 15 seconds, then checks the notification log and skips.
Narration: Alerts are sent to every Alertmanager; they share the notification log via gossip and stagger by position, so each notification is sent only once.
Shot 4 · 1:40–2:00
Visual: kubectl delete pod; amtool silence query still shows the silences.
Narration: Deleting any one instance does not lose silences or alerts.
or score ≥ 70% on the “Quiz”

Module 3 · Long-term storage: Thanos and Grafana Mimir

13:00 – 21:00 · Put 2-hour TSDB blocks into object storage, then query all of history through a single PromQL endpoint
8 minThanos v0.42.5 · Mimir 3.2.5★★★★★ Core module
Learning objectives
  • Draw Thanos's two write methods (sidecar uploads blocks / Receive accepts remote write) and the query path (Query → sidecar + store gateway, deduplicating by replica label).
  • Draw the Mimir write path (distributor → replicated to 3 ingesters via hash ring → 2h blocks uploaded to object storage → compactor) and query path (query-frontend → scheduler → querier → ingesters + store-gateways).
  • Know the three jobs of the compactor: merging, deduplication (vertical compaction), downsampling (Thanos) / split-and-merge (Mimir), and why it must be a singleton or sharded by tenant.
  • Run Thanos Query deduplication and a single-binary Mimir (filesystem backend) on kind, and have Grafana query Mimir.
Prerequisites: TSDB blocks and WAL (Hour 1), Module 1's remote write, Module 2's replica labels. Importance:★★★★★

What: both solve the same problem

Every 2 hours Prometheus cuts the data in the head into an immutable TSDB block (chunks/ + index + meta.json). Thanos and Mimir both put these blocks into object storage (S3, GCS, Azure Blob, Swift; filesystem for testing), then provide a query endpoint compatible with the Prometheus HTTP API, which merges “recent in-memory data” with “historical blocks in object storage” at query time.

DimensionThanos (CNCF incubating project)Grafana Mimir (AGPLv3)
Starting point“Add capabilities to existing Prometheus”: the sidecar sits next to Prometheus, with minimal changes“A horizontally scalable multi-tenant TSDB service”: Prometheus only handles remote write
Writes① Sidecar uploads the blocks Prometheus generates; ② Receive accepts remote write (hash ring + replication)Distributor receives remote write → hash ring → ingester (replication factor 3 by default); since Mimir 3.0, Kafka-based ingest storage can decouple reads and writes
QueriesQuery (Querier) fans out via gRPC StoreAPI to sidecar / receive / store gateway / ruler, and deduplicates by --query.replica-label ; Query Frontend handles splitting and caching.Query-frontend (splitting, caching) → query-scheduler → querier → ingesters (recent) + store-gateways (historical); since 3.0, Mimir Query Engine is the default (streaming, lower memory)
CompactionCompactor: merging, vertical deduplication,downsampling (5m, 1h) and retention by resolutionCompactor: split-and-merge compaction, deduplicates 3 replicas, sharded by tenant; no downsampling
Multi-tenancyReceive supports a tenant header (default THANOS-TENANT), while multi-tenancy on the query side needs extra components or conventionsNative: each request's X-Scope-OrgID, with per-tenant limits, isolation and cross-tenant federated queries.
Deployment formMultiple independent binary subcommands (same thanos image)Single binary (-target=all) or microservices (mimir-distributed Helm chart)
Suited forMany existing Prometheus instances, wanting to gradually add a global view and long-term storage; sidecar mode needs no change to the write pathPlatform teams providing “metrics as a service”, multi-tenant, high write volume; integrates with the Grafana ecosystem

Why: why object storage + compactor are needed

  • Object storage is cheap, nearly unlimited, and durable by design; 13 months of data is no longer constrained by a single disk.
  • There are huge numbers of small 2-hour blocks, and queries would have to open many indexes → the compactor merges them into large blocks (up to 24h or longer) and merges the duplicate data created by HA replicas / replication factor into one copy.
  • Thanos downsampling means “looking at a year's trend” doesn't need to read raw 15-second samples; Mimir relies on query splitting, caching and an efficient store-gateway instead.

How: key constraints of the Thanos sidecar

  • Each Prometheus's external_labels must be globally unique (cluster + replica); Thanos uses it to identify block sources and deduplicate.
  • When uploading to object storage, Prometheus's local compaction must be turned off (--storage.tsdb.min-block-duration = max-block-duration = 2h), otherwise the sidecar uploads blocks already merged locally, creating overlaps; the Operator does this automatically when configured with objectStorageConfig . The official tutorial's guidance is “do not change the minimum block duration.”
  • The Querier must be able to reach each sidecar over gRPC (default 10901); across clusters this means exposing the sidecar or using Receive.

When: how to choose

  • Dozens of independent Prometheus instances and you want a global view first: Thanos sidecar + Query, then add object storage and a compactor.
  • Clusters cannot be accessed inbound, or you want to run a “metrics platform service” for many teams: Mimir (or Thanos Receive) + remote write.
  • Don't want to operate it: managed services (Hour 3 Azure Monitor workspace, Hour 4 AMP, Grafana Cloud).
Common misconceptions① “With Thanos/Mimir, you no longer need local Prometheus retention” — keep local retention for a few hours to 1–2 days, so local alerts and recent queries still work if the remote end fails. ② “Running several compactors speeds things up” — the Thanos compactor must run as a singleton over a given set of blocks, otherwise they would rewrite the same blocks concurrently; the Mimir compactor shards by tenant via a hash ring and does not have multiple instances processing the same data concurrently. ③ “Mimir single-binary mode suits small production clusters” — the single binary can run with multiple replicas, but the filesystem backend only suits demos; production must use object storage. ④ MinIO is often used in tutorials as a local S3, but the MinIO Community Edition repository is archived and no longer maintained, so for new projects, evaluate other S3-compatible storage or use cloud object storage directly.

Architecture diagram A: Thanos (sidecar mode + Receive mode)

Cluster A (sidecar mode) Prometheus ×22h block thanos sidecarStoreAPI :10901 Cluster B (remote write) Prometheusremote_write thanos receivehashring · RF Object storage bucketS3 / GCS / Azure Blob uploads blocks compactor (singleton)merge · deduplicate · downsample · retain store gatewayread bucket · StoreAPI thanos query--query.replica-labelPromQL · deduplicate gRPC StoreAPI (recent data) query-frontendsplit · cache Grafana
Figure 3-1 Thanos: the sidecar serves recent data inside the cluster and uploads blocks; Receive accepts remote write; Query aggregates via StoreAPI and deduplicates by replica label

Architecture diagram B: Grafana Mimir (microservices view)

Write path Prometheus / AgentPOST /api/v1/push distributorvalidation · limits · HA deduplication ingester ×3 (RF=3)WAL + head (per-tenant TSDB)cut and upload a block every 2h(3.0: can go via Kafka ingest storage) Object storage<tenant>/<block ULID>/ compactorsplit-and-merge · deduplicate Query path GrafanaGET /prometheus/api/v1/query_range query-frontendsplit by day · results cache query-schedulerfair queuing per tenant querierMQE (default in 3.0) ingestersrecent (about the last 13h) store-gatewayshistorical blocks (bucket index) store-gateway lazy-loads index-header
Figure 3-2 Mimir: writes pass through the distributor and are replicated to 3 ingesters; queries merge recent data in the ingesters with historical blocks in the store-gateway. In monolithic mode all of these components run in one process (-target=all)

Core animation: write path and query path (switch between Thanos / Mimir)

Select a path, then press play. Each step highlights a real component, and the log shows that component's actual API, gRPC method, object storage path, or key parameters.

n0 n1 n2 n3 n4 n5 n6
After selecting a path, click “Play”.

Core commands and configuration

CommandPurposeKey parameters
thanos sidecarSits next to Prometheus: StoreAPI + block upload--tsdb.path,--prometheus.url,--objstore.config-file,--grpc-address
thanos queryGlobal PromQL and deduplication--endpoint (repeatable, supports dns+/dnssrv+),--query.replica-label
thanos storeServes historical data from the bucket--objstore.config-file,--data-dir (index cache)
thanos compactCompaction, deduplication, downsampling, retention--wait,--retention.resolution-raw/5m/1h,--deduplication.replica-label
thanos tools bucket inspect / lsInspect blocks in the bucket--objstore.config-file
mimir -config.file=… -target=allRuns all components in one process-target can be distributor, ingester, querier, etc.
mimirtoolCommand-line tools for rules, alerting configuration, analysis, etc.--address,--id (tenant)

1. Thanos object storage configuration (production example: S3)

type: S3
config:
  bucket: prom-lab-thanos
  endpoint: s3.ca-central-1.amazonaws.com
  region: ca-central-1
  # Recommended: use IRSA / Workload Identity, do not store static keys
kubectl -n monitoring create secret generic thanos-objstore --from-file=objstore.yml
prometheus:
  thanosService:
    enabled: true                # creates a headless Service exposing the sidecar gRPC port 10901
  prometheusSpec:
    thanos:
      image: quay.io/thanos/thanos:v0.42.5
      objectStorageConfig:
        existingSecret:
          name: thanos-objstore
          key: objstore.yml

The kps values comments state: prometheusSpec.thanos section is experimental and may change without deprecation notice.

2. Thanos Query and Compactor

thanos query \
  --http-address=0.0.0.0:10902 --grpc-address=0.0.0.0:10901 \
  --endpoint=dnssrv+_grpc._tcp.kps-kube-prometheus-stack-thanos-discovery.monitoring.svc.cluster.local \
  --endpoint=dnssrv+_grpc._tcp.thanos-store.monitoring.svc.cluster.local \
  --query.replica-label=prometheus_replica

thanos compact --wait \
  --data-dir=/var/thanos/compact \
  --objstore.config-file=/etc/thanos/objstore.yml \
  --retention.resolution-raw=30d --retention.resolution-5m=90d --retention.resolution-1h=1y \
  --deduplication.replica-label=prometheus_replica

How to verify: The Stores page of the Thanos Query UI (10902) lists each sidecar/store's label set and time range; toggle “Use deduplication” on and off to compare results. Common errors: Multiple Prometheus servers with identical external labels → Query reports duplicate label sets, and the deduplicated results are wrong. Production use: Grafana should have only one Thanos Query (via query-frontend) data source.

3. Minimal Mimir monolith configuration (demo configuration from the official Get started guide, with multi-tenancy enabled)

multitenancy_enabled: true          # the demo original sets false; this lesson enables it to use X-Scope-OrgID
tenant_federation:
  enabled: true                     # allows cross-tenant queries with X-Scope-OrgID: a|b (Module 4)
blocks_storage:
  backend: filesystem
  bucket_store:
    sync_dir: /data/tsdb-sync
  filesystem:
    dir: /data/blocks
  tsdb:
    dir: /data/tsdb
compactor:
  data_dir: /data/compactor
  sharding_ring:
    kvstore:
      store: memberlist
distributor:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: memberlist
ingester:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: memberlist
    replication_factor: 1
ruler_storage:
  backend: filesystem
  filesystem:
    dir: /data/rules
server:
  http_listen_port: 9009
  log_level: warn
store_gateway:
  sharding_ring:
    replication_factor: 1

4. Mimir HTTP endpoints

EndpointPurpose
POST /api/v1/pushPrometheus remote write
/prometheus/api/v1/query,/prometheus/api/v1/query_rangePromQL (set the Grafana data source URL to /prometheus)
POST /otlp/v1/metricsOTLP metric ingestion (Module 6)
/ready,/config,/runtime_config,/distributor/all_user_statsreadiness, effective configuration, runtime overrides, per-tenant ingestion statistics
curl -s -H 'X-Scope-OrgID: cluster-lab' \
  'http://localhost:9009/prometheus/api/v1/query?query=count(up)' | jq .data.result

Lab A: deduplicating two Prometheus replicas with Thanos Query

Goal and environment: kind lab, Module 2 already scaled Prometheus to 2 replicas. This lab only enables the sidecar's StoreAPI (no object storage upload), deploys Thanos Query, and verifies deduplication. About 8 minutes.
Enable the sidecar and the discovery Service: in ~/promlab/k8s/kps-part6.yaml the prometheus: section, add:
  thanosService:
    enabled: true
  prometheusSpec:
    # ...keep the existing fields, then append:
    thanos:
      image: quay.io/thanos/thanos:v0.42.5
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait
kubectl -n monitoring get pod prometheus-kps-kube-prometheus-stack-prometheus-0 -o jsonpath='{.spec.containers[*].name}{"\n"}'
kubectl -n monitoring get svc | grep thanos
prometheus config-reloader thanos-sidecar
kps-kube-prometheus-stack-thanos-discovery   ClusterIP   None   <none>   10901/TCP,10902/TCP
Deploy Thanos Query
cat > ~/promlab/part6/thanos-query.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: {name: thanos-query, namespace: monitoring, labels: {app: thanos-query}}
spec:
  replicas: 1
  selector: {matchLabels: {app: thanos-query}}
  template:
    metadata: {labels: {app: thanos-query}}
    spec:
      containers:
      - name: thanos-query
        image: quay.io/thanos/thanos:v0.42.5
        args:
        - query
        - --http-address=0.0.0.0:10902
        - --grpc-address=0.0.0.0:10901
        - --endpoint=dnssrv+_grpc._tcp.kps-kube-prometheus-stack-thanos-discovery.monitoring.svc.cluster.local
        - --query.replica-label=prometheus_replica
        ports:
        - {name: http, containerPort: 10902}
        - {name: grpc, containerPort: 10901}
        readinessProbe: {httpGet: {path: /-/ready, port: http}}
        resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}}
---
apiVersion: v1
kind: Service
metadata: {name: thanos-query, namespace: monitoring}
spec:
  selector: {app: thanos-query}
  ports:
  - {name: http, port: 10902, targetPort: http}
EOF
kubectl apply -f ~/promlab/part6/thanos-query.yaml
kubectl -n monitoring rollout status deploy/thanos-query
kubectl -n monitoring port-forward svc/thanos-query 10902 &
Compare with and without deduplication
q='count(up{namespace="myapp"})'
curl -sG localhost:10902/api/v1/query --data-urlencode "query=$q" --data-urlencode dedup=false | jq -r '.data.result[0].value[1]'
curl -sG localhost:10902/api/v1/query --data-urlencode "query=$q" --data-urlencode dedup=true  | jq -r '.data.result[0].value[1]'
curl -s localhost:10902/api/v1/stores | jq '.data | to_entries[] | {type: .key, n: (.value|length)}'
4
2
{ "type": "sidecar", "n": 2 }

Without deduplication, each replica's series is counted separately (2 Pods × 2 replicas = 4); after deduplication, they are merged by prometheus_replica into 2.

Lab B: Mimir monolith + kps remote write + Grafana data source

Deploy Mimir (filesystem backend, emptyDir, demo only)
kubectl create namespace mimir
# Save the third part of the “Commands” page as ~/promlab/part6/mimir.yaml
kubectl -n mimir create configmap mimir-config --from-file=mimir.yaml=$HOME/promlab/part6/mimir.yaml
cat > ~/promlab/part6/mimir-deploy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: {name: mimir, namespace: mimir, labels: {app: mimir}}
spec:
  replicas: 1
  selector: {matchLabels: {app: mimir}}
  template:
    metadata: {labels: {app: mimir}}
    spec:
      containers:
      - name: mimir
        image: grafana/mimir:3.2.5
        args: ["-config.file=/etc/mimir/mimir.yaml", "-target=all"]
        ports: [{name: http, containerPort: 9009}]
        readinessProbe: {httpGet: {path: /ready, port: http}, initialDelaySeconds: 15}
        resources: {requests: {cpu: 100m, memory: 256Mi}, limits: {memory: 1Gi}}
        volumeMounts:
        - {name: config, mountPath: /etc/mimir}
        - {name: data, mountPath: /data}
      volumes:
      - {name: config, configMap: {name: mimir-config}}
      - {name: data, emptyDir: {}}
---
apiVersion: v1
kind: Service
metadata: {name: mimir, namespace: mimir}
spec:
  type: NodePort
  selector: {app: mimir}
  ports: [{name: http, port: 9009, targetPort: http, nodePort: 30909}]
EOF
kubectl apply -f ~/promlab/part6/mimir-deploy.yaml
kubectl -n mimir rollout status deploy/mimir --timeout=3m
Make kps remote-write to Mimir (tenant cluster-lab): under prometheusSpec , append:
    remoteWrite:
    - url: http://mimir.mimir.svc:9009/api/v1/push
      headers:
        X-Scope-OrgID: cluster-lab
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait
kubectl -n mimir port-forward svc/mimir 9009 &
sleep 60
curl -s -H 'X-Scope-OrgID: cluster-lab' 'http://localhost:9009/prometheus/api/v1/query?query=count%20by%20(prometheus_replica)(up)' | jq -c '.data.result[]'
{"metric":{"prometheus_replica":"prometheus-kps-kube-prometheus-stack-prometheus-0"},"value":[1763190000,"21"]}
{"metric":{"prometheus_replica":"prometheus-kps-kube-prometheus-stack-prometheus-1"},"value":[1763190000,"21"]}

Both replicas have been written, forming two sets of series. In production, use Mimir's HA tracker (by cluster + replica label, which accepts only one replica and requires KV storage, see “Production case studies”) to deduplicate; in the lab, simply query with max without(prometheus_replica)(…) is enough.

What happens without a tenant header
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost:9009/prometheus/api/v1/query?query=up'
curl -s 'http://localhost:9009/prometheus/api/v1/query?query=up'
401
no org id
Add the Mimir data source in Grafana: in the kps values' grafana: section, add (merged with the Grafana settings from Lesson 5):
grafana:
  additionalDataSources:
  - name: Mimir (cluster-lab)
    type: prometheus
    uid: mimir-lab
    url: http://mimir.mimir.svc:9009/prometheus
    access: proxy
    jsonData:
      httpHeaderName1: X-Scope-OrgID
    secureJsonData:
      httpHeaderValue1: cluster-lab
  - name: Thanos Query
    type: prometheus
    uid: thanos-query
    url: http://thanos-query.monitoring.svc:10902
    access: proxy

After upgrading kps, select “Mimir (cluster-lab)” in Explore and run sum by (status) (rate(myapp_http_requests_total[5m])), and the result should match the local Prometheus result.

(Optional) Watch block generation: wait more than 2 hours,kubectl -n mimir exec deploy/mimir -- ls /data/blocks/cluster-lab a block directory named with a ULID appears. This is the output of the final step of the “write path”, which uploads to object storage (here it is a local directory).
Cleanup: keep Mimir and Thanos Query for Modules 4 and 5 and the capstone lab. When everything is finished: kubectl delete ns mimir; kubectl delete -f ~/promlab/part6/thanos-query.yaml.

Case 1: rolling out Thanos incrementally

Problem: 30 clusters each run their own Prometheus (2 replicas, 15-day local retention) with no global view, and audit requires 400-day retention.

Approach: Phase 1 adds only sidecars and a central Query (connected to the sidecars over internal gRPC), giving an immediate global view and deduplication. Phase 2 configures object storage upload, deploys the store gateway and a singleton compactor (retention: raw 30 days, 5m 180 days, 1h 400 days), and shortens local retention to 2 days. Phase 3 adds query-frontend (split by day + memcached results cache).

Limitations: Query needs network connectivity to every sidecar; network jitter in one cluster slows queries (mitigate with --query.partial-response / timeout policies).

Case 2: Mimir as a company-wide “metrics service”

Problem: Multiple product lines need unified long-term metric storage, with per-team isolation and chargeback.

Approach: mimir-distributed Helm chart, using cloud Blob/S3 object storage; one tenant per team (X-Scope-OrgID set by each cluster's remote_write header or injected by a gateway); per-tenant ingestion_rate,max_global_series_per_user limits; HA tracker enabled (accept_ha_samples, requires a KV store such as Consul/etcd; check the official docs for the supported KV stores). For each cluster, only the elected one of its two Prometheus replicas is accepted.

Limitations: Many components, and it needs caching (memcached) and capacity planning. Mimir 3.0's ingest storage introduces a Kafka dependency (the classic architecture is still supported), so read the 3.0 release notes before upgrading.

Case 3: hybrid — Thanos Receive

When some clusters sit behind a firewall and cannot be reached by Query, have them remote-write to Thanos Receive (hash ring + replication factor). Receive uploads blocks to the same bucket too, and Query connects to Receive, the sidecars, and the store gateway at the same time. This way Thanos can also cover the “push only, no pull” scenario.

Common errors and fixes

no org id

Cause: Mimir has multi-tenancy enabled, but the request does not include the X-Scope-OrgID header (the Grafana data source or remote_write has no header configured).

Fix: Add the header under remote_write headers: {X-Scope-OrgID: …}; for the Grafana data source, use httpHeaderName1/httpHeaderValue1; or inject it at the gateway layer. In a single-tenant setup you can set multitenancy_enabled: false (the tenant is fixed to anonymous).

err-mimir-sample-out-of-order / out of order sample

Cause: Data for the same series arrives with timestamps earlier than existing samples. Common causes: two HA replicas were changed to write the same label set (the replica label was removed without enabling the HA tracker), or out-of-order OTLP batch data.

curl -s localhost:9009/metrics | grep cortex_discarded_samples_total

Fix: Keep the replica label and the HA tracker; or set the tenant's out_of_order_time_window (Mimir supports a per-tenant out-of-order window).

Thanos Query: found duplicate series / multiple stores with identical label sets on the Stores page

Cause: Multiple Prometheus servers have the same external_labels (for example, two clusters both named cluster: lab), so Query cannot tell them apart.

curl -s localhost:10902/api/v1/stores | jq '.data[][] | .labelSets'

Fix: Make sure cluster names are globally unique, and that the replica label differs only between replicas.

thanos compact: "critical error detected; halting" / overlapping blocks

Cause: Blocks with overlapping time ranges and identical label sets appear in the bucket. Common causes: uploading after Prometheus local compaction was enabled, or running two compactors.

thanos tools bucket inspect --objstore.config-file=objstore.yml | head -30
thanos tools bucket verify --objstore.config-file=objstore.yml --issues=overlapped_blocks

Fix: Confirm there is only one compactor; confirm Prometheus's min and max block duration are both 2h; handle overlapping blocks per the official docs (mark them for deletion if necessary). Queries still work while the compactor is down, but the block count will keep growing.

Mimir startup log: error initialising module: ... mkdir /data/...: permission denied

Cause: The image runs as non-root, and the mounted volume is not writable.

Fix: Use emptyDir, or set securityContext.fsGroup on the PVC.

Command-line exercises

1. Write the Thanos Query startup flags to discover thanos-sidecars.monitoring.svc gRPC endpoints via DNS SRV, and deduplicate by replica label.

Answer
thanos query --http-address=0.0.0.0:10902 \
  --endpoint=dnssrv+_grpc._tcp.thanos-sidecars.monitoring.svc.cluster.local \
  --query.replica-label=replica

2. Use curl to query the Mimir tenant cluster-lab 's count(up).

Answer
curl -sG -H 'X-Scope-OrgID: cluster-lab' http://localhost:9009/prometheus/api/v1/query --data-urlencode 'query=count(up)'

Scenario analysis: A team's Thanos queries over a 90-day range are very slow. Checking shows the bucket holds 30,000 two-hour blocks and no 5m or 1h resolution data. What is the likely cause?

Answer

The compactor is not running or has been halted for a long time (for example, it stopped after encountering overlapping blocks), so blocks were never compacted or downsampled. Check the compactor logs and thanos_compact_halted metrics, fix the overlapping blocks, and restart it. Also allow automatic downsampling resolution selection in Query/Grafana (max_source_resolution=auto).

Verified instructional videos

▶
Thanos (Multi Cluster Prometheus) Tutorial: Global View - Long Term Storage - Kubernetes — Anton Putra
English · 2023 · hands-on deployment of Thanos global view and long-term storage
▶
Thanos - Transforming Prometheus to a Global Scale in a Seven Simple Steps — Grafana
English · how to introduce Thanos components step by step
▶
Introducing Grafana Mimir — Grafana
English · official introduction to Mimir at release (2022; for the 3.x architecture, follow the docs)
▶
Getting started with Grafana Mimir — Grafana
English · official getting-started demo

Official documentation

Video storyboard script

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visuals: Prometheus data directory: a row of 2-hour block directories, next to a disk capacity bar that is nearly full.
Narration: Prometheus creates an immutable block every two hours. The idea behind long-term storage is simple: put the blocks into object storage.
Shot 2 · 0:25–1:05
Visuals: Thanos: the sidecar uploads blocks to the bucket; Query asks the sidecar and the store gateway at the same time, then merges the two copies into one using the replica label.
Narration: Thanos works alongside the existing Prometheus, and the query layer handles merging and deduplication.
Shot 3 · 1:05–1:45
Visuals: Mimir: remote write enters the distributor, which hashes series across three ingesters; blocks are uploaded after two hours; at query time, the querier asks the ingesters and the store-gateway at the same time.
Narration: Mimir is a multi-tenant service, and Prometheus only needs remote write.
Shot 4 · 1:45–2:10
Visuals: The compactor merges many small blocks into larger blocks, and merges three replicas into one.
Narration: Don't forget the compactor: without it, queries get slower and slower, and storage gets more and more expensive.
or score ≥ 70% on the quiz

Module 4 · Multi-cluster and multi-tenancy

21:00 – 28:00 · Use cluster labels to tell “where the data came from” apart, and tenants to tell “who the data belongs to” apart
7 minMimir tenants · tenant_federation · prom-label-proxy★★★★ Essential for platform teams
Learning objectives
  • Distinguish label dimension (cluster,env,region) and tenant dimension (isolation, limits, billing), and know when labels alone are enough and when tenants are needed.
  • Write per tenant in Mimir (X-Scope-OrgID), query across tenants (a|b and __tenant_id__), and configure per-tenant limits (runtime overrides).
  • Know the Prometheus/Thanos “query isolation” options: prom-label-proxy enforces labels, and Grafana uses per-team data sources.
  • On a second kind cluster lab-b , use Agent mode to write to a separate Mimir tenant, and trigger a tenant limit.
Prerequisites: Module 1 remote write, Module 3 Mimir. Priority:★★★★

What: two orthogonal dimensions

DimensionImplementationWhat it providesWhat it does not provide
Source label (multi-cluster)Each Prometheus's external_labels: {cluster, region, env}distinguishes sources within the same storage, and supports aggregation and alerting by clusterNo isolation: anyone who can query can see all clusters
Tenant (multi-tenancy)Mimir: the per-request X-Scope-OrgID; Thanos Receive: tenant header (default THANOS-TENANT, attached at write time as the tenant_id label)data isolation, per-tenant limits, retention, billing, fair query queuingCross-tenant queries require explicitly enabling federated queries

Why: why platforms need tenants

  • Blast radius: a team ships a metric with a user_id label (cardinality explosion). It should only exhaust its own quota, not overwhelm the company-wide ingesters.
  • Access control: the security team requires that Team A cannot see Team B's business metrics (for example, transaction volume).
  • Cost allocation: track active series and sample rate per tenant (/distributor/all_user_stats,cortex_ingester_active_series) for showback/chargeback.

How: common ways to divide tenants

ModelExampleProsCons
One tenant per clustercluster-lab,cluster-lab-bSimplest write configuration (cluster-level remote_write header)Teams within the same cluster share a quota
One tenant per teamteam-paymentsQuotas and permissions match the org structureWrites must be split by namespace within the same cluster (multiple remote_write entries + write_relabel_configs filtering, or multiple Prometheus/Agent instances)
One tenant per environmentprod,nonprodnon-production does not affect productionNo isolation between teams

Cross-tenant queries: after enabling tenant_federation.enabled: true in Mimir, the query header can be set to X-Scope-OrgID: cluster-lab|cluster-lab-b, and each series in the result carries the __tenant_id__ label showing its source tenant. This suits a “global SRE view” data source and should not be open to everyone.

Query isolation (without Mimir): put a prom-label-proxyin front of Prometheus/Thanos Query, which forcibly rewrites every PromQL query to include a label matcher (such as namespace="payments"), used together with an authenticating proxy.

When: when you really need multi-tenancy

  • A single platform team where everyone can see all data: Just use the cluster label is enough, no need to introduce tenants.
  • Multiple teams that need quotas or isolation: Mimir tenants (or the “workspaces” of managed services; the Azure Monitor workspace in Lesson 3 and the AMP workspace in Lesson 4 are essentially tenant boundaries too).
Common misconceptions① “The tenant header is set by the client, so it prevents unauthorized access”: the tenant header is not authentication! Anyone who can reach Mimir can forge the X-Scope-OrgID; in production you must put an authentication gateway in front of Mimir (such as GEM's gateway or an Nginx + OIDC proxy) that injects the tenant header based on identity. ② “cluster label can be renamed at any time”: renaming creates entirely new series, and every dashboard and alert that filters by cluster must be updated at the same time, so settle the naming up front (ideally matching the cloud resource name). ③ “Cross-tenant federated queries copy data together”: no, they only read multiple tenants at query time.

Architecture diagram: two clusters, two tenants, one Mimir

kind lab kps Prometheus ×2external_labels: cluster=labX-Scope-OrgID: cluster-lab kind lab-b kps PrometheusAgentexternal_labels: cluster=lab-bX-Scope-OrgID: cluster-lab-b Mimir (NodePort 30909) distributor: reads the tenant header → checks overrides limits TSDB tenantcluster-lab TSDB tenantcluster-lab-b runtime overrides:cluster-lab-b.max_global_series_per_user data source “lab team”X-Scope-OrgID: cluster-lab data source “lab-b team”X-Scope-OrgID: cluster-lab-b data source “Global SRE” (restricted)cluster-lab|cluster-lab-b → __tenant_id__
Figure 4-1: on write, the remote_write header decides the tenant; on query, the header on the Grafana data source decides which tenants are visible. In production, the header is injected by the authentication gateway

Flowchart: how the distributor evaluates a write request

Has tenant header?No → 401 no org id Rate limitingestion_rate → 429 Sample validationlabel count/length, timestamp → 400 ingester: series limitmax_global_series → 400 Write to tenant TSDB200 OK 429 / 5xx → Prometheus retries; 400 → Prometheus drops the batch (no retry), and the data is lost permanently
Figure 4-2: the status code determines the sender's behavior. Data rejected with 400 is not resent, so an alert must fire when the series limit is hit

Tenant routing and limit simulator

Adjust the parameters, then click “Send write request” or “Send query” to simulate Mimir's decision process. Limit names and error IDs come from the Mimir docs.


Sample rate of this request (samples/second):8000

Current active series count for this tenant:400

runtime overrides (simulated)
overrides:
  cluster-lab-b:
    ingestion_rate: 10000
    max_global_series_per_user: 500
# Other tenants use default limits (Mimir defaults apply)
① Tenant header
② Rate limit
③ Sample validation
④ Series limit
⑤ Result
Set the parameters and send.

Core commands and configuration

Command / configurationPurposeKey points
external_labels.clusterSource identifierglobally unique, decide early
remote_write[].headers.X-Scope-OrgIDWrite tenantsafer when injected by the gateway in production
tenant_federation.enabledCross-tenant queryQuery header a|b, results carry the __tenant_id__
runtime_config.file + overrides:Per-tenant limits (hot-reloaded)ingestion_rate,ingestion_burst_size,max_global_series_per_user,compactor_blocks_retention_period
GET /distributor/all_user_statsPer-tenant ingestion statisticsseries count, sample rate
prom-label-proxy --label=namespace --upstream=…Query isolation outside of Mimirrequires an authenticating proxy to inject label values

1. Mimir runtime overrides (per-tenant limits)

runtime_config:
  file: /etc/mimir/runtime.yaml
overrides:
  cluster-lab-b:
    ingestion_rate: 10000                 # samples/second
    ingestion_burst_size: 20000
    max_global_series_per_user: 500       # set deliberately low, to trigger in the lab
    compactor_blocks_retention_period: 30d
  cluster-lab:
    max_global_series_per_user: 300000
curl -s localhost:9009/runtime_config | head -20          # view the effective overrides
curl -s localhost:9009/distributor/all_user_stats           # per-tenant statistics (HTML/text, depends on version)

2. Cross-tenant queries

curl -sG -H 'X-Scope-OrgID: cluster-lab|cluster-lab-b' \
  http://localhost:9009/prometheus/api/v1/query \
  --data-urlencode 'query=count by (__tenant_id__, cluster) (up)' | jq -c '.data.result[]'
{"metric":{"__tenant_id__":"cluster-lab","cluster":"lab"},"value":[1763190000,"42"]}
{"metric":{"__tenant_id__":"cluster-lab-b","cluster":"lab-b"},"value":[1763190000,"18"]}

3. Monitor tenant limits (on Mimir's own metrics)

sum by (user, reason) (rate(cortex_discarded_samples_total[5m])) > 0
sum by (user) (cortex_ingester_active_series)

Many of Mimir's internal metrics still use the cortex_ prefix, and the tenant label name is user.

4. prom-label-proxy (Prometheus / Thanos scenario)

prom-label-proxy --label=namespace --upstream=http://thanos-query.monitoring.svc:10902 \
  --insecure-listen-address=0.0.0.0:8080
# Callers must pass the namespace parameter; queries are forced to include {namespace="payments"}:
curl -sG 'http://localhost:8080/api/v1/query?namespace=payments' --data-urlencode 'query=up'

Lab: second cluster lab-b Write to a separate tenant in Agent mode and trigger the series limit

Goal and environment: Module 0 already created the kind lab-b; the Mimir from Module 3 is exposed in lab via NodePort 30909. Memory usage increases by about 1–1.5 GiB. If memory is insufficient, the Docker Agent container from Module 1 can be used instead of lab-b (changing the tenant header to cluster-lab-b).
Add runtime overrides to Mimir
cd ~/promlab/part6
cat >> mimir.yaml <<'EOF'
runtime_config:
  file: /etc/mimir/runtime.yaml
EOF
cat > runtime.yaml <<'EOF'
overrides:
  cluster-lab-b:
    max_global_series_per_user: 500
EOF
kubectl --context kind-lab -n mimir create configmap mimir-config \
  --from-file=mimir.yaml --from-file=runtime.yaml --dry-run=client -o yaml | kubectl --context kind-lab apply -f -
kubectl --context kind-lab -n mimir rollout restart deploy/mimir
kubectl --context kind-lab -n mimir rollout status deploy/mimir

Note: emptyDir data is cleared when the Pod is recreated; this is a known limitation of the demo environment. Afterwards, to change runtime.yaml you only need to update the ConfigMap, and Mimir reloads it periodically without a restart.

In lab-b install kps (Agent mode, with AM/Grafana/rules disabled)
LAB_IP=$(docker inspect -f '{{.NetworkSettings.Networks.kind.IPAddress}}' lab-control-plane)
cat > ~/promlab/k8s/kps-lab-b.yaml <<EOF
alertmanager: {enabled: false}
grafana: {enabled: false}
defaultRules: {create: false}
prometheus:
  agentMode: true
  prometheusSpec:
    externalLabels:
      cluster: lab-b
    remoteWrite:
    - url: http://${LAB_IP}:30909/api/v1/push
      headers:
        X-Scope-OrgID: cluster-lab-b
EOF
helm --kube-context kind-lab-b upgrade --install kps prometheus-community/kube-prometheus-stack \
  -n monitoring --create-namespace --version 93.3.0 -f ~/promlab/k8s/kps-lab-b.yaml --wait
kubectl --context kind-lab-b -n monitoring get prometheusagent,pods

In the kps prometheus.agentMode let the Operator create the PrometheusAgent resource; the values comments note that in agent mode, rules, queries, alerting, Thanos, and similar features are unavailable. prometheusSpec which fields are passed to the PrometheusAgent depends on the chart templates.

Observe the limit being triggered
kubectl --context kind-lab-b -n monitoring logs -l app.kubernetes.io/name=prometheus -c prometheus --tail=50 | grep -i 'remote' | tail -3
level=ERROR source=queue_manager.go:2042 msg="non-recoverable error" component=remote remote_name=64eae4 url=http://172.18.0.2:30909/api/v1/push failedSampleCount=454 … err="server returned HTTP status 400 Bad Request: send data to ingesters: failed pushing to ingester …: user=cluster-lab-b: per-user series limit of 500 exceeded (err-mimir-max-series-per-user). To adjust the related per-tenant limit, configure -ingester.max-global-series-per-user, or contact your service administrator. (sampled 1/10)"
curl -s localhost:9009/metrics | grep 'cortex_discarded_samples_total' | grep cluster-lab-b
cortex_discarded_samples_total{group="",reason="per_user_series_limit",user="cluster-lab-b"} 18342

This is the live demonstration of “400 = permanent drop”: lab-b All new series beyond 500 are lost, while the cluster-lab is unaffected. This is the value of tenant isolation.

Raise the limit and verify cross-tenant queries
sed -i 's/max_global_series_per_user: 500/max_global_series_per_user: 50000/' runtime.yaml
kubectl --context kind-lab -n mimir create configmap mimir-config --from-file=mimir.yaml --from-file=runtime.yaml \
  --dry-run=client -o yaml | kubectl --context kind-lab apply -f -
sleep 90   # wait for the ConfigMap sync and runtime config reload
curl -s localhost:9009/runtime_config | grep -A2 cluster-lab-b
# then run the cross-tenant query from the second part of the “Commands” page
Add a “Global SRE” data source in Grafana: in kps grafana.additionalDataSources add another httpHeaderValue1: cluster-lab|cluster-lab-b data source (uid mimir-global), and Module 7 will grant query permission on it only to the SRE team (data source permissions require Enterprise/Cloud; in OSS, use a separate organization for isolation).
Cleanup: kind delete cluster --name lab-b (the capstone lab still uses these, so delete them last).

Case 1: one team's cardinality explosion did not take down the platform

Problem: The payments team released a new version that added a customer_id label to a request counter, and active series grew from 200K to 3M within 10 minutes.

Approach: The team's tenant max_global_series_per_user limit was set to 500K; the excess was rejected with 400, and other tenants were unaffected. A platform alert rate(cortex_discarded_samples_total{reason="per_user_series_limit"}[5m]) > 0 notified the team, which rolled back and switched to exemplars to associate the user dimension.

Limitations: Rejected series data is lost permanently, including the team's “normally behaving” new series (such as new Pods). Limits therefore need headroom, and an alert should fire at 80% (cardinality governance is covered in Lesson 7).

Case 2: cluster naming convention

One company mandated that the cluster label = cloud resource name (such as aks-prom-lab,prom-lab), plus region,env,cloud, and the first variable on every Grafana dashboard is cluster. As a result, cross-cloud comparisons (Azure in Lesson 3, AWS in Lesson 4) only require switching the variable.

Case 3: tenant header security

Problem: A penetration test found that developers could curl Mimir directly and change the X-Scope-OrgID to another team.

Approach: Mimir is reachable only on the internal network; all reads and writes go through an authentication gateway (OIDC/mTLS), which overrides the tenant header based on identity; the Grafana data source's tenant header is stored in secureJsonData , and only Admins can edit data sources.

Common errors and fixes

per-user series limit of 500 exceeded (err-mimir-max-series-per-user)

Cause: The tenant's active series count exceeded the max_global_series_per_user.

sum by (user) (cortex_ingester_active_series)
topk(10, count by (__name__) ({__name__=~".+"}))   # find the largest metrics on this tenant's data source

Fix: Reduce cardinality (Lesson 7) or raise the override value for this tenant; limit changes are hot-reloaded through the runtime config.

the request has been rejected because the tenant exceeded the ingestion rate limit (err-mimir-tenant-max-ingestion-rate)

Cause: The sample rate exceeded the ingestion_rate (returns 429; the sender retries and backlogs). Common after the sender has been disconnected for a long time and then resends everything at once.

Fix: Raise the ingestion_rate and ingestion_burst_size; or reduce the send volume. Refer to the Mimir runbook for exact error text and IDs.

Grafana: query results contain a __tenant_id__ label, causing duplicate panel legend entries

Cause: A data source using cross-tenant federated queries is in use.

Fix: In the query, use sum without (__tenant_id__), or have team panels use single-tenant data sources.

lab-b Agent log: dial tcp 172.18.0.2:30909: connect: connection refused

Cause: The Mimir Service is not NodePort, or the nodePort differs; or LAB_IP is wrong (the network name from docker inspect is not kind).

kubectl --context kind-lab -n mimir get svc mimir
docker network inspect kind | jq '.[0].Containers[] | {Name, IPv4Address}'
Command-line exercises

1. Write runtime overrides that set tenant team-payments active series limit to 200000 and sample rate limit to 50000.

Answer
overrides:
  team-payments:
    max_global_series_per_user: 200000
    ingestion_rate: 50000

2. Write a PromQL query that, on Mimir's own metrics, finds the tenants that had samples dropped in the last 5 minutes, and the reasons.

Answer
sum by (user, reason) (rate(cortex_discarded_samples_total[5m])) > 0

Scenario analysis: A company has 4 AKS clusters (2 prod, 2 nonprod), and 10 product teams share the clusters (separated by namespace). Security requires each team to see only the metrics of its own namespace, while SRE can see everything. Design a tenant and data source plan.

Answer

Option A (per-team tenants): each cluster's Prometheus configures 10 remote_write entries, each using write_relabel_configs keep for the matching namespace with the team tenant header, and another remote_write sends cluster-level infrastructure metrics to the platform tenant; Grafana has one data source per team (fixed tenant header), and SRE uses a cross-tenant data source. Option B (per-environment tenants + enforced labels): tenant prod/nonprod, with prom-label-proxy or the gateway enforcing namespace filtering in front of queries. A has stronger isolation and allows per-team limits, but the write configuration is complex and infrastructure metrics need separate handling; B is simpler to write, but isolation depends on the proxy being configured correctly. Every option must have the authentication gateway inject the tenant header/label, rather than trusting the client.

Verified instructional videos

▶
Absorbing Thanos Infinite Powers for Multi-Cluster Telemetry - Bartlomiej Płotka — CNCF [Cloud Native Computing Foundation]
English · Thanos maintainer on multi-cluster telemetry
▶
Migrating to Grafana Mimir — Grafana
English · official migration demo (2022)

Official documentation

Video storyboard script

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

Shot 1 · 0:00–0:20
Visuals: Metrics from two clusters flow into the same storage, in blue and orange, distinguished by the cluster label.
Narration: Multi-cluster is first a labeling problem: every data point needs to know where it came from.
Shot 2 · 0:20–0:55
Visuals: The two colored data streams enter Mimir, then each goes into one of two locked cells (tenants), each cell with a quota scale.
Narration: Multi-tenancy is an isolation problem: who the data belongs to, who can see it, and how much they can use.
Shot 3 · 0:55–1:30
Visuals: The orange cell's scale overflows, new data is blocked by a red 400, and the blue cell carries on as normal.
Narration: If one team's cardinality explodes, it only exhausts its own quota.
Shot 4 · 1:30–1:50
Visuals: An attacker forges the tenant header and is blocked by the authentication gateway.
Narration: The tenant header is not authentication, so it must be injected by the gateway.
or score ≥ 70% on the quiz

Module 5 · SLOs and error budgets: burn rate alerts

28:00 – 35:00 · Stop alerting on “error rate > 1%”; alert on “how fast the error budget is burning” instead
7 minGoogle SRE Workbook · Sloth v0.16.0★★★★★ The key to alert quality
Learning objectives
  • Define SLIs for myapp (ratio of non-5xx requests, ratio of requests completed within 500 ms) and an SLO (99.9% over 30 days), and calculate the error budget.
  • Understand burn rate = current error rate ÷ (1 − SLO), and that the 14.4 / 6 / 1 thresholds correspond to consuming 2% / 5% / 10% of the budget respectively.
  • Write multi-window, multi-burn-rate recording rules and alerts (a long window plus a short window at 1/12 of its length), and test them with promtool test rules unit tests.
  • Know that tools such as Sloth, Pyrra, and OpenSLO can generate these rules automatically.
Prerequisites: recording and alerting rules (Lesson 2), PrometheusRule (Lesson 5), histogram and rate() (Lesson 1). Priority:★★★★★

What: SLI, SLO, error budget, burn rate

TermDefinitionmyapp example
SLI (service level indicator)good events / all eventsAvailability SLI = non-5xx requests / all requests (from myapp_http_requests_total{status}); latency SLI = requests ≤ 0.5 s / all requests (from myapp_http_request_duration_seconds_bucket{le="0.5"})
SLO (service level objective)The target value of an SLI over a time window99.9% available over a 30-day rolling window; 99% of requests ≤ 0.5 s
Error budget1 − SLO0.1%: about 43.2 minutes of “total failure” over 30 days, or 1,000 failures per 1 million requests
burn rateCurrent error rate ÷ error budgetError rate 1.44% ÷ 0.1% = 14.4: at this pace, the 30-day budget burns out in 50 hours

Why: why threshold alerts are poor

  • “5-minute error rate > 1%”: at low traffic in the early morning, 3 errors trigger it (false positive); yet a sustained 0.5% error rate never triggers it, even though it burns through the 99.9% monthly budget in 6 days (false negative).
  • Burn rate turns “severity” into one measure of “how fast the commitment to users is threatened”. The threshold is independent of any specific service and can be reused across the company.

How: multiple windows, multiple burn rates (recommended by the Google SRE Workbook)

SeverityLong windowShort windowburn rateBudget consumed at trigger (30 days)Error rate threshold (SLO 99.9%)
Page (call immediately)1h5m14.42%1.44%
Page6h30m65%0.6%
Ticket3d6h110%0.1%
  • Why a long window: Ensures the alert fires only when the impact is significant (a meaningful share of the budget is consumed), avoiding momentary blips.
  • Why a short window (1/12 of the long window): After a fix, the long-window average takes a long time to come back down; requiring the short window to also exceed the threshold lets the alert recover within minutes of the fix.
  • Math: Budget consumed = burn rate × long window ÷ SLO period. 14.4 × 1h ÷ 720h = 2%; 6 × 6h ÷ 720h = 5%; 1 × 72h ÷ 720h = 10%.

When: when to use it

  • For user-facing services with clear request traffic: use multi-window, multi-burn-rate alerts.
  • For services with very low traffic (a few dozen requests per hour): ratios are very noisy, so consider synthetic probes (blackbox) to add traffic, a longer window, or an event-count threshold.
  • Batch processing and data freshness: change the SLI to “ratio of jobs finished on time” or “proportion of time that data latency < X”.
Common misconceptions① “The higher the SLO the better, so set 99.99%”: a 99.99% monthly budget is only about 4.3 minutes, so a single deployment blip burns it all, and the team is forced to freeze releases; SLOs should be based on user needs and historical data. ② “Error ratio can be directly avg(rate(errors)/rate(total))”: averaging ratios across multiple Pods is wrong; you must first sum sum the numerator and the denominator, then divide. ③ “A 3d-window rate is too expensive, so skip it”: you can first record 5m counts, then use sum_over_time to combine them, or evaluate the long-window rules on Mimir/Thanos Ruler; local Prometheus retention must be ≥ the longest window.

Schematic: error budget consumed over time

100%0%30 days0 burn rate = 1: exhausted right at month end Incident: burn rate ≈ 14.4burns 2% in 1 hour (page alert) Remaining budget can be used for releases and experiments Remaining error budget (SLO 99.9% · 30 days)
Figure 5-1: the slope of the budget curve is the burn rate; the steeper the slope, the sooner a human needs to step in

Flowchart: from counter to alert

myapp_http_requests_total{status=~"5.."} / total Recording rule (every 30s)myapp:sli_errors:ratio_rate5m…ratio_rate30m · rate1h…ratio_rate6h · rate3dsum first, then divide Alerting rule(1h > 14.4·ε and 5m > 14.4·ε)or (6h > 6·ε and 30m > 6·ε) → page(3d > ε and 6h > ε) → ticketε = 1 − SLO = 0.001 Alertmanager routingcritical → PagerDuty · warning → ticket
Figure 5-2: the three layers of SLO alerting: SLI recording rules → multi-window alerts → routing by severity

Core interaction: burn rate calculator

Set the SLO and the error rate of a sudden incident. The calculator shows the error budget, burn rate, time to budget exhaustion, and, for each of the three multi-window rules,whether it fires, how soon it fires, and how much budget has been consumed when it fires (assuming constant traffic, with the error rate jumping from 0 to the set value at t=0).


Error rate during the incident:2.00%

Rule's for:2 min

Core rules and commands

ObjectPurposeKey points
Recording rule myapp:sli_errors:ratio_rate<window>Precomputes the error ratio for each windowNaming follows level:metric:operations
Alert MyappErrorBudgetBurnpage level (14.4 / 6)severity: critical
Alert MyappErrorBudgetBurnSlowticket level (1)severity: warning
promtool test rulesRule unit testsinput_series Extended approach 0+20x120
sloth generate -i slo.yamlGenerate rules from SLO specsSloth v0.16.0 (2026-04)

1. SLI recording rules (Prometheus rule file format, for easy promtool testing)

groups:
  - name: myapp-slo-sli
    interval: 30s
    rules:
      - record: myapp:sli_errors:ratio_rate5m
        expr: |
          sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[5m]))
          /
          sum(rate(myapp_http_requests_total{namespace="myapp"}[5m]))
      - record: myapp:sli_errors:ratio_rate30m
        expr: |
          sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[30m]))
          /
          sum(rate(myapp_http_requests_total{namespace="myapp"}[30m]))
      - record: myapp:sli_errors:ratio_rate1h
        expr: |
          sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[1h]))
          /
          sum(rate(myapp_http_requests_total{namespace="myapp"}[1h]))
      - record: myapp:sli_errors:ratio_rate6h
        expr: |
          sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[6h]))
          /
          sum(rate(myapp_http_requests_total{namespace="myapp"}[6h]))
      - record: myapp:sli_errors:ratio_rate3d
        expr: |
          sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[3d]))
          /
          sum(rate(myapp_http_requests_total{namespace="myapp"}[3d]))
      # Latency SLI: ratio of requests over 0.5s (le="0.5" must be one of the histogram bucket boundaries)
      - record: myapp:sli_latency_slow:ratio_rate5m
        expr: |
          1 - (
            sum(rate(myapp_http_request_duration_seconds_bucket{namespace="myapp",le="0.5"}[5m]))
            /
            sum(rate(myapp_http_request_duration_seconds_count{namespace="myapp"}[5m]))
          )
  - name: myapp-slo-alerts
    rules:
      - alert: MyappErrorBudgetBurn
        expr: |
          (
            myapp:sli_errors:ratio_rate1h > (14.4 * 0.001)
            and
            myapp:sli_errors:ratio_rate5m > (14.4 * 0.001)
          )
          or
          (
            myapp:sli_errors:ratio_rate6h > (6 * 0.001)
            and
            myapp:sli_errors:ratio_rate30m > (6 * 0.001)
          )
        for: 2m
        labels:
          severity: critical
          slo: myapp-availability
        annotations:
          summary: "myapp error budget burning fast (SLO 99.9%)"
          description: "1h error rate {{ $value | humanizePercentage }}; at this rate the 30-day budget will be exhausted soon."
      - alert: MyappErrorBudgetBurnSlow
        expr: |
          myapp:sli_errors:ratio_rate3d > 0.001
          and
          myapp:sli_errors:ratio_rate6h > 0.001
        for: 1h
        labels:
          severity: warning
          slo: myapp-availability

In the or expression, the value taken is $value from the left-hand series of the triggering branch. In production, the SLO target is often made into a series (such as myapp:slo_target) rather than hardcoding 0.001, so multiple SLOs can share the alert expression.

2. Unit tests

rule_files:
  - myapp-slo-rules.yml
evaluation_interval: 30s
tests:
  - interval: 1m
    input_series:
      # 1000 requests per minute, 20 of which are 5xx → error rate 2% → burn rate 20
      - series: 'myapp_http_requests_total{namespace="myapp",route="/",method="GET",status="500"}'
        values: '0+20x180'
      - series: 'myapp_http_requests_total{namespace="myapp",route="/",method="GET",status="200"}'
        values: '0+980x180'
    alert_rule_test:
      - eval_time: 1m
        alertname: MyappErrorBudgetBurn
        exp_alerts: []                 # just started, the for: 2m duration is not yet met
      - eval_time: 30m
        alertname: MyappErrorBudgetBurn
        exp_alerts:
          - exp_labels:
              severity: critical
              slo: myapp-availability
            exp_annotations:
              summary: "myapp error budget burning fast (SLO 99.9%)"
              description: "1h error rate 2%; at this rate the 30-day budget will be exhausted soon."
    promql_expr_test:
      - expr: myapp:sli_errors:ratio_rate5m
        eval_time: 30m
        exp_samples:
          - labels: 'myapp:sli_errors:ratio_rate5m'
            value: 0.02
cd ~/promlab/part6 && promtool check rules myapp-slo-rules.yml && promtool test rules myapp-slo-test.yml
Checking myapp-slo-rules.yml
  SUCCESS: 8 rules found

Unit Testing:  myapp-slo-test.yml
  SUCCESS

promtool compares both the labels and annotations of alerts, so the exp_annotations must match the rendered annotations: and returns the value of the left-hand series,$value that is, the 1h error rate 0.02, which after humanizePercentage is rendered as 2%.

3. Convert to a PrometheusRule (kps selects it via release: kps )

cat > ~/promlab/part6/myapp-slo-prometheusrule.yaml <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: myapp-slo
  namespace: myapp
  labels:
    release: kps
spec:
EOF
sed 's/^/  /' ~/promlab/part6/myapp-slo-rules.yml >> ~/promlab/part6/myapp-slo-prometheusrule.yaml
kubectl apply -f ~/promlab/part6/myapp-slo-prometheusrule.yaml

4. Remaining budget (suitable for querying 30 days on Mimir/Thanos)

1 - (
  sum(increase(myapp_http_requests_total{namespace="myapp",status=~"5.."}[30d]))
  /
  sum(increase(myapp_http_requests_total{namespace="myapp"}[30d]))
) / 0.001

The result is the “remaining budget ratio”: 1 means none has been used, 0 means exactly used up, and a negative number means overspent. Local Prometheus retention is only 2 days (set in Module 2), so 30-day queries must run on the Mimir data source.

5. Generate the same rules with Sloth

version: "prometheus/v1"
service: "myapp"
labels:
  owner: "team-myapp"
slos:
  - name: "requests-availability"
    objective: 99.9
    description: "myapp non-5xx ratio"
    sli:
      events:
        error_query: sum(rate(myapp_http_requests_total{namespace="myapp",status=~"5.."}[{{.window}}]))
        total_query: sum(rate(myapp_http_requests_total{namespace="myapp"}[{{.window}}]))
    alerting:
      name: MyappHighErrorRate
      page_alert:
        labels: {severity: critical}
      ticket_alert:
        labels: {severity: warning}
sloth generate -i slo.yaml -o myapp-sloth-rules.yml

The windows and thresholds Sloth generates by default are the SRE Workbook's multi-window, multi-burn-rate combination; for field names, follow the official Sloth repository for the current version. Pyrra provides similar capabilities with a UI (CRD ServiceLevelObjective), and Grafana Cloud offers a managed Grafana SLO.

Lab: deploy SLO rules for myapp and inject a fault

Goal and environment: kind lab, myapp in namespace myapp, selected by kps's rule selector release: kps. About 15 minutes (to see the 1h window, actual firing takes several to more than ten minutes).
Local unit tests: run the second part of the “Commands” page, and make sure SUCCESS.
Deploy the PrometheusRule and confirm it is loaded
kubectl apply -f ~/promlab/part6/myapp-slo-prometheusrule.yaml
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090 &
sleep 60
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[] | select(.name|startswith("myapp-slo")) | .name + " " + (.rules|length|tostring)'
myapp-slo-sli 6
myapp-slo-alerts 2
Generate traffic
kubectl -n myapp run load --image=curlimages/curl:8.11.1 --restart=Never --command -- \
  sh -c 'while true; do curl -s -o /dev/null http://myapp.myapp.svc:5000/; sleep 0.05; done'

You can replace the curl image tag with any version available locally. The Service name and port follow the myapp deployment from Lesson 5 (port 5000).

Inject a fault: make Redis unavailable
kubectl -n myapp scale deploy/redis --replicas=0     # the Redis Deployment name depends on your deployment
sleep 120
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=myapp:sli_errors:ratio_rate5m' | jq -r '.data.result[0].value[1]'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=myapp_redis_up' | jq -r '.data.result[].value[1]'
0.83
0

The myapp counter endpoint depends on Redis and returns 5xx when Redis is unavailable (depending on your myapp implementation: if yours returns 200 and degrades gracefully, you can switch the myapp image to a version that deliberately returns 500, or load-test a nonexistent route and change the SLI to include 404).

Watch the alert: Prometheus UI → Alerts,MyappErrorBudgetBurn first pending, then firing after 2 minutes; it is visible in Alertmanager as severity=critical. Plug the error rate into the calculator on the “Animation” page and compare with the actual firing time.
Recover and observe the role of the short window
kubectl -n myapp scale deploy/redis --replicas=1
sleep 420
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=myapp:sli_errors:ratio_rate1h' | jq -r '.data.result[0].value[1]'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=ALERTS{alertname="MyappErrorBudgetBurn"}' | jq '.data.result | length'
0.09
0

The 1h window's error rate is still as high as 9% (far above the 1.44% threshold), but the 5m short window has dropped to 0,and so the condition no longer holds, and the alert automatically recovers about 5 minutes after the fix. This is the value of the short window.

Cleanup: kubectl -n myapp delete pod load; keep the SLO rules for the capstone lab.

Case 1: from 40 threshold alerts to 6 SLO alerts

Problem: An API team was paged 30 times a week, mostly for error-rate blips during low-traffic periods, while a real chronic fault (0.4% errors lasting 4 days) went unnoticed.

Approach: They defined 3 SLOs (availability, latency, critical transaction success rate), each with a set of multi-window alerts. Pages come only from the 14.4/6 tiers, while the 1 tier only opens tickets. A weekly SLO review looks at the remaining budget to decide whether to freeze releases.

Results and limitations: Pages dropped to 1–2 per week. However, the SLI denominator must first be corrected (excluding health checks and crawler traffic), otherwise the SLI is distorted.

Case 2: low-traffic service

An internal admin console gets only 50 requests per hour, so a single 5xx pushes the 5m error rate to 100%. Approach: add blackbox_exporter synthetic probes (one every 30 seconds) as a supplementary SLI, and add a minimum event count condition to the alert and sum(increase(myapp_http_requests_total[1h])) > 100.

Case 3: where SLO rules are evaluated

A 3d window requires at least 3 days of local retention, and every evaluation scans 3 days of data. At scale, hand the SLO rules to the Mimir ruler (mimirtool rules sync) or Thanos Ruler to evaluate on long-term storage and write the recorded results back. Local Prometheus keeps only short-window rules as a fallback.

Common errors and fixes

Recording rule myapp:sli_errors:ratio_rate5m has no data (Empty query result)

Cause:① When there are no 5xx errors, the numerator is an empty vector,empty / non-empty gives an empty result; ② label mismatch (namespace, status values); ③ the PrometheusRule is not selected.

sum(rate(myapp_http_requests_total{namespace="myapp"}[5m])) by (status)

Fix: Write the numerator as (sum(rate(...{status=~"5.."}[5m])) or vector(0)), so the ratio is 0 when there are no errors; check kubectl get prometheus -n monitoring -o yaml | grep -A3 ruleSelector.

promtool: FAILED: alertname: MyappErrorBudgetBurn, time: 30m, exp:[...], got:[...] (annotation mismatch)

Cause: The expected alert did not specify exp_annotations, but the actual alert carries annotations.

Fix: Add the exp_annotations, or remove the annotations in a test-only rule file.

The alert is still firing 1 hour after the incident was fixed

Cause: Only the long window is used (the short-window condition is missing), or the short-window condition was written as or.

Fix: Long window and short window (1/12 of the long window).

The ratio_rate3d result does not match the 30-day report on Mimir / evaluation times out with “query timed out in expression evaluation”

Cause: Local retention is less than 3 days (set to 2d in this lesson), or the 3d range query is too heavy.

Fix: Increase retention, or move the long-window rules to the Mimir ruler / Thanos Ruler; or use a 5m recording rule + avg_over_time an approximation (note that it must be traffic-weighted to be accurate).

Command-line exercises

1. The SLO is 99.5% (30 days). Write the alert condition for the 6h/30m window at burn rate 6 (using myapp:sli_errors:ratio_rate6h and …ratio_rate30m).

Answer
myapp:sli_errors:ratio_rate6h > (6 * 0.005)
and
myapp:sli_errors:ratio_rate30m > (6 * 0.005)

Error rate threshold 3%.

2. Write the promtool commands: first check the rule file syntax, then run the unit tests.

Answer
promtool check rules myapp-slo-rules.yml
promtool test rules myapp-slo-test.yml

Scenario analysis: myapp's SLO is 99.9% over 30 days. After this morning's release, the error rate stayed at 0.4%, and no page fired. Is the rule wrong? When will a notification occur? How long until the budget is exhausted?

Answer

The rule is not wrong. 0.4% corresponds to a burn rate of 4, which is below the page tier's 14.4 and 6, so no page fires. The ticket tier (burn rate 1, 3d and 6h windows) fires when the 3d-window average error rate exceeds 0.1%. After the error rate jumps from 0 to 0.4%, the ticket fires after about 72h × 0.1/0.4 = 18 hours (if the previous 3 days were clean). At burn rate 4, the 30-day budget runs out in 7.5 days. This is the intended design: chronic problems go to tickets and are handled during working hours, rather than paging in the middle of the night.

Verified instructional videos

▶
How to Alert on SLOs using Error Budget Burn Rate // DoK Talks #81 — Data on Kubernetes Community (DoKC)
English · explanation of error budget burn rate alerts
▶
SLOconf 2022: Petr Hajek - Alerting on High and Low Traffic Using SLOs — Nobl9
English · SLO alerts for high- and low-traffic services (corresponding to Case 2 in this module)

Official and authoritative documentation

Video storyboard script

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

Shot 1 · 0:00–0:20
Visuals: At 3 a.m. the phone rings: “error rate > 1%”, but in reality only 2 requests failed.
Narration: Threshold alerts are both noisy and miss chronic problems.
Shot 2 · 0:20–0:55
Visuals: A “budget tank”: a 30-day budget of 99.9% = 43 minutes; the needle drains as errors flow out.
Narration: The SLO gives us a budget, and the burn rate is the fuel consumption.
Shot 3 · 0:55–1:40
Visuals: Three rows of lights: 14.4 (1h/5m), 6 (6h/30m), 1 (3d/6h). They light up in turn after the incident, and after the fix the short windows go dark first.
Narration: The long window ensures significance; the short window ensures timely recovery.
Shot 4 · 1:40–2:00
Visuals: promtool test rules outputs SUCCESS.
Narration: Rules are code too: test them before going live.
or score ≥ 70% on the quiz

Module 6 · The relationship between OpenTelemetry and Prometheus

35:00 – 42:00 · OTel handles “generating and transporting”, Prometheus handles “storage, querying, and alerting”, plus name and label translation at the boundary between the two
7 minOTLP ingestion · Collector v0.165.0★★★★ Must-know trend
Learning objectives
  • Clearly explain the division of responsibilities between OpenTelemetry (API/SDK, Collector, OTLP protocol, semantic conventions) and Prometheus (scraping, TSDB, PromQL, alerting).
  • Compare four integration paths: Prometheus client library + scraping, OTel SDK → OTLP → Prometheus, Collector scraping + remote write, and the Prometheus exporter in the OTel SDK.
  • Master Prometheus OTLP ingestion: --web.enable-otlp-receiver,/api/v1/otlp/v1/metrics,promote_resource_attributes,translation_strategy,target_info, and the out-of-order window.
  • Know the difference between delta and cumulative temporality, and the experimental otlp-deltatocumulative.
Prerequisites: metric types and histograms (Lesson 1), push/pull from Module 1, and replicas from Module 2. Priority:★★★★

What: what each project is responsible for

CapabilityOpenTelemetryPrometheus
Instrumentation API/SDKA unified multi-language API covering traces / metrics / logsPer-language client libraries (myapp uses the prometheus_client)
Transport protocolOTLP (gRPC 4317 / HTTP 4318),pushtext / OpenMetrics / protobuf exposition formats (pull); remote write (push)
PipelineCollector: receivers → processors → exportersservice discovery + relabeling + scraping
Storage / query / alertingNot provided (left to the backend)TSDB, PromQL, rules, Alertmanager
Resource modelResource attributes (service.name,k8s.pod.name…) separate from data point attributesOnly a flat layer of labels; job/instance come from the scrape target

Why: why you should care about OTel

  • More and more frameworks, SDKs, and cloud services emit OTLP by default. One SDK produces both traces and metrics, making exemplar correlation easy.
  • The Collector is a general-purpose “telemetry router”: the same data can be sent at the same time to Prometheus/Mimir, managed services (Azure Monitor in Lesson 3, ADOT/AMP in Lesson 4), and other backends.
  • Prometheus 3 treats OTLP as a first-class input: a built-in receiver, UTF-8 metric names, and name translation by policy (see the OpenTelemetry guide on prometheus.io).

How: what happens when OTLP is written to Prometheus

  1. Enable the receiver: --web.enable-otlp-receiver (disabled by default, no authentication); endpoint /api/v1/otlp/v1/metrics; on the sender, set HTTP/protobuf, with base URL http://prometheus:9090/api/v1/otlp (/v1/metrics is appended automatically).
  2. Name translation (otlp.translation_strategy):
    • UnderscoreEscapingWithSuffixes (default): http.server.request.duration (unit s, histogram) → http_server_request_duration_seconds_bucket/_sum/_count; monotonic Sum → add _total.
    • UnderscoreEscapingWithoutSuffixes: escapes but adds no suffix (name collisions are possible).
    • NoUTF8EscapingWithSuffixes: keeps dots and similar characters, adds suffixes (relies on UTF-8 name support).
    • NoTranslation: stored as-is (UTF-8); without suffixes, name collisions are possible.
  3. Resource attributes: service.namespace/service.name → job (with a namespace it becomes namespace/name),service.instance.id → instance other resource attributes are not by default added to every metric; instead they go into one target_info series. promote_resource_attributes List the attributes to “promote” to ordinary labels (the official guide gives about 20 recommended attributes).
  4. Out of order: batch sending from multiple Collector replicas causes out-of-order data; the official recommendation is storage.tsdb.out_of_order_time_window: 30m.
  5. Temporality: Prometheus expects cumulative; delta requires the Collector's deltatocumulative processor or the Prometheus experimental feature --enable-feature=otlp-deltatocumulative.
  6. Histograms: OTel explicit-bucket histograms → classic _bucket; exponential histograms → native histogram (native histograms have been stable since v3.8.0).

When: how to choose among the four integration paths

PathBest forCaveats
A. Client library + Prometheus scraping (myapp's current setup)Pure Prometheus stack; requires up and scrape health semanticsone library per language
B. OTel SDK → Collector → Prometheus/Mimir OTLPNew services standardize on OTel and also need tracesNo up; rely on target_info and Collector self-monitoring to determine whether it is “alive”; when pushing to an HA pair, send to every replica
C. Collector's prometheus receiver scraping → remote write / OTLPUse the Collector to unify and replace the agent; cloud vendor distributions (such as ADOT)The receiver is compatible with most scrape_config, but not 100%; horizontal scaling requires the Target Allocator
D. Prometheus exporter in the OTel SDK (exposes /metrics)Want to use the OTel API but keep the pull modelResource attributes appear as target_info in /metrics
Common misconceptions① “OTel will replace Prometheus”: OTel does not store, query, or alert; it and Prometheus are upstream and downstream of each other. ② “Promoting all resource attributes to labels is the most convenient”—k8s.pod.uid,process.pid such attributes cause cardinality explosions (Lesson 7); only promote the ones needed for queries. ③ “Pushing OTLP to the Prometheus Service gives high availability”: the Service sends each request to only one replica, so the two replicas' data becomes inconsistent; either send to each replica separately, or send to a backend like Mimir that already replicates internally.

Architecture diagram: four paths

A · myapp prometheus_client/metrics B · Service + OTel SDKOTLP push C · any /metrics targetscraped by the Collector D · OTel SDKPrometheus exporter OTel Collectorreceivers: otlp · prometheusprocessors: batch · k8sattributesdeltatocumulative (optional)exporters: otlphttp ·prometheusremotewrite Prometheusscrape (A, D)/api/v1/otlp/v1/metrics (B)/api/v1/write (C's remote write) Mimir/otlp/v1/metrics · /api/v1/pushX-Scope-OrgID Prometheus pull scrape
Figure 6-1: the Collector is the crossing point. It can receive pushes (OTLP) and scrape (prometheus receiver), then push on to Prometheus or Mimir

Data translation: one OTLP data point entering Prometheus

OTLP Resource: service.namespace=shop service.name=myapp-otel service.instance.id=pod-1 k8s.namespace.name=myappMetric: http.server.request.duration unit=s · Histogram · attr http.route=/ Metric series (UnderscoreEscapingWithSuffixes + promote k8s.namespace.name)http_server_request_duration_seconds_bucket{job="shop/myapp-otel", instance="pod-1", http_route="/", k8s_namespace_name="myapp", le="0.5"} target_info (one per resource)target_info{job="shop/myapp-otel", instance="pod-1", k8s_namespace_name="myapp", …other resource attributes} 1
Figure 6-2: job/instance come from service.* attributes; the other resource attributes go only to target_info by default, and can be used with info() (experimental function) or joined in a query

Interactive: OTel metric name and label translator

Enter the OTel metric name, unit, type, and resource attributes, choose a translation_strategy and the attributes to promote, and view the resulting series in Prometheus (the rules follow the OpenTelemetry guide on prometheus.io; unit mapping covers only common units).



Resource attributes (checked = promote_resource_attributes)

Core configuration and commands

Configuration / commandPurposeKey points
--web.enable-otlp-receiverEnable the OTLP receiver in Prometheusdisabled by default, no authentication
otlp.promote_resource_attributesresource attributes → labelsno attributes are promoted by default
otlp.translation_strategyName translation strategydefault UnderscoreEscapingWithSuffixes
otlp.keep_identifying_resource_attributeskeep the original service.* attributes on target_infodefault false
storage.tsdb.out_of_order_time_windowAccept out-of-order samplesofficial recommendation 30m
kps: prometheusSpec.enableOTLPReceiver / otlp / tsdb.outOfOrderTimeWindowthe corresponding field in the OperatorcamelCase: promoteResourceAttributes,translationStrategy
telemetrygen metricsGenerate test OTLP metrics--otlp-insecure --otlp-attributes

1. Prometheus configuration (standalone deployment)

storage:
  tsdb:
    out_of_order_time_window: 30m
otlp:
  promote_resource_attributes:
    - service.namespace
    - service.name
    - k8s.namespace.name
    - k8s.deployment.name
    - k8s.cluster.name
  translation_strategy: UnderscoreEscapingWithSuffixes
  keep_identifying_resource_attributes: false
prometheus --config.file=prometheus.yml --web.enable-otlp-receiver

2. kps values

prometheus:
  prometheusSpec:
    enableOTLPReceiver: true
    otlp:
      promoteResourceAttributes: [service.namespace, service.name, k8s.namespace.name]
      translationStrategy: UnderscoreEscapingWithSuffixes
    tsdb:
      outOfOrderTimeWindow: 30m

3. Collector: OTLP in, one output per Prometheus replica

receivers:
  otlp:
    protocols:
      grpc: {endpoint: 0.0.0.0:4317}
      http: {endpoint: 0.0.0.0:4318}
processors:
  batch: {}
exporters:
  otlphttp/prom0:
    endpoint: http://prometheus-kps-kube-prometheus-stack-prometheus-0.prometheus-operated.monitoring.svc:9090/api/v1/otlp
    tls: {insecure: true}
  otlphttp/prom1:
    endpoint: http://prometheus-kps-kube-prometheus-stack-prometheus-1.prometheus-operated.monitoring.svc:9090/api/v1/otlp
    tls: {insecure: true}
  otlphttp/mimir:                         # or send only to Mimir (which replicates on its own)
    endpoint: http://mimir.mimir.svc:9009/otlp
    headers: {X-Scope-OrgID: cluster-lab}
    tls: {insecure: true}
  debug: {}
service:
  pipelines:
    metrics:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlphttp/prom0, otlphttp/prom1, otlphttp/mimir]

otlphttp 's endpoint is the base URL; the exporter appends the path automatically /v1/metrics: for Prometheus it is /api/v1/otlp/v1/metrics, for Mimir it is /otlp/v1/metrics.

4. Query OTel data

sum by (job) (rate(gen_total[5m]))
target_info{job="shop/myapp-otel"}
# join resource attributes via target_info (traditional join syntax)
rate(gen_total[5m]) * on (job, instance) group_left (k8s_pod_name) target_info
# info() is an experimental function and requires --enable-feature=promql-experimental-functions
# In Prometheus 3, query UTF-8 names that keep dots:
{"http.server.request.duration_seconds_count"}

Lab: Collector + telemetrygen → OTLP receiver on the kps Prometheus

Goal and environment: kind lab. The Collector and Prometheus parts of this lab were tested locally with Docker using Prometheus v3.16.0 + Collector 0.165.0 + telemetrygen v0.165.0 (see the output in step 4); the kind steps are written with the same configuration.
Enable the OTLP receiver in kps: merge the second part of the “Commands” page into ~/promlab/k8s/kps-part6.yaml the prometheusSpec, then:
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml -f ~/promlab/k8s/kps-part6.yaml --wait
kubectl -n monitoring get sts prometheus-kps-kube-prometheus-stack-prometheus -o yaml | grep -E 'enable-otlp-receiver|out_of_order' 
Deploy the Collector
# Save the third part of the “Commands” page as ~/promlab/part6/otelcol.yaml (if Mimir is not deployed, remove otlphttp/mimir)
kubectl -n monitoring create configmap otelcol-config --from-file=config.yaml=$HOME/promlab/part6/otelcol.yaml
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata: {name: otelcol, namespace: monitoring, labels: {app: otelcol}}
spec:
  replicas: 1
  selector: {matchLabels: {app: otelcol}}
  template:
    metadata: {labels: {app: otelcol}}
    spec:
      containers:
      - name: otelcol
        image: otel/opentelemetry-collector:0.165.0
        args: ["--config=/conf/config.yaml"]
        ports: [{containerPort: 4317, name: otlp-grpc}, {containerPort: 4318, name: otlp-http}]
        volumeMounts: [{name: conf, mountPath: /conf}]
        resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}}
      volumes: [{name: conf, configMap: {name: otelcol-config}}]
---
apiVersion: v1
kind: Service
metadata: {name: otelcol, namespace: monitoring}
spec:
  selector: {app: otelcol}
  ports: [{name: otlp-grpc, port: 4317}, {name: otlp-http, port: 4318}]
EOF
kubectl -n monitoring rollout status deploy/otelcol
kubectl -n monitoring logs deploy/otelcol | grep -i 'Everything is ready'
… info service@v0.165.0/service.go:256 Everything is ready. Begin running and processing data. …
Send histograms with resource attributes using telemetrygen
kubectl -n monitoring run telemetrygen --rm -it --restart=Never \
  --image=ghcr.io/open-telemetry/opentelemetry-collector-contrib/telemetrygen:v0.165.0 -- \
  metrics --otlp-endpoint otelcol.monitoring.svc:4317 --otlp-insecure \
  --duration 2m --rate 1 --metric-type Histogram \
  --otlp-attributes 'service.name="myapp-otel"' --otlp-attributes 'service.namespace="shop"' \
  --otlp-attributes 'service.instance.id="pod-1"' --otlp-attributes 'k8s.namespace.name="myapp"'
Verify in Prometheus
curl -s localhost:9090/api/v1/label/__name__/values | jq -r '.data[] | select(test("^gen|target_info"))'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=gen_count' | jq -c '.data.result[].metric'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=target_info' | jq -c '.data.result[].metric'
gen_bucket
gen_count
gen_sum
target_info
{"__name__":"gen_count","instance":"pod-1","job":"shop/myapp-otel","k8s_namespace_name":"myapp","service_name":"myapp-otel","service_namespace":"shop"}
{"__name__":"target_info","instance":"pod-1","job":"shop/myapp-otel","k8s_namespace_name":"myapp"}

Observe: job = service.namespace/service.name,instance = service.instance.id; the promoted attributes (dots converted to underscores) appear on every metric. The telemetrygen metric name is gen, with no unit, so there is no _seconds suffix; when using the Sum type it yields gen_total. On kind, both replicas should have data (count by (prometheus_replica) without deduplication in Thanos Query, 2 copies are visible).

Cleanup
kubectl -n monitoring delete deploy/otelcol svc/otelcol configmap/otelcol-config
# When no longer needed, set enableOTLPReceiver back to false and run helm upgrade

Case 1: a new Java service standardizes on OTel

Problem: The new service uses the OTel Java agent for automatic instrumentation (HTTP server/client, JVM), and the platform already has Prometheus + Mimir.

Approach: One Collector per node (DaemonSet,k8sattributes processor adds Pod/namespace attributes) → OTLP sent to Mimir's /otlp/v1/metrics (per tenant). Dashboards use the metric names after semantic-convention translation http_server_request_duration_seconds_bucket; promote k8s.namespace.name,k8s.deployment.name,service.name, but do not promote Pod UID.

Limitations: There are no up metrics. For “service is down” alerts, use absent_over_time(target_info{job="shop/checkout"}[5m]) or the Collector's own metrics.

Case 2: replacing the Prometheus Agent with the Collector

A team already sends data to AMP using ADOT (Lesson 4) and wants to use the same collector on Azure. Approach: the Collector's prometheus receiver reuses the existing scrape_config and exports to the Azure Monitor workspace from Lesson 3 or to Mimir. Limitations: not all Prometheus scraping features are equivalent in the receiver; ServiceMonitor support depends on the OTel Operator's Target Allocator; verify each item.

Case 3: cloud SDKs with delta temporality

Some SDKs or cloud services export delta counters by default; writing them directly to Prometheus gets them rejected or produces wrong semantics. Approach: add a deltatocumulative processor to the Collector (contrib distribution), or enable the experimental feature in Prometheus otlp-deltatocumulative (do not do both; the official docs note that delta support is still evolving).

Common errors and fixes

Exporting failed ... error exporting items, request to http://…:9090/api/v1/otlp/v1/metrics responded with HTTP Status Code 404

Cause: Prometheus does not have OTLP receiving enabled (--web.enable-otlp-receiver / kps enableOTLPReceiver), or the endpoint path was written as /api/v1/otlp/v1/metrics/v1/metrics (otlphttp appends the path automatically).

kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.enableOTLPReceiver}{"\n"}'
out of order sample / too old sample (OTLP batch write rejected)

Cause: Multiple Collector replicas or retries cause out-of-order samples for the same series.

Fix:out_of_order_time_window: 30m (kps: tsdb.outOfOrderTimeWindow); ensure service.instance.id each instance is unique, so that two instances never write the same series.

Dashboard query cannot find http_server_duration_milliseconds (the metric name changed after upgrading the SDK)

Cause: OTel HTTP semantic conventions moved from the old http.server.duration (ms) to http.server.request.duration (s); or translation_strategy changed the suffix.

curl -s localhost:9090/api/v1/label/__name__/values | jq -r '.data[]' | grep -i http_server
Active series spike after enabling OTLP

Cause: Promoted high-cardinality resource attributes (k8s.pod.uid,process.pid,host.id), or promote_all_resource_attributes a similar setting.

count by (__name__) ({job="shop/myapp-otel"})

Fix: Promote only the attributes queries need, and link the others through target_info a join.

Command-line exercise

1. Write a Prometheus configuration snippet: enable an out-of-order window of 30 minutes and promote service.name and k8s.cluster.name, and use a translation strategy that keeps UTF-8 and adds suffixes.

Reference answer
storage:
  tsdb:
    out_of_order_time_window: 30m
otlp:
  promote_resource_attributes: [service.name, k8s.cluster.name]
  translation_strategy: NoUTF8EscapingWithSuffixes

2. Write a PromQL query: for rate(gen_total[5m]) , from target_info, add the k8s_pod_name label.

Reference answer
rate(gen_total[5m]) * on (job, instance) group_left (k8s_pod_name) target_info

Scenario analysis: After the team switched all services from prometheus_client to the OTel SDK + OTLP push, the “service down” alert stopped working, and the same Grafana panel occasionally jumped in value. Analyze the causes of these two problems.

Reference answer

① The original down alert was based on the up == 0; in push mode there is no scraping, so the up does not exist. A down service only means “no more data”, so the alert must be changed to absent_over_time(target_info{job="…"}[5m]) an alert based on Collector or Kubernetes readiness state. ② Jump: OTLP is sent to the Prometheus Service, which reaches only one replica of the HA pair; the two replicas hold different data, and Grafana reads different replicas when the Service load-balances. The Collector should send to each replica separately or send to Mimir, and use Thanos Query or Mimir as the query entry point.

Verified instructional videos

▶
Prometheus and OpenTelemetry: Better Together - Adriana Villela & Reese Lee — CNCF [Cloud Native Computing Foundation]
English · How the two projects work together
▶
Why Prometheus 3.0 Will Change How You Do Observability: OTel Support, Remote Write 2.0, and More — Grafana
English · OTLP support in Prometheus 3

Official docs

Video storyboard script

This courseware cannot generate video or MP3 directly, so the storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: A dividing line between two logos: on the left “Generate and transport”, on the right “Store, query, alert”.
Narration: OpenTelemetry and Prometheus are not competitors; they are upstream and downstream.
Shot 2 · 0:20–1:00
Visual: An OTLP data point enters Prometheus: dots become underscores, the _seconds_bucket suffix is added, service.name becomes job, and other resource attributes fall into target_info.
Narration: At the boundary, both names and labels get converted.
Shot 3 · 1:00–1:30
Visual: After k8s.pod.uid is checked, the series count bar chart spikes.
Narration: Only promote the resource attributes you actually query.
Shot 4 · 1:30–1:50
Visual: The Collector splits in two and sends to each of the two Prometheus replicas separately.
Narration: In push mode, high availability depends on replication at the sender or in the backend.
or score ≥ 70% on the quiz

Module 7 · Grafana at scale: organizations, folders, permissions and teams

42:00 – 50:00 · From “one admin account + 50 dashboards” to “30 teams + 2,000 dashboards + managed as code”
8 minutesGrafana 13.3.1 · Terraform provider v4.55.0 · Operator v5.26.0★★★★ Platform governance
Learning objectives
  • Distinguish organizations (Organization, hard isolation), folders (permission boundary, nestable), teams (permission subjects), basic roles (Viewer / Editor / Admin / No basic role) and Grafana server administrators.
  • Know which features are OSS and which require Enterprise / Cloud: custom RBAC roles, data source permissions, Team Sync.
  • Use the HTTP API to create teams and nested folders and grant permissions; use service accounts instead of personal API keys.
  • Choose a manage-as-code approach: Git Sync (Grafana 13 GA), Terraform provider, Grafana Operator, file provisioning.
Prerequisites: Grafana data sources and provisioning (Lessons 1 and 2), Grafana bundled with kps (Lesson 5). Importance:★★★★

What: Grafana's permission model

LevelWhat it isIsolationAvailability
Grafana server adminManages the whole instance: organizations, users, settingsAcross all organizationsOSS / Enterprise (Grafana Cloud does not have this role)
OrganizationAn independent set of dashboards, data sources, alerts and teamsHard isolation: organizations cannot see each other; a user can belong to several organizations, with a different role in eachOSS (in Cloud, one stack is one organization)
Basic roleRoles within an organization: Admin, Editor, Viewer, No basic role (no permissions by default; must be granted separately)Organization-level default permissionsOSS
FolderContainer for dashboards, alert rules and library panels; supports subfolders; the main permission boundaryPermissions are inherited by subfolders and contentOSS
TeamUser group; members / Team AdminGrant targetOSS; syncing with IdP groups (Team Sync) requires Enterprise/Cloud
RBACFine-grained permissions and custom roles, data source query permissionsPrecise down to actions and resourcesEnterprise / Cloud

Folder and dashboard permissions have three levels: View / Edit / Admin (Edit cannot change permissions, Admin can). Explicit grants on a folder or dashboard will override the default permissions granted by organization roles. New folders default to “Editor role = Edit, Viewer role = View”, and anyone who creates a folder or dashboard at the top level automatically gets Admin.

Why: why scaling requires design

  • Without structure, every Editor can change every dashboard, and accidental deletions or edits cannot be traced.
  • Alert rules are also stored in folders: folder permissions also decide who can change alerts (Lesson 2, Grafana Alerting).
  • Staff turnover: grant by team, sync teams with IdP groups, and avoid granting user by user.

How: recommended structure

  • Use multiple organizations as little as possible: organizations cannot share dashboards and data sources, and viewing across organizations requires switching; use them only when customer or regulatory requirements demand hard isolation. Most companies = 1 organization + folders + teams.
  • Create folders by “team / service”: Platform/,Teams/payments/,Teams/myapp/,SLO/; at the top level, remove the default “Viewer role = View” grant and switch to team-based grants.
  • Set the default organization role to Viewer (or No basic role); grant edit rights through teams + folders.
  • For machine access, use service accounts (with roles, multiple tokens allowed, tokens can expire), not personal accounts.
  • Managed as code: Git Sync (Grafana 13 GA, supports GitHub/GitLab/Bitbucket/any git, can save, commit and open PRs from the UI),Terraform (grafana/grafana Terraform provider),Grafana Operator Grafana Operator (GrafanaDashboard / GrafanaFolder CR), file provisioning (kps dashboard sidecar).

When: which manage-as-code approach to choose

ApproachBest forCaveats
File provisioning / kps sidecarPlatform dashboards shipped with HelmChanges made in the UI cannot be saved back to the file
Git SyncTeams edit in the UI while requiring Git reviewWhen upgrading Grafana 13.0.0 from 12.x, early Git Sync users face a risk of data loss; the release notes require backing up the database first and then upgrading directly to 13.0.1+
Terraform provider“Configuration objects” such as teams, folders, permissions, data sources and alert contact pointsManaging large numbers of dashboard JSON files with Terraform is verbose
Grafana OperatorKubernetes-native, GitOps (Argo CD/Flux)The sync status between CRs and the Grafana instance needs monitoring
Common misconceptions① “Giving each team its own organization means isolation”: overusing organizations means shared dashboards, alert contact points and data sources must each be duplicated N times. ② “If Viewers cannot see the data source, it is safe”: in OSS, anyone who can view a dashboard can query the organization's data sources through Explore or panels; restricting queries per data source requires Enterprise/Cloud data source permissions, or placing sensitive data sources in a separate organization, or isolating them in the backend (Mimir tenant header). ③ “Upgrading just means swapping the image”: Grafana 13 has breaking changes: removal of grafana-cli/grafana-server binaries,/api paths marked deprecated (recommended /apis), Image Renderer plugin is no longer supported, RBAC validation is stricter; read the release notes before upgrading.

Structure diagram: folders, teams and grants within one organization

Organization Main Org (default basic role: Viewer) Team sreIdP group sre (Team Sync*) Team myapp-teamalice (Team Admin) · bob Service account ci-dashboardsrole: Editor · token 90 days 📁 Platformsre: Admin · Viewer role: Viewkps default dashboards 📁 TeamsRemove default Viewer role grant 📁 Teams / myapp (subfolder)myapp-team: Edit · sre: Admin (inherited)Dashboards + Grafana alert rules Data sourceMimir (cluster-lab)Mimir global SRE (a|b)Query permission restrictions require Enterprise/Cloud* As codeGit Sync · TerraformGrafana Operatorprovisioning files * Features marked with an asterisk require Grafana Enterprise or Grafana Cloud
Figure 7-1: 1 organization + nested folders + team grants, the recommended structure for most companies

Decision diagram: can a user edit dashboards under Teams/myapp

Organization Admin?Yes → Admin Collect applicable grantsUser · team membership · basic role Inherit along the folder chainTeams → Teams/myapp → dashboard Take the highest levelNone / View / Edit / Admin Grants can only be added, not “subtracted” in a subfolder from permissions given by the parent folder
Figure 7-2: effective permission = the highest of all applicable grants (simplified model, excludes custom RBAC roles)

Interactive: effective permission calculator

Choose a user's basic role and team, adjust the grants on a folder, and see their effective permission on Teams/myapp dashboards in it, along with the grant that determines the result.


Team membership

📁 Teams grants

📁 Teams/myapp grants

Effective permission: —

Core API and tools

API / toolPurposeKey points
POST /api/serviceaccounts · POST /api/serviceaccounts/:id/tokensService accounts and tokensReplaces old API keys; token settings secondsToLive
POST /api/teams · POST /api/teams/:id/membersCreate teams and add membersMembers must be existing user IDs
POST /api/foldersCreate folders (parentUid to create subfolders)Specify a stable uid
POST /api/folders/:uid/permissionsFully replace folder permissionspermission: 1=View, 2=Edit, 4=Admin; grants not listed are deleted
grafana cliPlugins, admin password reset, etc.Starting with Grafana 13, use grafana cli / grafana server, the old grafana-cli,grafana-server have been removed
Terraform grafana/grafanagrafana_team,grafana_folder,grafana_folder_permission,grafana_dashboardprovider v4.55.0 (2026-11-13)

In Grafana 13, /api is marked as deprecated, recommending the new /apis (Kubernetes-style resource API); the following /api calls still work in 13.x, but new automation should evaluate /apis or Terraform/Operator.

1. Preparation: port forwarding and admin credentials

kubectl -n monitoring port-forward svc/kps-grafana 3000:80 &
GPASS=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
G="http://admin:${GPASS}@localhost:3000"
curl -s "$G/api/health" | jq .

2. Service account (use it for all later automation)

SA_ID=$(curl -s -X POST -H 'Content-Type: application/json' "$G/api/serviceaccounts" \
  -d '{"name":"ci-dashboards","role":"Admin"}' | jq .id)
TOKEN=$(curl -s -X POST -H 'Content-Type: application/json' "$G/api/serviceaccounts/$SA_ID/tokens" \
  -d '{"name":"lab","secondsToLive":86400}' | jq -r .key)
H="Authorization: Bearer $TOKEN"
curl -s -H "$H" localhost:3000/api/org | jq .

3. Teams, nested folders and permissions

# Creating users is a server admin operation; here we use admin's Basic Auth ($G), and the rest use the service account token
curl -s -X POST "$G/api/admin/users" -H 'Content-Type: application/json' \
  -d '{"name":"alice","login":"alice","password":"Lab-Passw0rd!","email":"alice@example.com"}'
ALICE=$(curl -s "$G/api/users/lookup?loginOrEmail=alice" | jq .id)

TEAM=$(curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/teams \
  -d '{"name":"myapp-team"}' | jq .teamId)
curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/teams/$TEAM/members -d "{\"userId\":$ALICE}"

curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/folders \
  -d '{"uid":"teams","title":"Teams"}' | jq -r .uid
curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/folders \
  -d '{"uid":"teams-myapp","title":"myapp","parentUid":"teams"}' | jq -r '.uid, .parentUid'

# Teams: keep only Editor role Edit (remove Viewer role View)
curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/folders/teams/permissions \
  -d '{"items":[{"role":"Editor","permission":2}]}'
# Teams/myapp: myapp-team can edit
curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/folders/teams-myapp/permissions \
  -d "{\"items\":[{\"teamId\":$TEAM,\"permission\":2}]}"
curl -s -H "$H" localhost:3000/api/folders/teams-myapp/permissions | jq -c '.[] | {team, role, permissionName, inherited}'
{"team":"","role":"Editor","permissionName":"Edit","inherited":true}
{"team":"myapp-team","role":"","permissionName":"Edit","inherited":false}

4. The same structure with Terraform

terraform {
  required_providers {
    grafana = { source = "grafana/grafana", version = "~> 4.55" }
  }
}
provider "grafana" {
  url  = "http://localhost:3000"
  auth = var.grafana_sa_token
}
resource "grafana_team" "myapp" { name = "myapp-team" }
resource "grafana_folder" "teams" {
  uid   = "teams"
  title = "Teams"
}
resource "grafana_folder" "myapp" {
  uid               = "teams-myapp"
  title             = "myapp"
  parent_folder_uid = grafana_folder.teams.uid
}
resource "grafana_folder_permission" "myapp" {
  folder_uid = grafana_folder.myapp.uid
  permissions {
    team_id    = grafana_team.myapp.id
    permission = "Edit"
  }
}

Refer to the v4.55 docs on registry.terraform.io for resource and parameter names (the Terraform lesson goes into more depth).

Lab: create teams, nested folders and permissions in the Grafana bundled with kps, and verify

Goal and environment: kind lab, the Grafana bundled with kps (Secret kps-grafana admin password). About 10 minutes. For the Grafana version bundled with kps 93.3.0, check kubectl -n monitoring get deploy kps-grafana -o jsonpath='{..image}' , which may not be 13.3.1.
Run sections 1–3 of the “Commands” tab, creating the service account, user alice, team myapp-team, folder Teams, and subfolder Teams/myapp and its permissions.
Import an SLO dashboard into Teams/myapp
cat > /tmp/dash.json <<'EOF'
{"dashboard":{"uid":"myapp-slo","title":"myapp SLO","panels":[
 {"type":"timeseries","title":"5m error rate","gridPos":{"h":8,"w":12,"x":0,"y":0},
  "targets":[{"expr":"myapp:sli_errors:ratio_rate5m","refId":"A"}]},
 {"type":"stat","title":"1h burn rate","gridPos":{"h":8,"w":12,"x":12,"y":0},
  "targets":[{"expr":"myapp:sli_errors:ratio_rate1h / 0.001","refId":"A"}]}]},
 "folderUid":"teams-myapp","overwrite":true}
EOF
curl -s -X POST -H "$H" -H 'Content-Type: application/json' localhost:3000/api/dashboards/db -d @/tmp/dash.json | jq '{status, url}'
Verify as alice
A="http://alice:Lab-Passw0rd!@localhost:3000"
curl -s "$A/api/search?folderUIDs=teams-myapp" | jq -r '.[].title'          # can see myapp SLO
curl -s "$A/api/dashboards/uid/myapp-slo" | jq '.meta | {canEdit, canAdmin, folderTitle}'
curl -s "$A/api/search?query=Kubernetes" | jq length                          # kps dashboards in Platform (visible to Viewer by default)
myapp SLO
{ "canEdit": true, "canAdmin": false, "folderTitle": "myapp" }
27
Verify again after removing alice from the team
curl -s -X DELETE -H "$H" localhost:3000/api/teams/$TEAM/members/$ALICE
curl -s -o /dev/null -w '%{http_code}\n' "$A/api/dashboards/uid/myapp-slo"
403

The Teams folder has already removed “Viewer role = View”; alice is only a Viewer and is no longer in the team, so she has no access. Compare the results with the calculator on the “Animation” tab.

Cleanup: curl -X DELETE -H "$H" localhost:3000/api/folders/teams (this deletes the subfolders and the dashboards in them); delete the user and the service account; stop the port-forward.

Case 1: merging 12 organizations into 1

Problem: Early on each team had its own organization, so data sources, alert contact points and shared dashboards were duplicated 12 times, and SRE troubleshooting meant switching organizations back and forth.

Approach: Merged into 1 organization, with one folder per team plus team grants; teams synced with Entra ID groups (Team Sync, Enterprise/Cloud); sensitive financial data sources placed in a separate organization (how data source isolation is achieved under OSS).

Case 2: dashboards as code

Platform dashboards ship with Helm through the kps sidecar (ConfigMaps carrying the grafana_dashboard label); team dashboards sync to each team's repository via Git Sync, with changes made in the UI submitted as PRs for review; teams, folders, permissions, data sources and contact points are managed centrally with Terraform. Limitation: each object can have only one “source of truth”, otherwise Terraform and the UI overwrite each other.

Case 3: highly available Grafana

3 Grafana replicas + external PostgreSQL (no longer SQLite) + sessions stored in the database; multi-instance Grafana Alerting requires alerting HA configuration ([unified_alerting] in the HA peer or Redis mode; verify parameters against the official “Configure high availability” docs), otherwise every replica evaluates the rules and sends duplicate notifications.

Common errors and fixes

{"message":"Access denied to this dashboard","status":"error"} / 403

Cause: The user is not in any authorized team, and the folder has removed the default basic-role grant.

curl -s -H "$H" localhost:3000/api/folders/teams-myapp/permissions | jq -c '.[] | {team,userLogin,role,permissionName,inherited}'
curl -s -H "$H" "localhost:3000/api/teams/search?query=myapp" | jq '.teams[] | {name, memberCount}'
After calling POST /api/folders/:uid/permissions, all the original grants disappear

Cause: This endpoint is a full replacement, so any grants not listed are deleted.

Fix: GET the existing grants first, merge them, then POST; or switch to declaring all grants with Terraform.

{"message":"Permissions needed: users:create"} / service account cannot create users

Cause: User management belongs to the server admin scope; organization-level service accounts do not have this permission (in the RBAC version, it is controlled by specific actions).

Fix: Create users automatically through the IdP (OIDC/SAML), or use server admin credentials to call /api/admin/users.

After upgrading to Grafana 13 the container fails to start: exec: "grafana-server": executable file not found

Cause: Grafana 13 removed grafana-server and grafana-cli.

Fix: Change the custom start command to grafana server; change the script to grafana cli.

Command-line exercise

1. Write a curl command: in the parent folder teams create a folder with uid teams-payments, titled payments as a subfolder (the Bearer token is in $TOKEN).

Reference answer
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  localhost:3000/api/folders -d '{"uid":"teams-payments","title":"payments","parentUid":"teams"}'

2. Write the request body: set the folder permissions to “Team 7 = Admin, Viewer role = View”.

Reference answer
{"items":[{"teamId":7,"permission":4},{"role":"Viewer","permission":1}]}

Scenario analysis: The finance team requires that “only the finance team can see the transaction volume metrics.” You use Grafana OSS + Mimir. Is it enough to put the finance dashboards in a restricted folder? Give a complete plan.

Reference answer

Not enough: a folder only restricts dashboards; in OSS, anyone in the organization who can use Explore can query the same data source directly. Plan: ① backend isolation — write transaction metrics to a separate Mimir tenant team-finance; ② on the Grafana side — create a data source for that tenant and put it in a separate organization (OSS), or use Enterprise/Cloud data source permissions granting access only to the finance team; ③ the gateway ensures the tenant header cannot be forged; ④ alert rules are likewise placed in the restricted folder/organization.

Verified instructional videos

▶
Grafana Dashboard Provisioning, Teams & Permissions, and Running Grafana in a HA Environment — Grafana
English · Teams, permissions, provisioning and HA (recorded on an earlier version; the UI follows 13.x)
▶
Grafana 13 Deep Dive: Suggested Dashboards, Dynamic Dashboards, SQL Expressions, and More! — Grafana
English · What's new in Grafana 13

Official docs

Video storyboard script

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

Shot 1 · 0:00–0:20
Visual: A messy dashboard list, with every title reading “Copy of …”.
Narration: The first step in scaling Grafana is structure.
Shot 2 · 0:20–1:00
Visual: A folder tree inside one organization, with team badges attached to folders and permissions flowing downward.
Narration: Folders are the permission boundary, teams are the grant targets, and organizations are used only when hard isolation is needed.
Shot 3 · 1:00–1:30
Visual: Calculator: Viewer + myapp-team → Edit; removed from team → no access.
Narration: Effective permission is the highest of all applicable grants.
Shot 4 · 1:30–1:50
Visual: A two-way arrow between the Git repository and the Grafana UI, with PR review.
Narration: Use Git Sync, Terraform, or the Operator to turn dashboards and permissions into code.
or score ≥ 70% on the quiz

Module 8 · Comprehensive Architecture Review

50:00 – 60:00 · Turn the first 7 modules into one review checklist, a set of capacity formulas and one troubleshooting tree
10 minCapacity formula from the prometheus.io Storage docs★★★★★ Frequently asked in interviews and design reviews
Learning objectives
  • Review a monitoring architecture across 8 dimensions: collection, HA, storage, multi-tenancy, alert quality, OTel, visualization governance and self-monitoring.
  • Estimate disk with the official formula: retention seconds × samples ingested per second × bytes per sample (about 1–2), and estimate the ingestion rate from active series.
  • Give reference architectures and their rationale for small, medium and large scales.
  • Use the interactive troubleshooting tree to locate cross-component problems such as missing data, duplicate alerts, slow queries and rejected writes.
Prerequisites: Modules 1–7. Importance:★★★★★

What: review checklist (8 dimensions)

DimensionQuestion to askAcceptable answer (example)
1. CollectionHow is each cluster scraped? Push or pull?kps (Operator + ServiceMonitor) or Agent; external_labels.cluster unique
2. High availabilityIf any Pod, node or availability zone fails, do scraping and alerting still work?Prometheus ×2, Alertmanager ×3 (anti-affinity + PDB), alerts sent to all Alertmanagers
3. Storage and retentionHow long is data kept? Who handles compaction? Object storage?1–2 days local + 13 months in Mimir/Thanos; compactor is monitored
4. Multi-cluster / multi-tenancyWho can see what? What is the blast radius?Tenants per team/cluster, limits, tenant header injected by the gateway
5. Alert qualityAre alerts based on SLOs? Are they tested?Multi-window multi-burn-rate,promtool test rules, runbook link
6. OTel and standardizationWhich instrumentation do new services use? Naming conventions?A standard choosing either the OTel SDK or client libraries; a list of promoted resource attributes
7. Visualization governanceFolders / teams / permissions / as code?1 org + folders + teams, Git Sync/Terraform
8. Monitoring the monitoringIf the monitoring system goes down, who knows?Watchdog heartbeat to an external service; alerts for remote write latency, dropped samples and compactor downtime

Why: why quantify

“Is it enough?” needs numbers: active series determine memory, sample rate determines write load and disk, query range determines the size of the query layer. The official disk formula:

Disk needed ≈ retention time (seconds) × samples ingested per second × bytes per sample (about 1–2 bytes on average)
Samples ingested per second ≈ active series ÷ scrape interval (seconds)

Example: 800k active series, 30 s scrape → about 26.7k samples/s; 15-day retention → 1,296,000 s × 26,667 × 2 bytes ≈ 69 GB (plus room for WAL and compaction overhead).

How: reference architectures for three scales

ScaleCharacteristicsReference architecture
Small1–3 clusters, < 1M series, retention ≤ 30 days, one teamPer cluster: kps (Prometheus ×2, Alertmanager ×3) + Grafana; add Thanos Query when a global view is needed; or use a managed service directly (Lessons 3/4)
Medium5–20 clusters, millions of series, 1-year retention, multiple teamsPer-cluster Prometheus (short retention) remote_write → Mimir (or Thanos sidecar + object storage); central Ruler; Grafana folders + teams
LargeTens to hundreds of clusters, hundreds of millions of series, a platform team serving internal customersAgent / Collector scraping → Mimir microservices (per-team tenants, limits, gateway authentication) → query cache; SLO platform (Sloth/Pyrra); Grafana as code + RBAC (Enterprise/Cloud)

When: when to re-review

  • Active series or cluster count doubles; new compliance requirements (retention, isolation); on-call alert volume keeps rising; the monitoring system itself has had an outage.
Common misconceptions① “Build the most complete architecture first and you’ll never have to change it”: Mimir microservices + Kafka are a burden for a team with 3 clusters, and the operating cost may outweigh the benefit. ② “One capacity estimate is enough”: cardinality grows with each release (Lesson 7) and must be monitored continuously prometheus_tsdb_head_series and per-tenant active series. ③ “The monitoring system does not need an SLO”: monitoring is itself a service, and query availability and alert delivery latency should both have targets.

Reference architecture (medium scale): a combination of all the components in this lesson

Cluster lab (full Prometheus) Prom ×2 AM ×3 myapp · SLO rules (local fallback)OTel Collector Cluster lab-b (Agent) PrometheusAgentcluster=lab-b · tenant cluster-lab-b Auth gatewayInjects tenant header Mimirdistributor · ingester ×3store-gateway · compactorquery-frontend · querierruler (SLO long windows)alertmanager (optional)overrides: per-tenant limits Object storage13 months · lifecycle policy Grafana ×3PostgreSQLFolders · teamsGit Sync / Terraform External heartbeatWatchdog → dead man’s switch
Figure 8-1 Medium-scale reference architecture: the full local Prometheus keeps alerting working, remote Mimir provides long-term storage and global queries, the gateway keeps tenants secure, and the external heartbeat monitors “the monitoring itself”

Failure domain matrix

FailureScrapingLocal alertingGlobal queriesData loss One Prometheus replica✓ other replica✓✓ (dedup / HA tracker)None One Alertmanager✓✓ the other 2 take over✓None (silences already gossiped) Mimir unavailable for 1 hour✓✓ (full Prometheus)✗None (backfilled from WAL) Mimir unavailable for 6 hours✓✓ / Agent clusters ✗✗Remote gap (beyond WAL)
Figure 8-2 Agent-mode clusters lose alerting when the central system is unavailable. This is a trade-off that must be accepted or compensated for when choosing the architecture.

Interactive: architecture scorecard and capacity estimate

Enter your environment parameters to get a capacity estimate (official disk formula), a recommended topology and review risk notes. Estimates are for order-of-magnitude judgment only.

Number of clusters:8

Active series per cluster (10k):80

Scrape interval (seconds):30

Long-term retention (days):395

Number of teams:6

Queries and commands commonly used in reviews

Query / commandQuestion answered
prometheus_tsdb_head_seriesCurrent active series
rate(prometheus_tsdb_head_samples_appended_total[5m])Samples ingested per second
prometheus_tsdb_storage_blocks_bytesLocal block usage
sum by (user) (cortex_ingester_active_series)Mimir series per tenant
alertmanager_cluster_members,alertmanager_notifications_failed_totalAlerting pipeline health
promtool tsdb analyze /prometheusMetrics and labels with the highest cardinality (covered in depth in Lesson 7)
prometheus_tsdb_head_series
rate(prometheus_tsdb_head_samples_appended_total[5m])
# Estimate 15-day disk at the current rate (bytes, 2 bytes/sample):
rate(prometheus_tsdb_head_samples_appended_total[1h]) * 15 * 86400 * 2
absent_over_time(up{job=~".*prometheus.*"}[5m])
alertmanager_cluster_members < 3
rate(prometheus_remote_storage_samples_failed_total[5m]) > 0
sum by (user, reason) (rate(cortex_discarded_samples_total[5m])) > 0
time() - max(thanos_objstore_bucket_last_successful_upload_time) > 3 * 3600   # Thanos sidecar upload stalled (metric name depends on version)
kubectl -n monitoring exec prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus -- \
  promtool tsdb analyze /prometheus | head -30
Block ID: 01JD…
Duration: 2h0m0s
Total Series: 41234
Label names: 128
…
Highest cardinality metric names:
6120 apiserver_request_duration_seconds_bucket
…

Lab: run an architecture review on the environment built in this lesson

Goal: fill in the review table with real data and answer “What happens if this scales to 20 clusters?” About 10 minutes, on paper + queries.
Collect a capacity snapshot: on the lab Prometheus, run the first section of the “Commands” page and record active series and sample rate; on Mimir, run sum by (user) (cortex_ingester_active_series) (data source: Mimir’s /metrics or the data kps scrapes from Mimir).
Estimate: plug the numbers into the scorecard on the “Animation” page (enter 2 clusters first, then 20), and record the recommended topology and disk estimate.
Failure drill check: against Figure 8-2, actually run one kubectl -n mimir scale deploy/mimir --replicas=0, wait 5 minutes, then recover; check whether lab alerts still work (full Prometheus evaluates locally), whether remote write backfills (prometheus_remote_storage_samples_retried_total the rise then drop back), and whether the lab-b Agent backlog builds up.
Write the review conclusions (template):
## Monitoring architecture review · lab + lab-b · 2026-11
| Dimension | Current state | Risk | Action |
|---|---|---|---|
| Collection | kps / PrometheusAgent, unique cluster label | lab-b has no local alerting | Central Mimir ruler evaluates lab-b rules |
| HA | Prom×2, AM×3 | Mimir monolith with a single replica | Use mimir-distributed in production |
| Storage | Mimir filesystem | Non-production backend | Cloud object storage + lifecycle |
| Tenants | One tenant per cluster | Tenant header can be forged | Add an auth gateway |
| Alerts | myapp SLO multi-window | 3d window exceeds local retention | Migrate to Mimir ruler |
| OTel | Collector → two replicas | No up metric | Alert on missing target_info |
| Grafana | Folders + teams | OSS has no data source permissions | Separate org for sensitive tenants |
| Self-monitoring | Watchdog | No external heartbeat | Connect to a dead man’s switch service |
Cleanup: kubectl -n mimir scale deploy/mimir --replicas=1.

Case 1: the review found that “nothing was monitoring the monitoring”

Problem: A misconfigured Alertmanager (the receiver webhook URL was broken) meant no notifications went out for 9 hours, and nobody noticed.

Approach: The kps Watchdog alert (always firing) is routed to an external heartbeat service, which phones someone if nothing arrives for more than 5 minutes; add rate(alertmanager_notifications_failed_total[5m]) > 0 alerts sent to a second channel (email).

Case 2: a capacity review prevented an incident

Problem: The plan was to connect 30 clusters to the central Mimir, with the existing ingesters sized for 6 million series.

Approach: During the review, using prometheus_tsdb_head_series totaled 21 million series, with kube-state-metrics and cAdvisor making up 55%; first, on each cluster, use write_relabel_configs to drop metrics that do not need central storage (cutting it to 9 million), then scale the ingesters accordingly and set per-tenant limits with 1.2× headroom.

Case 3: a small team chooses a managed service

A team with only 2 SREs and 5 AKS clusters. The review concluded: each cluster's kps keeps only 2 days locally, Azure Monitor managed Prometheus (Lesson 3) handles long-term storage and global queries, and Azure Managed Grafana handles visualization; do not self-host Mimir/Thanos. Reason: operations staff is the scarcest resource.

Interactive troubleshooting tree: cross-component issues in the monitoring platform

Start from the symptom and choose step by step; the leaf nodes give diagnostic commands and fixes. Covers all modules in this lesson.

Common errors (additional)

In Grafana’s global dashboard some clusters “disappear”, but the local Prometheus of those clusters is healthy

Cause: remote write from that cluster is failing (authentication, limits, network), or cluster the label spelling does not match the dashboard variable.

rate(prometheus_remote_storage_samples_failed_total[5m])
count by (cluster) (up)
The same alert is received once from the local Alertmanager and once from the Mimir Alertmanager

Cause: The same rule is being evaluated by both the local Prometheus and the central ruler.

Fix: Make rule ownership explicit: keep local fallback rules and central rules separate by name/label, or evaluate them in only one place; use source a label to mark the source.

Command-line tasks

1. Write PromQL: estimate the disk needed for 30 days at the current ingestion rate (GiB, 2 bytes per sample).

Reference answer
rate(prometheus_tsdb_head_samples_appended_total[1h]) * 30 * 86400 * 2 / 1024^3

2. Write the promtool command: analyze /prometheus the cardinality of the data directory.

Reference answer
promtool tsdb analyze /prometheus

Scenario analysis: Review a design: “20 clusters all in Agent mode → monolithic Mimir (filesystem backend, 1 replica) → Grafana; all alerting rules in the Mimir ruler”. Identify at least 4 problems and suggest improvements.

Reference answer

① A single monolith with one replica on filesystem: a single point of failure, with data on one disk, not suitable for production → mimir-distributed + object storage, ingester replication factor 3. ② All Agent: when the central system is down, no cluster has alerting → keep full Prometheus on key clusters + local fallback rules. ③ No tenants or limits: one cluster’s cardinality explosion takes everything down → per-cluster or per-team tenants + limits. ④ No auth gateway: anyone can write to or read any tenant → the gateway injects the tenant header. ⑤ The Mimir ruler also needs Alertmanager HA and self-monitoring (Watchdog to an external heartbeat). ⑥ Capacity not estimated: total series for 20 clusters and the ingester memory needed must be quantified.

Verified educational videos

▶
Prometheus – What it is, What is New, and What is Coming - Richard Hartmann & Julien Pivotto — CNCF [Cloud Native Computing Foundation]
English · Prometheus maintainers on the project’s current state and direction
▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · architecture review summary

Official documentation

Video storyboard script

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: A whiteboard with 8 boxes: collection, HA, storage, tenants, alerting, OTel, Grafana, self-monitoring.
Narration: Review a monitoring architecture by going through these 8 questions.
Shot 2 · 0:20–0:50
Visual: Formula animation: 800k series ÷ 30 s × 15 days × 2 bytes ≈ 69 GB.
Narration: Capacity estimates rely on the official formula, not on gut feeling.
Shot 3 · 0:50–1:30
Visual: The failure domain matrix lights up row by row: replica, AM, Mimir 1 hour, Mimir 6 hours.
Narration: For each failure, answer what happens to scraping, alerting, queries and data.
Shot 4 · 1:30–1:50
Visual: The Watchdog heartbeat stops and the external service calls.
Narration: Finally, don’t forget to monitor your monitoring.
or score ≥ 70% on the “Quiz”

Command cheat sheet

Lesson 6: architecture selection, HA, Thanos/Mimir, multi-tenancy, SLO, OTel, Grafana governance

Federation / remote write / Agent

curl -sG :9090/federate --data-urlencode 'match[]={__name__=~"job:.*"}'
# Upper layer: honor_labels: true, metrics_path: /federate
remote_write:
  - url: http://mimir:9009/api/v1/push
    headers: {X-Scope-OrgID: cluster-lab}
    write_relabel_configs: [{source_labels: [__name__], regex: 'go_.*', action: drop}]
prometheus --agent --config.file=agent.yml
promtool check config --agent agent.yml

HA (kps values)

prometheus:
  prometheusSpec: {replicas: 2, externalLabels: {cluster: lab}}
alertmanager:
  alertmanagerSpec: {replicas: 3}
amtool cluster show --alertmanager.url=http://localhost:9093
# PromQL
alertmanager_cluster_members != 3

Thanos

thanos sidecar --tsdb.path=/prometheus --prometheus.url=http://localhost:9090 \
  --objstore.config-file=objstore.yml
thanos query --endpoint=dnssrv+_grpc._tcp.<svc> --query.replica-label=prometheus_replica
thanos store --objstore.config-file=objstore.yml
thanos compact --wait --retention.resolution-raw=30d \
  --retention.resolution-5m=90d --retention.resolution-1h=1y
thanos tools bucket inspect --objstore.config-file=objstore.yml

Mimir

mimir -config.file=mimir.yaml -target=all
curl -H 'X-Scope-OrgID: t1' :9009/prometheus/api/v1/query?query=up
curl -H 'X-Scope-OrgID: t1|t2' …        # tenant_federation.enabled
curl :9009/ready ; curl :9009/runtime_config
# runtime.yaml
overrides:
  t1: {ingestion_rate: 10000, max_global_series_per_user: 150000}

SLO multi-window burn rate (SLO 99.9%)

(err:ratio_rate1h > 14.4*0.001 and err:ratio_rate5m > 14.4*0.001)
or
(err:ratio_rate6h > 6*0.001 and err:ratio_rate30m > 6*0.001)   # page
(err:ratio_rate3d > 0.001 and err:ratio_rate6h > 0.001)         # ticket
# Budget consumed = burn × long window / period: 2% · 5% · 10%
promtool test rules myapp-slo-test.yml

OpenTelemetry

prometheus --web.enable-otlp-receiver     # /api/v1/otlp/v1/metrics
otlp:
  promote_resource_attributes: [service.name, k8s.namespace.name]
  translation_strategy: UnderscoreEscapingWithSuffixes
storage: {tsdb: {out_of_order_time_window: 30m}}
# Collector exporter
otlphttp: {endpoint: http://prom:9090/api/v1/otlp}
rate(x_total[5m]) * on (job, instance) group_left (k8s_pod_name) target_info

Grafana API

POST /api/serviceaccounts {"name","role"}
POST /api/serviceaccounts/:id/tokens {"name","secondsToLive"}
POST /api/teams {"name"} ; POST /api/teams/:id/members {"userId"}
POST /api/folders {"uid","title","parentUid"}
POST /api/folders/:uid/permissions {"items":[{"teamId":1,"permission":2}]}  # full replacement
# 1=View 2=Edit 4=Admin; Grafana 13: grafana cli / grafana server

Capacity and self-monitoring

prometheus_tsdb_head_series
rate(prometheus_tsdb_head_samples_appended_total[5m])
# disk ≈ retention seconds × samples/sec × 1–2 bytes
rate(prometheus_remote_storage_samples_failed_total[5m]) > 0
sum by (user, reason) (rate(cortex_discarded_samples_total[5m])) > 0
sum by (user) (cortex_ingester_active_series)

Quick troubleshooting table

Symptom / errorMost likely causeFirst step
remote write receiver needs to be enabledReceiver not enabledenableRemoteWriteReceiver / switch to Mimir
/federate context deadline exceededFull federationmatch only job: recording rules
Same alert received 2–3 timesAM not clustered / replica label not removedalertmanager_cluster_members,alert_relabel_configs
Grafana curve jumpsService round-robins across two replicasThanos Query dedup or Mimir
no org id (401)Missing X-Scope-OrgIDremote_write headers / data source httpHeaderName1
err-mimir-max-series-per-user (400)Tenant series limit exceeded, data droppedReduce cardinality or adjust overrides
429 ingestion rateSample rate limit exceededingestion_rate / ingestion_burst_size
compactor halted / overlapping blocksMultiple compactors or local compaction not disabledthanos tools bucket verify
SLO recording rule is emptyEmpty vector when the numerator has no 5xxor vector(0)
OTLP 404not enabled --web.enable-otlp-receiver or path duplicatedendpoint uses the base address
field rule_files is not allowed in agent modeAgent config includes rulesmove the rules to the central ruler
Grafana 403 Access deniedfolder permissions / team membershipGET /api/folders/:uid/permissions

Recommended config snippet: per-cluster “standard kps override layer”

prometheus:
  prometheusSpec:
    replicas: 2
    retention: 2d
    externalLabels: {cluster: CHANGE_ME, env: prod, region: canadacentral}
    podAntiAffinity: hard
    podAntiAffinityTopologyKey: topology.kubernetes.io/zone
    remoteWrite:
    - url: https://metrics-gw.example.internal/api/v1/push    # auth gateway → Mimir
      writeRelabelConfigs:
      - {sourceLabels: [__name__], regex: 'go_gc_.*', action: drop}
    tsdb: {outOfOrderTimeWindow: 30m}
alertmanager:
  alertmanagerSpec: {replicas: 3, podAntiAffinity: hard}

Capstone lab + final quiz

Two clusters → Mimir multi-tenancy → Thanos dedup → myapp SLO alerts → OTel → Grafana team permissions → architecture review
60–90 min after classLaptop scale · zero cloud cost
Scenario You are a platform engineer who needs to provide a “mini metrics platform” for the myapp team and the SREs: cluster lab (full Prometheus HA) and lab-b (Agent) data flow into two Mimir tenants; myapp has a 99.9% availability SLO and multi-window alerts; OTel services can also connect; in Grafana, the myapp team can only edit its own folders, and SREs can see global data.
Environment (Modules 0, 2): kps with Prometheus ×2 and Alertmanager ×3,externalLabels.cluster: lab.
kubectl -n monitoring get pods -l 'app.kubernetes.io/name in (prometheus,alertmanager)'
curl -s localhost:9093/api/v2/status | jq '.cluster.peers | length'
Long-term storage (Module 3): deploy a Mimir monolith (multitenancy + tenant_federation + runtime_config), with kps remote-writing to the tenant cluster-lab; deploy Thanos Query and verify that the count differs by a factor of two before and after deduplication.
Second cluster (Module 4): lab-b ’s kps agentMode remote-writes to cluster-lab-b; first set its series limit to 500 and observe err-mimir-max-series-per-user, then raise it; cross-tenant query count by (__tenant_id__, cluster) (up).
SLO (Module 5): promtool test rules After it passes, deploy PrometheusRule myapp-slo; load test + stop Redis, and watch MyappErrorBudgetBurn firing; after recovery it should resolve within 5 minutes.
OTel (Module 6): Collector + telemetrygen sends service.name="myapp-otel" histograms, exporting to both Prometheus replicas and the Mimir tenant at the same time cluster-lab; verify job="shop/myapp-otel" and target_info.
Grafana (Modules 3, 4, 7): data sources Mimir (cluster-lab), Mimir global (cluster-lab|cluster-lab-b), Thanos Query; folder Teams/myapp grants edit only to myapp-team; import the myapp SLO dashboard; verify canEdit with alice.
Review and failure (Module 8): stop Mimir for 5 minutes, confirm local alerting works and remote write backfills; fill in the review table.
Cleanup
kind delete cluster --name lab-b
kubectl delete ns mimir
kubectl -n monitoring delete deploy/thanos-query svc/thanos-query deploy/otelcol svc/otelcol --ignore-not-found
kubectl -n myapp delete prometheusrule myapp-slo
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 \
  -f ~/promlab/k8s/kps-part5-values.yaml --wait        # restore the Lesson 5 configuration; Lesson 7 continues to use lab
Acceptance checklist

Open-ended self-test (6 questions)

1. Why does Thanos sidecar mode require Prometheus to disable local compaction?

The sidecar uploads the 2h blocks Prometheus generates. If local compaction keeps merging them into larger blocks, the same time range gets uploaded again, the bucket ends up with overlapping blocks, and the compactor halts because of the overlap. When object storage is configured, the Operator automatically sets min/max block duration to 2h.

2. What are the storage costs of Mimir’s replication factor of 3 versus Prometheus’s 2 replicas?

Prometheus replica pair: scraping and local storage are both 2 copies. If both replicas remote-write, Mimir ends up with two sets of series (unless the HA tracker accepts only one). Mimir’s internal ingesters replicate 3 copies (memory and WAL); after upload to object storage, the compactor deduplicates to 1 copy.

3. Why is the short window 1/12 of the long window?

This is an empirical ratio from the SRE Workbook: the short window is short enough that the alert recovers within minutes after the fix, yet not so short that a momentary blip triggers it alone (because the long window must also exceed the threshold).

4. When should you choose Agent mode instead of full Prometheus?

When there are many clusters, each cluster needs no local queries or alerting, and central storage and the ruler are highly available; keep full Prometheus for clusters where alerting continuity is critical.

5. In OSS Grafana, how do you stop team A from querying team B’s data?

Folders only govern dashboards. At the data level, rely on separate tenant data sources (Mimir) + separate organizations, or upgrade to Enterprise/Cloud and use data source permissions; the gateway injects the tenant header.

6. What should the SLO of your monitoring platform itself be?

For example: query success rate 99.5% (share of non-5xx Grafana/Mimir queries), alert delivery latency p99 < 2 minutes (Watchdog heartbeat interval), write success rate 99.9% (share of non-dropped samples). Alert on burn rate as well, but the notification channel must be independent of the platform being monitored.

Sources and version notes

Verified: 2026-11-15 (some items tested on local Docker on 2026-11-16)
TopicVerification resultSource (date)
Prometheusv3.16.0 (2026-11-05); v3.15.1 and v3.13.5 patches (2026-10-21); --agent,--storage.agent.retention.max-time default 4h; --web.enable-remote-write-receiver,--web.remote-write-receiver.accepted-protobuf-messages (prometheus.WriteRequest / io.prometheus.write.v2.Request); --web.enable-otlp-receiverGitHub releases · command-line flags
Native histogramsstable since v3.8.0; scraping still requires scrape_native_histograms; since v3.9 the old feature flags are no-opsNative Histograms spec
Remote-Write 2.0Spec status Experimental (2.0-rc); symbol table, metadata, exemplars, start timestamp; response header X-Prometheus-Remote-Write-*-WrittenRW 2.0 spec
OTLP receiver/api/v1/otlp/v1/metrics; translation_strategy has four options; resource attributes are not promoted by default; recommended out_of_order_time_window: 30m; otlp-deltatocumulative experimental; info() experimental functionsOpenTelemetry guide · Feature flags
Alertmanagerv0.35.0 (2026-11-09); cluster flags --cluster.listen-address (default 0.0.0.0:9094),--cluster.peer,--cluster.peer-timeout (default 15s)releases · README HA
Thanosv0.42.5 (2026-10-27); components sidecar/store/compactor/receive/ruler/query/query-frontend; --endpoint,--query.replica-label; compactor must be a singleton; external labels must be globally uniquereleases · Quick tutorial
Grafana Mimir3.2.5 (2026-11-13; also 3.1.10 and 2.17.12 patches); 3.0 released 2025-10-31: Kafka ingest storage, MQE default, read-write deployment mode removed; demo config (filesystem, port 9009,/api/v1/push,/prometheus)releases · Get started · 3.0 release notes
Mimir tested (local Docker, 2026-11-16)grafana/mimir:3.2.5 starts and becomes ready with this lesson’s mimir.yaml; no tenant header returns 401 no org id; a|b cross-tenant query 200; runtime overrides take effect; Prometheus v3.16.0 Agent reports 400 when a write exceeds limits per-user series limit of 100 exceeded (err-mimir-max-series-per-user),cortex_discarded_samples_total{reason="per_user_series_limit"} growthTested by the lesson author
promtool testedin prom/prometheus:v3.16.0 promtool check rules (8 rules) and promtool test rules (this lesson’s SLO test) both SUCCESS; promtool check config --agent for rule_files reports field rule_files is not allowed in agent modeTested by the lesson author
OTel testedotel/opentelemetry-collector:0.165.0 + telemetrygen v0.165.0 → Prometheus 3.16 OTLP: yields gen_bucket/_count/_sum,gen_total,target_info; job=shop/myapp-otel, instance=pod-1Tested by the lesson author · Collector releases(v0.165.0, 2026-11-07)
kube-prometheus-stack93.3.0 (2026-11-13); values include prometheus.agentMode,prometheusSpec.thanos (experimental),thanosService (gRPC 10901),enableRemoteWriteReceiver,enableOTLPReceiver,otlp,tsdb.outOfOrderTimeWindow,replicaExternalLabelName; Prometheus Operator v0.95.2 (2026-11-12)helm-charts releases · chart values.yaml (93.3.0 tag) · Operator releases
Grafana13.3.1 (2026-11-10), same-day patches 13.2.6 / 13.1.10 / 13.0.13 / 12.4.15; 13.0: Git Sync GA, dynamic dashboards default, stricter RBAC validation, grafana-cli/grafana-server removed,/api deprecated in favor of /apis, Image Renderer no longer supported, 12.x→13.0.0 Git Sync data loss riskreleases · What's new in 13.0
Grafana permissionsBasic roles Admin/Editor/Viewer/No basic role; folders are the main permission boundary; View/Edit/Admin; RBAC is Enterprise/Cloud; Cloud has no server adminRoles and permissions
Grafana as codeTerraform provider v4.55.0 (2026-11-13); Grafana Operator v5.26.0 (2026-11-16)provider releases · operator releases
SLOMulti-window multi-burn-rate: 1h/5m×14.4 (2%), 6h/30m×6 (5%), 3d/6h×1 (10%); Sloth v0.16.0 (2026-04-04)SRE Workbook · Sloth releases
MinIOThe minio/minio repository is archived and its README marks it as no longer maintained (replaced by the AIStor product); this lesson therefore does not use MinIOgithub.com/minio/minio
Capacity formulaDisk needed ≈ retention seconds × samples ingested per second × bytes per sample (about 1–2)Prometheus Storage

Video verification notes

The titles and channels of the following videos were verified on 2026-11-15/16 via the YouTube oEmbed API: Grafana “Why Prometheus 3.0 Will Change How You Do Observability…” (YubGvtyFJG8); Prometheus Monitoring “PromCon EU 2019: Remote Write Storage Wars” (OsH6gPdxR4s); CNCF “From Manual to Managed: Prometheus Agent Deployment at Scale - Mihail Mihaylov” (xyaoYeak_7Q); Prometheus Monitoring “PromCon 2017: Alertmanager and High Availability - Frederic Branczyk” (i6Hmc0bKHAY); TechWorld with Nana “How Prometheus Monitoring works | Prometheus Architecture explained” (h4Sl21AKiDg); Anton Putra “Thanos (Multi Cluster Prometheus) Tutorial…” (feHSU0BMcco); Grafana “Thanos - Transforming Prometheus to a Global Scale in a Seven Simple Steps” (Iuo1EjCN5i4); Grafana “Introducing Grafana Mimir” (ej9y3KILV8g); Grafana “Getting started with Grafana Mimir” (pTkeucnnoJg); Grafana “Migrating to Grafana Mimir” (aaGxTcJmzBw); CNCF “Absorbing Thanos Infinite Powers for Multi-Cluster Telemetry - Bartlomiej Płotka” (6Nx2BFyr7qQ); DoKC “How to Alert on SLOs using Error Budget Burn Rate // DoK Talks #81” (F0vIIxoBom0); Nobl9 “SLOconf 2022: Petr Hajek - Alerting on High and Low Traffic Using SLOs” (4mtIDt8E9zE); CNCF “Prometheus and OpenTelemetry: Better Together - Adriana Villela & Reese Lee” (LJd1pJ0k28g); Grafana “Grafana Dashboard Provisioning, Teams & Permissions, and Running Grafana in a HA Environment” (ezpc4oUZyaA); Grafana “Grafana 13 Deep Dive…” (giocvyAXO28); CNCF “Prometheus – What it is, What is New, and What is Coming - Richard Hartmann & Julien Pivotto” (UsxIDNNIwa0). Some videos were recorded on older versions, so refer to this lesson and the official docs for details.

Audio narration notes

The “Audio” page reads the narration script aloud using the browser’s Web Speech API (en-US), with English terms pronounced in en-US. The result depends on the speech packs installed on the operating system. The courseware generation environment cannot call a TTS service, so no MP3 is embedded; the narration script can be passed directly to another TTS tool to produce audio.

Known limitations

  • IPs, Pod names, ULIDs, timestamps and counts in the “Expected output” are example values. Output labeled “tested” comes from local Docker (Prometheus 3.16.0, Mimir 3.2.5, Collector/telemetrygen 0.165.0). The full steps in the kind cluster (kps upgrade, lab-b, Thanos Query, Grafana API) were not actually run in this environment.
  • Object names generated by kps (such as kps-kube-prometheus-stack-prometheus,…-thanos-discovery, Secret names) are inferred from chart naming rules; please refer to the kubectl get actual output. The Grafana/Prometheus image versions packaged in kps 93.3.0 may not be the latest versions listed in this lesson.
  • Conservative handling (refer to the official docs): the KV store type required by the Mimir HA tracker; in Prometheus 3, the retry_on_http_429 default value; the PDB key name in kps; which prometheusSpec fields are passed to PrometheusAgent under agentMode; Grafana alerting HA parameters; fields returned by the Grafana API; Sloth spec fields; Mimir error ID text (only the max-series one was tested); the Thanos upload time metric name.
  • The claim that myapp returns 5xx when Redis is unavailable is inferred from the behavior of myapp in the Docker lesson. If your implementation degrades and returns 200, inject the error using the alternative method from the lab.
  • The timing and calculator assumptions in the animations (constant traffic, step-change error rate) are teaching simplifications, not benchmarks. Lessons 1–5 were written in parallel with this one; for cross-lesson references, the final content of each lesson governs.