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.
Prometheus & Grafana Hour 6: Monitoring Architecture in Practice
- 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 headerX-Scope-OrgIDto 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
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: multi-cluster sample environment | Reuse the kind cluster from Hour 5 lab + kps (release: kps) + myapp; add a second kind cluster lab-b; resource estimates | — | kind create / helm list |
| 1 | 00–06 | Architecture choices | Single instance, vertical / functional sharding, federation /federate, remote write (1.0 / 2.0), Agent mode (--agent) | Topology selector: data flow in the four architectures | Federation scrape + Agent-mode container remote write |
| 2 | 06–13 | High availability | Replica pair + prometheus_replica, Alertmanager gossip cluster (9094), notification log deduplication, shards | HA failure simulation: kill replica / kill AM / network partition | kps: Prometheus ×2, Alertmanager ×3 |
| 3 | 13–21 | Thanos and Mimir | sidecar/receive/store/compactor/query and distributor/ingester/store-gateway/querier; object storage, downsampling, Mimir 3 ingest storage | Core animation: write and query paths (switchable between Thanos / Mimir) | Thanos Query deduplication + single-binary Mimir (filesystem backend) |
| 4 | 21–28 | Multi-cluster and multi-tenancy | cluster external labels,X-Scope-OrgID, cross-tenant federated queries, per-tenant limits, prom-label-proxy | Tenant routing and limits simulator | lab-b Agent → Mimir tenant cluster-lab-b |
| 5 | 28–35 | SLO and burn rate | SLI/SLO/error budget, multi-window multi-burn-rate (14.4/6/1), recording rules, Sloth/Pyrra | Core interaction: burn rate calculator | myapp SLO PrometheusRule + fault injection |
| 6 | 35–42 | OpenTelemetry and Prometheus | OTLP ingestion (/api/v1/otlp/v1/metrics),promote_resource_attributes, translation_strategy,target_info | OTel metric name translator | OTel Collector → Prometheus OTLP |
| 7 | 42–50 | Scaling Grafana | Organizations, nested folders, teams, basic roles, RBAC (Enterprise/Cloud), service accounts, Git Sync, Terraform / Operator | Effective permissions calculator | API: create teams / folders / permissions |
| 8 | 50–60 | Comprehensive architecture review | Review checklist, capacity estimate, cost, failure domains, interactive troubleshooting tree | Architecture scorecard + troubleshooting tree | Capacity and cardinality estimate |
| — | After class | Cheat sheet · Integrated lab | Two clusters → Mimir multi-tenancy → SLO alerts → Grafana team permissions | Final quiz, 12 questions | Acceptance checklist |
Knowledge coverage matrix
| Target skill | Module | Key commands / configuration | Lab | Production case |
|---|---|---|---|---|
| Architecture choices (federation / remote write / Agent) | M1 | /federate?match[]=,remote_write,--agent | ✓ | ✓ |
| Prometheus HA and alert deduplication | M2 | replicas: 2,external_labels,--cluster.peer | ✓ | ✓ |
| Long-term storage (Thanos) | M3 | thanos sidecar / query --query.replica-label, objstore.yml | ✓ | ✓ |
| Long-term storage (Mimir) | M3 · M4 | /api/v1/push,/prometheus,-target=all | ✓ | ✓ |
| Multi-cluster / multi-tenancy | M4 | X-Scope-OrgID,tenant_federation,overrides | ✓ | ✓ |
| SLO and burn rate alerts | M5 | PrometheusRule,promtool test rules | ✓ | ✓ |
| OpenTelemetry ingestion | M6 | --web.enable-otlp-receiver, otelcol otlphttp | ✓ | ✓ |
| Grafana organizations and permissions | M7 | /api/teams,/api/folders/:uid/permissions | ✓ | ✓ |
| Architecture review and capacity estimation | M8 | prometheus_tsdb_head_series,rate(prometheus_tsdb_head_samples_appended_total[5m]) | On paper | ✓ |
Out of scope for this hour
| Topic | Reason | Where to learn |
|---|---|---|
| Full parameter set for production Helm deployments of Mimir / Thanos (mimir-distributed, bitnami thanos chart), memcached cache tuning | Needs hours and lots of resources; this hour only covers laptop scale | mimir-distributed documentation · Thanos Getting started |
| Managed long-term storage (Azure Monitor managed Prometheus, Amazon Managed Service for Prometheus) | Covered in Hours 3 and 4 | Hour 3 · Hour 4 |
| Cardinality explosion, TSDB head/WAL/compaction internals, query performance tuning | A topic for Hour 7 | Hour 7 |
| Logs (Loki) and traces (Tempo) backends, end-to-end exemplars | Beyond the scope of metrics monitoring | Grafana Loki / Tempo documentation |
| Detailed comparison of Cortex and VictoriaMetrics | Time constraints; mentioned only in the comparison table | Official project documentation |
How to use this courseware
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.
A quiz score ≥ 70% or clicking “Mark module complete” counts toward progress, saved in this browser (key name
prom60-part6-progress-v1).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.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
lab + kube-prometheus-stack (release kps, namespace monitoring) + myapp, plus one “remote cluster” lab-b- Completed Hour 5: kind cluster
lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoringinstalled; myapp (Flask + gunicorn, port 5000,/metrics) running in namespacemyapp, ServiceMonitor with labelrelease: 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
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
| Component | Memory (approx.) | Notes |
|---|---|---|
kind lab + kps (after Prometheus ×2 and Alertmanager ×3) | 2.5–3.5 GiB | Increases after Module 2 scales up the replica count |
| Mimir single binary (filesystem backend) | 0.3–0.8 GiB | From Module 3 |
| Thanos Query | ≈ 0.1 GiB | Module 3 |
kind lab-b + kps (agent mode) | 1–1.5 GiB | Module 4, optional |
| OTel Collector | ≈ 0.1 GiB | Module 6 |
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).Module 1 · Monitoring architecture choices: single instance, federation and remote write
--agent) · RW 2.0 experimental★★★★★ Architecture fundamentals- 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.
What: four basic topologies
| Topology | Approach | Where the data lives | Typical scale |
|---|---|---|---|
| Single instance | One Prometheus scrapes all targets, with local TSDB storage + rules + alerts | Local 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 sharding | Split into several Prometheus servers by team/domain (infrastructure, app A, app B), each independent | Each stores locally | Teams are autonomous, but there is no global view |
| Federation | An upper-level Prometheus scrapes the lower-level /federate endpoint, pulling only series matching match[] series'latest value | Both layers store a copy | Only suits thousands to tens of thousands of series aggregated series (such as job: prefixed recording rules) |
| Remote write | Each Prometheus pushes new samples from its WAL to central storage (Thanos Receive, Mimir, managed services) | Central storage (long-term retention) + short local retention | Central storage scales horizontally to hundreds of millions of series |
| Agent mode | prometheus --agent: scrape + remote write only; no local queries, rules or alerts; the WAL is truncated as soon as it is sent successfully | Remote only | Edge, 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
| Dimension | Federation /federate | Remote write remote_write |
|---|---|---|
| Direction | Pull (the upper layer does a scheduled GET) | Push (the lower layer does HTTP POST of snappy-compressed protobuf) |
| Data | Each request fetches only the current latest sample (an instantaneous value at scrape time); intermediate samples are lost | In the WAL,every sample is sent (can be filtered with write_relabel_configs ) |
| Outage | Data during the outage is permanently lost | Within the WAL retention window (about 2 hours), data is resent after recovery |
| Labels | Requires 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 to | Cross-layer aggregation of a few metrics, and migration | Long-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).
/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
Data flow: inside remote_write
prometheus_remote_storage_highest_timestamp_in_seconds - prometheus_remote_storage_queue_highest_sent_timestamp_secondsInteractive: 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.
Core commands and configuration
| Command / configuration | Purpose | Key parameters |
|---|---|---|
curl -G /federate --data-urlencode 'match[]=…' | Manually inspect what the federation endpoint returns | at least one match[]; returns text format |
scrape_configs[].metrics_path: /federate | Upper layer scrapes lower layer | honor_labels: true,params.match[] |
remote_write[] | pushes to remote | url,headers,queue_config,write_relabel_configs,protobuf_message |
prometheus --agent | Agent mode | --storage.agent.path (default data-agent/),--storage.agent.retention.max-time (default 4h) |
--web.enable-remote-write-receiver | Makes Prometheus act as a remote write receiver (/api/v1/write) | Off by default, no authentication |
promtool check config | Validate configuration | The 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)
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.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.
# 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_IPcat > ~/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' | headsleep 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).
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.
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.
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: dropScenario 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
Official documentation
- Federation
- remote_write configuration
- Remote write tuning
- Remote-Write 2.0 specification (Experimental)
- prometheus command-line flags (--agent, etc.)
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.
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.
Narration: Federation is a pull, and it only pulls the latest value, so it suits a small number of aggregated metrics.
Narration: Remote write is a push: every sample in the WAL is sent out, and a brief outage can be caught up afterward.
Narration: Agent mode is lighter, but alerting has to be handed to the center. Choosing an architecture means making decisions among these trade-offs.
Module 2 · High availability: Prometheus replicas and an Alertmanager cluster
- 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.
What: HA at the two layers uses two different mechanisms
| Component | HA approach | State sync | Deduplication happens in |
|---|---|---|---|
| Prometheus | N identically configured replicas, each scraping, storing and evaluating rules independently | None (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) |
| Alertmanager | N 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
- Each Prometheus replica sends the same alert to all Alertmanagers (kps gets each Pod IP through endpoints service discovery on the alertmanager Service).
- Each AM instance groups independently and waits
group_wait. When it is time to send, each instance waits according to its position in the clusterposition × --cluster.peer-timeout(default 15s): position 0 sends immediately, position 1 waits 15 seconds, position 2 waits 30 seconds. - 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.
- The alert's
prometheus_replicalabel must be removed before sending (the Prometheus Operator generatesalert_relabel_configsto 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.
| Comparison | Prometheus replica pair | Thanos Receive / Mimir (replication factor 3) |
|---|---|---|
| Data replication | Two independent replicas, each scraping | replicated to 3 ingesters/receivers on the write path (acknowledged once a majority succeeds) |
| At query time | requires deduplication (replica label) | the query layer merges automatically |
| Cost | scraping ×2, storage ×2 | storage ×3 (in memory); object storage keeps only 1 copy (compactor deduplicates) |
Architecture diagram: the HA topology in kps
Sequence diagram: deduplicating one alert
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.
Scraping
Scraping
Position 0
Position 1
Position 2
Core commands and configuration
| Command / configuration | Purpose | Key parameters |
|---|---|---|
prometheusSpec.replicas | Prometheus replica count | Operator adds external label prometheus_replica (the name can be replicaExternalLabelName changed) |
prometheusSpec.shards | horizontal sharding by target hashmod | each shard has replicas replicas; queries need an aggregation layer |
alertmanagerSpec.replicas | Alertmanager cluster size | The Operator adds it automatically --cluster.peer |
alertmanager --cluster.listen-address / --cluster.peer / --cluster.peer-timeout | cluster parameters for manual deployments | listens on default 0.0.0.0:9094, peer-timeout defaults to 15s |
amtool cluster show | View cluster status and members | --alertmanager.url |
alertmanager_cluster_members | cluster member count metric | should 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
lab, kps release kps, namespace monitoring. About 10 minutes; memory increases by about 0.8 GiB.~/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
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 .
ready.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.
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.
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.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.
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
Official documentation
- Alertmanager · High Availability
- Alertmanager README (cluster parameters)
- Prometheus Operator · High Availability
Video storyboard script
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided.
Narration: The monitoring system is most likely to fail exactly when you need it most.
Narration: Prometheus high availability is simple: two replicas, each scraping on its own, with no replication.
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.
Narration: Deleting any one instance does not lose silences or alerts.
Module 3 · Long-term storage: Thanos and Grafana Mimir
- 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.
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.
| Dimension | Thanos (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 |
| Queries | Query (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) |
| Compaction | Compactor: merging, vertical deduplication,downsampling (5m, 1h) and retention by resolution | Compactor: split-and-merge compaction, deduplicates 3 replicas, sharded by tenant; no downsampling |
| Multi-tenancy | Receive supports a tenant header (default THANOS-TENANT), while multi-tenancy on the query side needs extra components or conventions | Native: each request's X-Scope-OrgID, with per-tenant limits, isolation and cross-tenant federated queries. |
| Deployment form | Multiple independent binary subcommands (same thanos image) | Single binary (-target=all) or microservices (mimir-distributed Helm chart) |
| Suited for | Many existing Prometheus instances, wanting to gradually add a global view and long-term storage; sidecar mode needs no change to the write path | Platform 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_labelsmust 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 withobjectStorageConfig. 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).
Architecture diagram A: Thanos (sidecar mode + Receive mode)
Architecture diagram B: Grafana Mimir (microservices view)
-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.
Core commands and configuration
| Command | Purpose | Key parameters |
|---|---|---|
thanos sidecar | Sits next to Prometheus: StoreAPI + block upload | --tsdb.path,--prometheus.url,--objstore.config-file,--grpc-address |
thanos query | Global PromQL and deduplication | --endpoint (repeatable, supports dns+/dnssrv+),--query.replica-label |
thanos store | Serves historical data from the bucket | --objstore.config-file,--data-dir (index cache) |
thanos compact | Compaction, deduplication, downsampling, retention | --wait,--retention.resolution-raw/5m/1h,--deduplication.replica-label |
thanos tools bucket inspect / ls | Inspect blocks in the bucket | --objstore.config-file |
mimir -config.file=… -target=all | Runs all components in one process | -target can be distributor, ingester, querier, etc. |
mimirtool | Command-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
| Endpoint | Purpose |
|---|---|
POST /api/v1/push | Prometheus remote write |
/prometheus/api/v1/query,/prometheus/api/v1/query_range | PromQL (set the Grafana data source URL to /prometheus) |
POST /otlp/v1/metrics | OTLP metric ingestion (Module 6) |
/ready,/config,/runtime_config,/distributor/all_user_stats | readiness, 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
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.~/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
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 &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
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=3mcluster-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.
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
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.
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).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.
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
Official documentation
- Thanos Quick Tutorial (component overview)
- Thanos Compactor
- Mimir Get started
- Mimir architecture
- Mimir 3.0 release notes
Video storyboard script
This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.
Narration: Prometheus creates an immutable block every two hours. The idea behind long-term storage is simple: put the blocks into object storage.
Narration: Thanos works alongside the existing Prometheus, and the query layer handles merging and deduplication.
Narration: Mimir is a multi-tenant service, and Prometheus only needs remote write.
Narration: Don't forget the compactor: without it, queries get slower and slower, and storage gets more and more expensive.
Module 4 · Multi-cluster and multi-tenancy
cluster labels to tell “where the data came from” apart, and tenants to tell “who the data belongs to” apart- 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|band__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.
What: two orthogonal dimensions
| Dimension | Implementation | What it provides | What 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 cluster | No 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 queuing | Cross-tenant queries require explicitly enabling federated queries |
Why: why platforms need tenants
- Blast radius: a team ships a metric with a
user_idlabel (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
| Model | Example | Pros | Cons |
|---|---|---|---|
| One tenant per cluster | cluster-lab,cluster-lab-b | Simplest write configuration (cluster-level remote_write header) | Teams within the same cluster share a quota |
| One tenant per team | team-payments | Quotas and permissions match the org structure | Writes 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 environment | prod,nonprod | non-production does not affect production | No 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
clusterlabel 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).
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
Flowchart: how the distributor evaluates a write request
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
overrides:
cluster-lab-b:
ingestion_rate: 10000
max_global_series_per_user: 500
# Other tenants use default limits (Mimir defaults apply)
Core commands and configuration
| Command / configuration | Purpose | Key points |
|---|---|---|
external_labels.cluster | Source identifier | globally unique, decide early |
remote_write[].headers.X-Scope-OrgID | Write tenant | safer when injected by the gateway in production |
tenant_federation.enabled | Cross-tenant query | Query 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_stats | Per-tenant ingestion statistics | series count, sample rate |
prom-label-proxy --label=namespace --upstream=… | Query isolation outside of Mimir | requires 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
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).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.
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.
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.
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
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).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}'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: 500002. 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
Official documentation
- Mimir authentication and authorization (tenant header and gateway)
- Mimir runtime configuration
- Mimir runbooks (error IDs)
- Thanos Receive (tenants)
- prom-label-proxy
Video storyboard script
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.
Narration: Multi-cluster is first a labeling problem: every data point needs to know where it came from.
Narration: Multi-tenancy is an isolation problem: who the data belongs to, who can see it, and how much they can use.
Narration: If one team's cardinality explodes, it only exhausts its own quota.
Narration: The tenant header is not authentication, so it must be injected by the gateway.
Module 5 · SLOs and error budgets: burn rate alerts
- 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 rulesunit tests. - Know that tools such as Sloth, Pyrra, and OpenSLO can generate these rules automatically.
rate() (Lesson 1). Priority:★★★★★What: SLI, SLO, error budget, burn rate
| Term | Definition | myapp example |
|---|---|---|
| SLI (service level indicator) | good events / all events | Availability 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 window | 99.9% available over a 30-day rolling window; 99% of requests ≤ 0.5 s |
| Error budget | 1 − SLO | 0.1%: about 43.2 minutes of “total failure” over 30 days, or 1,000 failures per 1 million requests |
| burn rate | Current error rate ÷ error budget | Error 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)
| Severity | Long window | Short window | burn rate | Budget consumed at trigger (30 days) | Error rate threshold (SLO 99.9%) |
|---|---|---|---|---|---|
| Page (call immediately) | 1h | 5m | 14.4 | 2% | 1.44% |
| Page | 6h | 30m | 6 | 5% | 0.6% |
| Ticket | 3d | 6h | 1 | 10% | 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”.
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
Flowchart: from counter to alert
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
| Object | Purpose | Key points |
|---|---|---|
Recording rule myapp:sli_errors:ratio_rate<window> | Precomputes the error ratio for each window | Naming follows level:metric:operations |
Alert MyappErrorBudgetBurn | page level (14.4 / 6) | severity: critical |
Alert MyappErrorBudgetBurnSlow | ticket level (1) | severity: warning |
promtool test rules | Rule unit tests | input_series Extended approach 0+20x120 |
sloth generate -i slo.yaml | Generate rules from SLO specs | Sloth 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
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).SUCCESS.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
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).
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).
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.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.
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).
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
Official and authoritative documentation
- Google SRE Workbook · Alerting on SLOs
- Prometheus · Unit testing for rules
- Recording rules naming conventions
- Sloth · Pyrra
Video storyboard script
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.
Narration: Threshold alerts are both noisy and miss chronic problems.
Narration: The SLO gives us a budget, and the burn rate is the fuel consumption.
Narration: The long window ensures significance; the short window ensures timely recovery.
Narration: Rules are code too: test them before going live.
Module 6 · The relationship between OpenTelemetry and Prometheus
- 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.
What: what each project is responsible for
| Capability | OpenTelemetry | Prometheus |
|---|---|---|
| Instrumentation API/SDK | A unified multi-language API covering traces / metrics / logs | Per-language client libraries (myapp uses the prometheus_client) |
| Transport protocol | OTLP (gRPC 4317 / HTTP 4318),push | text / OpenMetrics / protobuf exposition formats (pull); remote write (push) |
| Pipeline | Collector: receivers → processors → exporters | service discovery + relabeling + scraping |
| Storage / query / alerting | Not provided (left to the backend) | TSDB, PromQL, rules, Alertmanager |
| Resource model | Resource attributes (service.name,k8s.pod.name…) separate from data point attributes | Only 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
- 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 URLhttp://prometheus:9090/api/v1/otlp(/v1/metricsis appended automatically). - 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.
- Resource attributes:
service.namespace/service.name→job(with a namespace it becomesnamespace/name),service.instance.id→instanceother resource attributes are not by default added to every metric; instead they go into onetarget_infoseries.promote_resource_attributesList the attributes to “promote” to ordinary labels (the official guide gives about 20 recommended attributes). - 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. - Temporality: Prometheus expects cumulative; delta requires the Collector's deltatocumulative processor or the Prometheus experimental feature
--enable-feature=otlp-deltatocumulative. - 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
| Path | Best for | Caveats |
|---|---|---|
| A. Client library + Prometheus scraping (myapp's current setup) | Pure Prometheus stack; requires up and scrape health semantics | one library per language |
| B. OTel SDK → Collector → Prometheus/Mimir OTLP | New services standardize on OTel and also need traces | No 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 / OTLP | Use 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 model | Resource attributes appear as target_info in /metrics |
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
Data translation: one OTLP data point entering Prometheus
info() (experimental function) or joined in a queryInteractive: 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).
Core configuration and commands
| Configuration / command | Purpose | Key points |
|---|---|---|
--web.enable-otlp-receiver | Enable the OTLP receiver in Prometheus | disabled by default, no authentication |
otlp.promote_resource_attributes | resource attributes → labels | no attributes are promoted by default |
otlp.translation_strategy | Name translation strategy | default UnderscoreEscapingWithSuffixes |
otlp.keep_identifying_resource_attributes | keep the original service.* attributes on target_info | default false |
storage.tsdb.out_of_order_time_window | Accept out-of-order samples | official recommendation 30m |
kps: prometheusSpec.enableOTLPReceiver / otlp / tsdb.outOfOrderTimeWindow | the corresponding field in the Operator | camelCase: promoteResourceAttributes,translationStrategy |
telemetrygen metrics | Generate 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
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.~/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'
# 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. …
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"'
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).
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.
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: NoUTF8EscapingWithSuffixes2. 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
Official docs
- Prometheus · Using Prometheus as your OpenTelemetry backend
- OpenTelemetry Collector
- telemetrygen
- Mimir · Configure the OpenTelemetry Collector
- Prometheus Operator API (otlp field)
Video storyboard script
This courseware cannot generate video or MP3 directly, so the storyboard and narration script are provided instead.
Narration: OpenTelemetry and Prometheus are not competitors; they are upstream and downstream.
Narration: At the boundary, both names and labels get converted.
Narration: Only promote the resource attributes you actually query.
Narration: In push mode, high availability depends on replication at the sender or in the backend.
Module 7 · Grafana at scale: organizations, folders, permissions and teams
- 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.
What: Grafana's permission model
| Level | What it is | Isolation | Availability |
|---|---|---|---|
| Grafana server admin | Manages the whole instance: organizations, users, settings | Across all organizations | OSS / Enterprise (Grafana Cloud does not have this role) |
| Organization | An independent set of dashboards, data sources, alerts and teams | Hard isolation: organizations cannot see each other; a user can belong to several organizations, with a different role in each | OSS (in Cloud, one stack is one organization) |
| Basic role | Roles within an organization: Admin, Editor, Viewer, No basic role (no permissions by default; must be granted separately) | Organization-level default permissions | OSS |
| Folder | Container for dashboards, alert rules and library panels; supports subfolders; the main permission boundary | Permissions are inherited by subfolders and content | OSS |
| Team | User group; members / Team Admin | Grant target | OSS; syncing with IdP groups (Team Sync) requires Enterprise/Cloud |
| RBAC | Fine-grained permissions and custom roles, data source query permissions | Precise down to actions and resources | Enterprise / 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/grafanaTerraform provider),Grafana Operator Grafana Operator (GrafanaDashboard / GrafanaFolder CR), file provisioning (kps dashboard sidecar).
When: which manage-as-code approach to choose
| Approach | Best for | Caveats |
|---|---|---|
| File provisioning / kps sidecar | Platform dashboards shipped with Helm | Changes made in the UI cannot be saved back to the file |
| Git Sync | Teams edit in the UI while requiring Git review | When 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 points | Managing large numbers of dashboard JSON files with Terraform is verbose |
| Grafana Operator | Kubernetes-native, GitOps (Argo CD/Flux) | The sync status between CRs and the Grafana instance needs monitoring |
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
Decision diagram: can a user edit dashboards under Teams/myapp
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
Core API and tools
| API / tool | Purpose | Key points |
|---|---|---|
POST /api/serviceaccounts · POST /api/serviceaccounts/:id/tokens | Service accounts and tokens | Replaces old API keys; token settings secondsToLive |
POST /api/teams · POST /api/teams/:id/members | Create teams and add members | Members must be existing user IDs |
POST /api/folders | Create folders (parentUid to create subfolders) | Specify a stable uid |
POST /api/folders/:uid/permissions | Fully replace folder permissions | permission: 1=View, 2=Edit, 4=Admin; grants not listed are deleted |
grafana cli | Plugins, admin password reset, etc. | Starting with Grafana 13, use grafana cli / grafana server, the old grafana-cli,grafana-server have been removed |
Terraform grafana/grafana | grafana_team,grafana_folder,grafana_folder_permission,grafana_dashboard | provider 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
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.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}'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" }
27curl -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.
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.
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
Official docs
- Roles and permissions
- What's new in Grafana 13.0 (including breaking changes)
- Folder permissions API
- Terraform grafana provider
- Grafana Operator
Video storyboard script
This courseware cannot generate video/MP3 directly, so a storyboard and narration script are provided.
Narration: The first step in scaling Grafana is structure.
Narration: Folders are the permission boundary, teams are the grant targets, and organizations are used only when hard isolation is needed.
Narration: Effective permission is the highest of all applicable grants.
Narration: Use Git Sync, Terraform, or the Operator to turn dashboards and permissions into code.
Module 8 · Comprehensive Architecture Review
- 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.
What: review checklist (8 dimensions)
| Dimension | Question to ask | Acceptable answer (example) |
|---|---|---|
| 1. Collection | How is each cluster scraped? Push or pull? | kps (Operator + ServiceMonitor) or Agent; external_labels.cluster unique |
| 2. High availability | If 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 retention | How 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-tenancy | Who can see what? What is the blast radius? | Tenants per team/cluster, limits, tenant header injected by the gateway |
| 5. Alert quality | Are alerts based on SLOs? Are they tested? | Multi-window multi-burn-rate,promtool test rules, runbook link |
| 6. OTel and standardization | Which 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 governance | Folders / teams / permissions / as code? | 1 org + folders + teams, Git Sync/Terraform |
| 8. Monitoring the monitoring | If 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
| Scale | Characteristics | Reference architecture |
|---|---|---|
| Small | 1–3 clusters, < 1M series, retention ≤ 30 days, one team | Per 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) |
| Medium | 5–20 clusters, millions of series, 1-year retention, multiple teams | Per-cluster Prometheus (short retention) remote_write → Mimir (or Thanos sidecar + object storage); central Ruler; Grafana folders + teams |
| Large | Tens to hundreds of clusters, hundreds of millions of series, a platform team serving internal customers | Agent / 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.
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
Failure domain matrix
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 / command | Question answered |
|---|---|
prometheus_tsdb_head_series | Current active series |
rate(prometheus_tsdb_head_samples_appended_total[5m]) | Samples ingested per second |
prometheus_tsdb_storage_blocks_bytes | Local block usage |
sum by (user) (cortex_ingester_active_series) | Mimir series per tenant |
alertmanager_cluster_members,alertmanager_notifications_failed_total | Alerting pipeline health |
promtool tsdb analyze /prometheus | Metrics 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
sum by (user) (cortex_ingester_active_series) (data source: Mimir’s /metrics or the data kps scrapes from Mimir).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.## 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 |
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.
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
Official documentation
Video storyboard script
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: Review a monitoring architecture by going through these 8 questions.
Narration: Capacity estimates rely on the official formula, not on gut feeling.
Narration: For each failure, answer what happens to scraping, alerting, queries and data.
Narration: Finally, don’t forget to monitor your monitoring.
Command cheat sheet
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.ymlHA (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 != 3Thanos
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_infoGrafana 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 serverCapacity 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 / error | Most likely cause | First step |
|---|---|---|
remote write receiver needs to be enabled | Receiver not enabled | enableRemoteWriteReceiver / switch to Mimir |
/federate context deadline exceeded | Full federation | match only job: recording rules |
| Same alert received 2–3 times | AM not clustered / replica label not removed | alertmanager_cluster_members,alert_relabel_configs |
| Grafana curve jumps | Service round-robins across two replicas | Thanos Query dedup or Mimir |
no org id (401) | Missing X-Scope-OrgID | remote_write headers / data source httpHeaderName1 |
err-mimir-max-series-per-user (400) | Tenant series limit exceeded, data dropped | Reduce cardinality or adjust overrides |
| 429 ingestion rate | Sample rate limit exceeded | ingestion_rate / ingestion_burst_size |
| compactor halted / overlapping blocks | Multiple compactors or local compaction not disabled | thanos tools bucket verify |
| SLO recording rule is empty | Empty vector when the numerator has no 5xx | or vector(0) |
| OTLP 404 | not enabled --web.enable-otlp-receiver or path duplicated | endpoint uses the base address |
field rule_files is not allowed in agent mode | Agent config includes rules | move the rules to the central ruler |
| Grafana 403 Access denied | folder permissions / team membership | GET /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
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.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'
cluster-lab; deploy Thanos Query and verify that the count differs by a factor of two before and after deduplication.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).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.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.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.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
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
| Topic | Verification result | Source (date) |
|---|---|---|
| Prometheus | v3.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-receiver | GitHub releases · command-line flags |
| Native histograms | stable since v3.8.0; scraping still requires scrape_native_histograms; since v3.9 the old feature flags are no-ops | Native Histograms spec |
| Remote-Write 2.0 | Spec status Experimental (2.0-rc); symbol table, metadata, exemplars, start timestamp; response header X-Prometheus-Remote-Write-*-Written | RW 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 functions | OpenTelemetry guide · Feature flags |
| Alertmanager | v0.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 |
| Thanos | v0.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 unique | releases · Quick tutorial |
| Grafana Mimir | 3.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"} growth | Tested by the lesson author |
| promtool tested | in 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 mode | Tested by the lesson author |
| OTel tested | otel/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-1 | Tested by the lesson author · Collector releases(v0.165.0, 2026-11-07) |
| kube-prometheus-stack | 93.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 |
| Grafana | 13.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 risk | releases · What's new in 13.0 |
| Grafana permissions | Basic roles Admin/Editor/Viewer/No basic role; folders are the main permission boundary; View/Edit/Admin; RBAC is Enterprise/Cloud; Cloud has no server admin | Roles and permissions |
| Grafana as code | Terraform provider v4.55.0 (2026-11-13); Grafana Operator v5.26.0 (2026-11-16) | provider releases · operator releases |
| SLO | Multi-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 |
| MinIO | The 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 MinIO | github.com/minio/minio |
| Capacity formula | Disk 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 thekubectl getactual 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_429default 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.