Prometheus & Grafana Hour 8: Logs and Traces — Loki, Tempo and OpenTelemetry

The first seven lessons used only the metrics pillar. This lesson adds the other two: store logs in Loki, store traces in Tempo, collect with OpenTelemetry and Grafana Alloy, and finish with an end-to-end troubleshooting flow in Grafana: alert → metric spike → exemplar → trace → logs for the same request
Loki v3.7.10Tempo v3.1.1Alloy v1.22.0OTel Collector v0.165.0Grafana v13.3.1Verified 2026-11-18
Where this lesson fits in the course Prerequisites:Lesson 1(metrics, PromQL, myapp instrumentation) → Lesson 2(alerting and dashboards) → Lesson 3 / Lesson 4(Azure and AWS managed services) → Lesson 5(kind + kube-prometheus-stack) → Lesson 6(architecture, SLOs, OTel and Prometheus) → Lesson 7(advanced troubleshooting). This is Lesson 8, reusing the kind cluster from Lessons 5–7 lab and the release kps. Next is Lesson 9 (optional): 50 production problems + 50 interview questions.
Overall learning goals
  • Explain metrics, logs and traces what each one answers (“is something broken, and how badly?” / “what happened?” / “which hop is slow?”), and which “keys” link the three: shared resource labels (service.name,namespace,pod),trace_id, exemplars, and time windows.
  • Explain Loki's design: index labels only, not full text; stream = a set of labels; chunks store log content and the TSDB index stores labels; the roles of distributor / ingester / querier / query-frontend / compactor; the three deployment modes Monolithic, Simple Scalable (deprecated) and Microservices; object storage.
  • Design labels correctly: use low-cardinality namespace,app,container as labels,trace_id,user_id put structured metadata or log content, never as labels; read maximum active stream limit exceeded and other real error messages.
  • Build collection pipelines with Grafana Alloy (Promtail reached end of life on 2026-03-02 EOL) and OpenTelemetry Collector (receivers → processors → exporters,k8sattributes,tail_sampling) and understand how the two divide the work.
  • Write LogQL: stream selectors, line filters (|= != |~), parsers (json / logfmt / pattern), label filters,rate / count_over_time / quantile_over_time … unwrap metric queries, and generating alerts from logs with the Loki ruler.
  • Understand the tracing model: trace / span / parent, the 4-part W3C traceparent format, context propagation, head and tail sampling; the new Tempo 3 write architecture (distributor → live-store / block-builder), TraceQL, and the RED metrics and service graph produced by metrics-generator.
  • Add OpenTelemetry to myapp (Flask): manual SDK initialization + Flask / Redis / requests auto-instrumentation, OTLP export, injecting trace_id into logs, and histograms with exemplars; deploy a second service myapp-edge to observe cross-service propagation.
  • Configure in Grafana exemplar → Tempo,trace → logs,Loki derived fields → Tempo, and the service graph, and master cost, retention and the four common failures (log loss, label cardinality, ingester / live-store OOM, broken traces).

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (kind cluster lab, namespaces observability + myapp)
0Before classPrep: deploy Loki, Tempo and the CollectorLoki (Monolithic + filesystem), Tempo (single binary + metrics-generator), OTel Collector, Alloy; kps enables exemplars and remote-write receiving; myapp:1.2 with OTelEnvironment self-check listOne request findable in all three backends
100–06The three pillars of observabilityThe questions each signal answers, cost, correlation keys, and the standard path from alert to root causeCore animation: one request produces metric + log + span, which pass through the Collector / Alloy into three backends; then in Grafana you jump from alert to trace to logsThe same slow request, described with each of the three signals
206–13Loki architecture and deploymentStreams and labels, chunks and TSDB index, write and read paths, deployment modes, object storage, structured metadata, cardinalityLabel cardinality → number of streams → chunk size calculatorObserve streams, chunks and limits; deliberately trigger a stream limit
313–21Log collection: Alloy and the OTel CollectorPromtail retirement and migration, Alloy component pipeline,loki.process, OTel Collector pipeline,k8sattributes, and how the two divide the workStep-by-step transformation of a log line in the collection pipelineModify the Alloy pipeline: logfmt parsing, trace_id into structured metadata
421–28LogQLstream selectors, line filters, parsers, label filters,line_format, metric queries,unwrap, ruler alertsLogQL pipeline step-through executorCompute the myapp 5xx ratio and P95 entirely from logs, and write one log-based alert
528–35Distributed tracing and Tempotrace/span,traceparent, sampling, the Tempo 3 architecture, TraceQL, metrics-generator RED and service graphCore animation: traceparent propagation across servicesFind slow spans with TraceQL; the service graph shows myapp-edge → myapp → redis
635–42OTel instrumentation and Collector pipelinesAutomatic vs manual instrumentation, SDK initialization and gunicorn fork, resource attributes, OTLP, tail sampling, Collector self-monitoringSampling decision simulator (head / tail)Add custom spans and attributes; enable tail_sampling and observe the bias
742–50Correlated troubleshootingexemplars (metric → trace), trace → logs, derived fields (logs → trace), trace → metrics, Explore and DrilldownCorrelated jump drill (click through one full troubleshooting run)Inject Redis latency and follow the alert all the way to the root-cause log
850–60Cost, retention, troubleshooting and self-testRetention policy, capacity and cost estimation, log loss, label cardinality, OOM, broken tracesCost estimator + interactive troubleshooting treeFour fault injections and fixes
—After classCheat sheet · Comprehensive labDeliver a “three pillars + correlation” observability plan for shop or myappFinal quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / configurationLab
The three pillars and the correlation model✓···✓·✓✓trace_id, resource attributesM1, M7
Loki architecture and storage·✓·····✓schema_config,limits_configM2
Label and cardinality design·✓✓✓·✓·✓logcli series --analyze-labelsM2, M8
Collection pipelines (Alloy / Collector)✓·✓··✓·✓loki.process,k8sattributesM3, M6
LogQL and log alerting···✓··✓✓logcli query, rulerM4
Tracing model and Tempo✓···✓✓✓✓TraceQL,/api/searchM5
OTel instrumentation and sampling····✓✓·✓OTEL_* environment variables,tail_samplingM6
Grafana correlation and Explore✓·····✓✓exemplarTraceIdDestinations,tracesToLogsV2,derivedFieldsM7
Cost, retention and troubleshooting·✓··✓··✓retention_period,tempo.retentionM8

What this lesson does not cover (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Prometheus scraping, PromQL, myapp's /metrics instrumentationFoundations of the metrics pillarLesson 1 Module 3
OTLP metric ingestion into Prometheus, name conversion,target_infoalready covered in Lesson 6; this lesson covers only logs and tracesLesson 6 Module 6
Azure Monitor's Container Insights, Log Analytics and KQLManaged logging serviceLesson 3 Module 6
AWS Distro for OpenTelemetry (ADOT), CloudWatch Logs, X-RayManaged collection and tracingLesson 4 Module 3,Module 6
Metric cardinality, TSDB internalsSame cardinality thinking as Loki; details in Lesson 7Lesson 7 Module 3
Profiling (Pyroscope), frontend RUM (Faro), eBPF zero-code instrumentation (Beyla / OBI)“The fourth pillar”; mentioned only in passing in the concepts due to lengthgrafana.com/docs for the corresponding product documentation
50 production problems, 50 interview questionsLesson 9 (optional)Lesson 9

How to use these course materials

10 pages per module
Concepts · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · narration · videos. Labs run on a kind cluster lab : kps is in monitoring, Loki / Tempo / Collector / Alloy are in new namespaces observability, myapp and myapp-edge are in myapp. All files are stored in ~/promlab/part8.
Learning progress
A quiz score of ≥ 70% or clicking “Mark this module complete” counts toward progress, stored in this browser (cleared on refresh when local storage is disabled).
Chinese narration
The “Narration” page reads the script aloud with the browser Web Speech API (en-US); English terms are pronounced with en-US. If no Chinese voice pack is installed, the script can still be read.
Version notes Versions verified on 2026-11-18 via GitHub Releases and the official Helm repository index: Loki v3.7.10 (2026-11-13; v4.0.0 is an RC, rc.3 released 2026-11-07, not used in this lesson); the Loki chart has moved to grafana-community/loki 21.4.0; Tempo v3.1.1 (2026-10-21; 3.0 released 2026-05-28, replacing ingesters with live-store / block-builder), chart grafana-community/tempo 3.2.1; Grafana Alloy v1.22.0 (chart grafana/alloy 1.16.0); OpenTelemetry Collector v0.165.0 (2026-11-07; chart open-telemetry/opentelemetry-collector 0.179.1 defaults appVersion to 0.163.2; this lesson pins the image tag to 0.165.0); OTel Python SDK 1.45.2 / contrib 0.66b2; Prometheus v3.16.0, kube-prometheus-stack 93.3.0 and Grafana 13.3.1 carried over from the Lesson 7 baseline. Trace IDs, Pod name suffixes, times and counts in sample output are example values.

Module 0 · Prep: deploy Loki, Tempo and the Collector on a kind cluster

On the kind cluster lab from Lessons 5–7 and kube-prometheus-stack (release kps), add the observability namespace: Loki (logs), Tempo (traces), OpenTelemetry Collector (trace pipeline), Grafana Alloy (log collection), then upgrade myapp to version 1.2 with OpenTelemetry
Before class ≈ 20 minuteskind · kps 93.3.0Local lab, zero cost
Prerequisites
  • Completed Lesson 5 Module 0: kind cluster lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring is deployed; myapp (myapp:1.1, Service myapp, port name http, label app.kubernetes.io/name: myapp) and Redis run in namespace myapp, ServiceMonitor with release: kps.
  • If you do not have the previous lesson's results: rebuild them with Lesson 5 Module 0 “Steps 1–4” (about 10 minutes); the Lesson 7 faultlab is unrelated to this lesson and can be deleted.
  • On your machine: Docker, kind, kubectl, helm (Lesson 5 uses Helm 4), jq, curl. Give Docker / kind at least 6 CPU / 8 GiB memory: the new components in this lesson request about 1 CPU / 1.5 GiB in total.
  • Optional: Loki command line logcli (same version as Loki, downloaded from Loki's GitHub Release); Tempo's tempo-cli is not required; this lesson uses the HTTP API directly.
Target topology for this lesson
  • Metrics: myapp /metrics (with exemplars) → kps Prometheus (with exemplar-storage); Tempo metrics-generator's span metrics / service graph → remote write → the same Prometheus.
  • Logs: container stdout → Alloy (loki.source.kubernetes → loki.process) → Loki.
  • Traces: myapp / myapp-edge (OTel SDK) → OTLP gRPC → OTel Collector (k8sattributes etc.) → Tempo.
  • Presentation: kps's Grafana adds Loki and Tempo data sources and configures three-way correlation.

Step 1: check the cluster, kps and myapp

kubectl config use-context kind-lab
helm -n monitoring list
kubectl -n monitoring get prometheus -o custom-columns=NAME:.metadata.name,VERSION:.spec.version
kubectl -n myapp get deploy,svc,servicemonitor
Switched to context "kind-lab".
NAME  NAMESPACE   REVISION  UPDATED  STATUS    CHART                          APP VERSION
kps   monitoring  5         ...      deployed  kube-prometheus-stack-93.3.0   v0.95.2
NAME                                    VERSION
kps-kube-prometheus-stack-prometheus    v3.16.0
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/myapp   2/2     2            2           3d
deployment.apps/redis   1/1     1            1           3d
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
service/myapp   ClusterIP   10.96.41.12    <none>        5000/TCP   3d
service/redis   ClusterIP   10.96.88.3     <none>        6379/TCP   3d
NAME                                         AGE
servicemonitor.monitoring.coreos.com/myapp   3d

Step 2: directories, variables and Helm repositories

mkdir -p ~/promlab/part8 && cd ~/promlab/part8
cat > env.sh <<'EOF'
export NS=monitoring ONS=observability ANS=myapp
export P=http://localhost:9090 G=http://localhost:3000 L=http://localhost:3100 T=http://localhost:3200
export GPW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
pq() { curl -s --data-urlencode "query=$1" "$P/api/v1/query" | jq -c '.data.result[] | [.metric, .value[1]]'; }
# LogQL instant queries (log queries return entries, metric queries return vectors)
lq() { curl -s -G "$L/loki/api/v1/query_range" --data-urlencode "query=$1" --data-urlencode "since=${2:-15m}" --data-urlencode limit=20 | jq -c '.data.result[] | (.stream // .metric), (.values[-1])'; }
EOF
source env.sh
kubectl create namespace observability
helm repo add grafana-community https://grafana-community.github.io/helm-charts
helm repo add grafana https://grafana.github.io/helm-charts
helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts
helm repo update
helm search repo -l grafana-community/loki | head -2; helm search repo grafana/alloy; helm search repo grafana-community/tempo | head -2
namespace/observability created
"grafana-community" has been added to your repositories
...
NAME                    CHART VERSION  APP VERSION  DESCRIPTION
grafana-community/loki  21.4.0         3.7.10       Helm chart for Grafana Loki and Grafana Enterprise Logs ...
grafana/alloy           1.16.0         v1.22.0      Grafana Alloy
grafana-community/tempo 3.2.1          3.1.1        Grafana Tempo Single Binary Mode
Note on the chart location The Loki and Tempo Helm charts are now maintained by the community at grafana-community/helm-charts (the official Loki installation docs use helm repo add grafana-community https://grafana-community.github.io/helm-charts). The old grafana/loki chart still appears in the index (7.x, appVersion 3.6.x); do not mix them. Alloy is still at grafana/alloy.

Step 3: install Loki (Monolithic mode, local filesystem storage)

deploymentMode: Monolithic
loki:
  auth_enabled: false            # single-tenant lab; tenant ID fixed to "fake"
  commonConfig:
    replication_factor: 1        # must match the number of replicas
  storage:
    type: filesystem             # only 1 replica allowed; for production use S3 / GCS / Azure Blob
  schemaConfig:
    configs:
      - from: "2024-04-01"
        store: tsdb
        object_store: filesystem
        schema: v13
        index:
          prefix: loki_index_
          period: 24h
  limits_config:
    allow_structured_metadata: true
    volume_enabled: true
    retention_period: 168h       # 7 days; takes effect only if the compactor has retention enabled
    max_global_streams_per_user: 5000
  compactor:
    retention_enabled: true
    delete_request_store: filesystem
  pattern_ingester:
    enabled: true
  rulerConfig:
    storage: {type: local, local: {directory: /rules}}
    rule_path: /tmp/loki-rules-scratch
    alertmanager_url: http://alertmanager-operated.monitoring.svc:9093
    enable_api: true
singleBinary:
  replicas: 1
  persistence: {enabled: true, size: 10Gi}
  resources: {requests: {cpu: 200m, memory: 512Mi}, limits: {memory: 1Gi}}
# disable components of other deployment modes (chart defaults read/write/backend to 3 replicas each)
read: {replicas: 0}
write: {replicas: 0}
backend: {replicas: 0}
gateway: {enabled: false}        # the lab connects directly to loki:3100; enable the nginx gateway only for multi-tenant / auth scenarios
chunksCache: {enabled: false}    # a memcached cache can consume several GiB of memory on a small cluster
resultsCache: {enabled: false}
lokiCanary: {enabled: false}
test: {enabled: false}
helm upgrade --install loki grafana-community/loki --version 21.4.0 -n observability -f loki-values.yaml
kubectl -n observability rollout status statefulset/loki --timeout=300s
kubectl -n observability port-forward svc/loki 3100:3100 >/dev/null 2>&1 &
sleep 2; curl -s $L/ready; curl -s $L/loki/api/v1/status/buildinfo | jq -c '{version,revision}'
Release "loki" does not exist. Installing it now.
NAME: loki
STATUS: deployed
partitioned roll out complete: 1 new pods have been updated...
ready
{"version":"3.7.10","revision":"…"}

The chart's validation templates reject two misconfigurations: filesystem storage with more than one Monolithic replica (Cannot run more than 1 Monolithic replica without an object storage backend.), and not providing schemaConfig (You must provide a schema_config for Loki …). During the first few dozen seconds after a Pod starts, /ready it may return Ingester not ready: waiting for 15s after being ready, which is normal.

Step 4: install Tempo (single-binary mode + metrics-generator)

tempo:
  retention: 48h                 # rendered as block_retention for backend_worker / backend_scheduler
  reportingEnabled: false
  metricsGenerator:
    enabled: true
    # writes back to kps's Prometheus (requires enabling remote-write receiving, see Step 5)
    remoteWriteUrl: http://prometheus-operated.monitoring.svc:9090/api/v1/write
  overrides:
    defaults:
      metrics_generator:
        processors: [service-graphs, span-metrics]
  # receivers keep the chart defaults: OTLP gRPC 4317 / HTTP 4318 (also includes a Jaeger receiver, not used in this lesson)
  resources: {requests: {cpu: 200m, memory: 512Mi}, limits: {memory: 1Gi}}
persistence:
  enabled: true
  size: 10Gi
helm upgrade --install tempo grafana-community/tempo --version 3.2.1 -n observability -f tempo-values.yaml
kubectl -n observability rollout status statefulset/tempo --timeout=300s
kubectl -n observability port-forward svc/tempo 3200:3200 >/dev/null 2>&1 &
sleep 2; curl -s $T/ready; curl -s $T/api/status/buildinfo | jq -c '{version}'
ready
{"version":"3.1.1"}

Single-binary mode (-target=all) does not need Kafka: the distributor hands data in-process to live-store and metrics-generator; production microservice mode needs a Kafka-compatible queue (Module 5). The chart values keys follow 3.2.1; if a field is rejected, compare with helm show values grafana-community/tempo --version 3.2.1 for reference.

Step 5: upgrade kps — exemplar storage, remote write receiving, new data sources

Append only the values this lesson needs; keep the rest of your Lesson 5 values file (shown below as --reuse-values ; when managed with GitOps, merge these values into the values file in your repository).

prometheus:
  prometheusSpec:
    enableFeatures: [exemplar-storage]   # exemplar storage is still a feature flag in 3.16
    enableRemoteWriteReceiver: true      # receive remote writes from Tempo metrics-generator
grafana:
  sidecar:
    datasources:
      exemplarTraceIdDestinations:       # Prometheus data source provisioned by kps: exemplar trace_id → Tempo
        datasourceUid: tempo
        traceIdLabelName: trace_id
        urlDisplayLabel: View in Tempo
  additionalDataSources:
    - name: Loki
      uid: loki
      type: loki
      access: proxy
      url: http://loki.observability.svc:3100
      jsonData:
        maxLines: 1000
        derivedFields:                   # logs → trace
          - name: TraceID
            matcherType: label           # take the value from structured metadata / the trace_id label
            matcherRegex: trace_id
            datasourceUid: tempo
            url: '$${__value.raw}'
            urlDisplayLabel: View trace
    - name: Tempo
      uid: tempo
      type: tempo
      access: proxy
      url: http://tempo.observability.svc:3200
      jsonData:
        tracesToLogsV2:                  # trace → logs
          datasourceUid: loki
          spanStartTimeShift: "-2m"
          spanEndTimeShift: "2m"
          filterByTraceID: true
          tags: [{key: k8s.namespace.name, value: namespace}]
        tracesToMetrics:                 # trace → metrics
          datasourceUid: prometheus
          tags: [{key: service.name, value: service}]
          queries:
            - name: Request rate
              query: 'sum(rate(traces_spanmetrics_calls_total{$$__tags}[5m]))'
        serviceMap: {datasourceUid: prometheus}
        nodeGraph: {enabled: true}
helm upgrade kps prometheus-community/kube-prometheus-stack --version 93.3.0 -n monitoring \
  --reuse-values -f kps-obs-values.yaml
kubectl -n monitoring rollout status statefulset/prometheus-kps-kube-prometheus-stack-prometheus
kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus -o jsonpath='{.spec.enableFeatures}{" "}{.spec.enableRemoteWriteReceiver}{"\n"}'
Release "kps" has been upgraded. Happy Helming!
statefulset rolling update complete 1 pods at revision prometheus-kps-kube-prometheus-stack-prometheus-6c7d...
["exemplar-storage"] true

$$ is how Grafana provisioning files escape $ (the official Loki data source docs write the same example as '$${__value.raw}'). matcherType: label This corresponds to the “Label” type of derived field in the UI (it can match indexed labels, parsed labels or structured metadata); if your Grafana version does not recognize this key, switch to the default regex type matcherRegex: 'trace_id=(\w+)' (see Module 7).

Step 6: install the OpenTelemetry Collector (trace pipeline)

mode: deployment
replicaCount: 1
image:
  repository: otel/opentelemetry-collector-contrib
  tag: "0.165.0"                 # pinned to the 2026-11-07 release; the chart default appVersion is 0.163.2
presets:
  kubernetesAttributes:
    enabled: true                # automatically adds the k8sattributes processor and the required RBAC
resources: {requests: {cpu: 100m, memory: 256Mi}, limits: {memory: 512Mi}}
config:
  receivers:
    otlp:
      protocols:
        grpc: {endpoint: "${env:MY_POD_IP}:4317"}
        http: {endpoint: "${env:MY_POD_IP}:4318"}
  processors:
    memory_limiter: {check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 25}
    batch: {}
    resource/cluster:
      attributes:
        - {key: k8s.cluster.name, value: lab, action: upsert}
  exporters:
    otlp_grpc/tempo:             # since v0.144 otlp is renamed otlp_grpc (the old name otlp is a deprecated alias)
      endpoint: tempo.observability.svc:4317
      tls: {insecure: true}
    otlp_http/loki:              # old name otlphttp; Loki's native OTLP endpoint is /otlp
      endpoint: http://loki.observability.svc:3100/otlp
  service:
    telemetry:                   # self-monitoring metrics: the chart listens only on Pod IP by default; change to 0.0.0.0 for port-forward
      metrics:
        readers:
          - pull: {exporter: {prometheus: {host: "0.0.0.0", port: 8888}}}
    pipelines:
      traces:
        receivers: [otlp]
        processors: [memory_limiter, k8sattributes, resource/cluster, batch]
        exporters: [otlp_grpc/tempo]
      logs:
        receivers: [otlp]
        processors: [memory_limiter, k8sattributes, resource/cluster, batch]
        exporters: [otlp_http/loki]
helm upgrade --install otelcol open-telemetry/opentelemetry-collector --version 0.179.1 -n observability -f otelcol-values.yaml
kubectl -n observability rollout status deploy/otelcol-opentelemetry-collector
kubectl -n observability logs deploy/otelcol-opentelemetry-collector | grep -E 'Everything is ready|error' | tail -3
deployment "otelcol-opentelemetry-collector" successfully rolled out
... info    service@v0.165.0/service.go:...   Everything is ready. Begin running and processing data.

The Service name is otelcol-opentelemetry-collector (release name + chart name). The chart merges what we write with config its own defaults (these include debug exporters, metrics pipelines, etc.); use kubectl -n observability get cm otelcol-opentelemetry-collector -o yaml to view the final configuration.

Step 7: install Grafana Alloy (log collection)

controller:
  type: deployment               # reads logs via the Kubernetes API; no DaemonSet / hostPath needed
  replicas: 1
alloy:
  resources: {requests: {cpu: 100m, memory: 128Mi}, limits: {memory: 512Mi}}
  configMap:
    content: |-
      // 1) discover Pods in the myapp namespace
      discovery.kubernetes "pods" {
        role = "pod"
        namespaces { names = ["myapp"] }
      }
      // 2) keep only low-cardinality labels
      discovery.relabel "pods" {
        targets = discovery.kubernetes.pods.targets
        rule {
          source_labels = ["__meta_kubernetes_namespace"]
          target_label  = "namespace"
        }
        rule {
          source_labels = ["__meta_kubernetes_pod_label_app_kubernetes_io_name"]
          target_label  = "app"
        }
        rule {
          source_labels = ["__meta_kubernetes_pod_container_name"]
          target_label  = "container"
        }
      }
      // 3) follow container stdout/stderr via the Kubernetes API
      loki.source.kubernetes "pods" {
        targets    = discovery.relabel.pods.output
        forward_to = [loki.process.myapp.receiver]
      }
      // 4) parse logfmt; trace_id goes into structured metadata (not a label!)
      loki.process "myapp" {
        stage.logfmt {
          mapping = { "level" = "", "trace_id" = "", "service" = "" }
        }
        stage.structured_metadata {
          values = { "trace_id" = "" }
        }
        stage.labels {
          values = { "service_name" = "service" }
        }
        forward_to = [loki.write.default.receiver]
      }
      // 5) push to Loki
      loki.write "default" {
        endpoint {
          url = "http://loki.observability.svc:3100/loki/api/v1/push"
        }
      }
helm upgrade --install alloy grafana/alloy --version 1.16.0 -n observability -f alloy-values.yaml
kubectl -n observability rollout status deploy/alloy
kubectl -n observability port-forward deploy/alloy 12345:12345 >/dev/null 2>&1 &
curl -s localhost:12345/-/ready
deployment "alloy" successfully rolled out
Alloy is ready.

Alloy has a built-in debug UI (http://localhost:12345): you can see the component graph, the health of each component, and Live debugging. The chart's default ClusterRole already includes pods,pods/log read permissions for them,loki.source.kubernetes which the UI depends on.

Step 8: myapp:1.2 — add OpenTelemetry, trace_id logs and exemplars

On top of the Lesson 1 myapp, add four things: ① OTel SDK initialization and Flask / Redis / requests auto-instrumentation; ② one logfmt log line per request, carrying trace_id; ③ a request-latency histogram with exemplars; ④ a new route /checkout: calls the upstream service when UPSTREAM_URL is set, to demonstrate cross-service propagation. The same image is deployed twice: myapp and myapp-edge.

import os, time, random, logging
from flask import Flask, Response, request, g
import redis, requests
from prometheus_client import Counter, Histogram, Gauge, REGISTRY
from prometheus_client.exposition import choose_encoder
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.redis import RedisInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.instrumentation.logging import LoggingInstrumentor

# ---- OpenTelemetry: resource, sampler and export endpoint are all read from OTEL_* environment variables ----
provider = TracerProvider(resource=Resource.create())
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("myapp")
LoggingInstrumentor().instrument()          # inject otelTraceID / otelSpanID / otelServiceName into LogRecord
logging.basicConfig(level=logging.INFO, datefmt="%Y-%m-%dT%H:%M:%S",
    format="ts=%(asctime)s level=%(levelname)s service=%(otelServiceName)s "
           "trace_id=%(otelTraceID)s span_id=%(otelSpanID)s %(message)s")
log = logging.getLogger("myapp")

app = Flask(__name__)
FlaskInstrumentor().instrument_app(app)     # one SERVER span per request, parses inbound traceparent
RedisInstrumentor().instrument()            # one CLIENT span per Redis command
RequestsInstrumentor().instrument()         # outbound HTTP: CLIENT span + injects traceparent

r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=0.5)
UPSTREAM = os.getenv("UPSTREAM_URL", "")
REQS = Counter("myapp_http_requests_total", "HTTP requests", ["method", "route", "status"])
LAT = Histogram("myapp_http_request_duration_seconds", "Request latency", ["route"],
                buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))
REDIS_UP = Gauge("myapp_redis_up", "1 if Redis is reachable")

@app.before_request
def _start():
    g.t0 = time.perf_counter()

@app.after_request
def _record(resp):
    route = request.url_rule.rule if request.url_rule else "unmatched"
    if route in ("/metrics", "/healthz"):
        return resp
    dt = time.perf_counter() - g.t0
    ctx = trace.get_current_span().get_span_context()
    ex = {"trace_id": format(ctx.trace_id, "032x")} if ctx.is_valid and ctx.trace_flags.sampled else None
    REQS.labels(request.method, route, str(resp.status_code)).inc()
    LAT.labels(route).observe(dt, exemplar=ex)  # exemplars are emitted only in OpenMetrics format
    lvl = logging.ERROR if resp.status_code >= 500 else logging.INFO
    log.log(lvl, "msg=request method=%s route=%s status=%d duration_ms=%.1f",
            request.method, route, resp.status_code, dt * 1000)
    return resp

@app.get("/")
def index():
    n = r.incr("hits")
    return f"Hello from myapp! hits={n}\n"

@app.get("/checkout")
def checkout():
    with tracer.start_as_current_span("price.calculate") as span:   # manual span
        items = random.randint(1, 5)
        span.set_attribute("app.cart.items", items)
        time.sleep(0.01 * items)
    if UPSTREAM:
        up = requests.get(UPSTREAM + "/", timeout=2)
        if up.status_code >= 500:
            return "upstream error\n", 502
    return f"checkout ok items={items}\n"

@app.get("/healthz")
def healthz():
    return "ok\n"

@app.get("/error")
def error():
    log.error("msg=\"payment provider timeout\" provider=demo")
    return "boom\n", 500

@app.get("/metrics")
def metrics():
    try:
        r.ping(); REDIS_UP.set(1)
    except Exception:
        REDIS_UP.set(0)
    encoder, content_type = choose_encoder(request.headers.get("Accept"))
    return Response(encoder(REGISTRY), content_type=content_type)
FROM python:3.13-slim
WORKDIR /app
RUN pip install --no-cache-dir flask gunicorn redis requests prometheus_client \
      opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-grpc==1.45.2 \
      opentelemetry-instrumentation-flask==0.66b2 opentelemetry-instrumentation-redis==0.66b2 \
      opentelemetry-instrumentation-requests==0.66b2 opentelemetry-instrumentation-logging==0.66b2
COPY app.py .
RUN useradd -r -u 10001 app
USER 10001
EXPOSE 5000
# single process, multi-threaded: prometheus_client multiprocess mode does not support exemplars (see Module 7)
CMD ["gunicorn", "-w", "1", "--threads", "8", "-b", "0.0.0.0:5000", "app:app"]
apiVersion: apps/v1
kind: Deployment
metadata: {name: myapp, namespace: myapp}
spec:
  replicas: 2
  selector: {matchLabels: {app.kubernetes.io/name: myapp}}
  template:
    metadata: {labels: {app.kubernetes.io/name: myapp}}
    spec:
      containers:
        - name: myapp
          image: myapp:1.2
          imagePullPolicy: IfNotPresent
          ports: [{name: http, containerPort: 5000}]
          env:
            - {name: REDIS_HOST, value: redis}
            - {name: OTEL_SERVICE_NAME, value: myapp}
            - {name: OTEL_EXPORTER_OTLP_ENDPOINT, value: "http://otelcol-opentelemetry-collector.observability.svc:4317"}
            - {name: OTEL_EXPORTER_OTLP_PROTOCOL, value: grpc}
            - {name: OTEL_TRACES_SAMPLER, value: parentbased_always_on}
            - {name: OTEL_PYTHON_FLASK_EXCLUDED_URLS, value: "healthz,metrics"}
            - {name: K8S_POD_IP, valueFrom: {fieldRef: {fieldPath: status.podIP}}}
            - {name: OTEL_RESOURCE_ATTRIBUTES, value: "service.namespace=shop-demo,deployment.environment.name=lab,k8s.pod.ip=$(K8S_POD_IP)"}
          readinessProbe: {httpGet: {path: /healthz, port: http}}
          resources: {requests: {cpu: 50m, memory: 96Mi}, limits: {memory: 256Mi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: myapp-edge, namespace: myapp}
spec:
  replicas: 1
  selector: {matchLabels: {app.kubernetes.io/name: myapp-edge}}
  template:
    metadata: {labels: {app.kubernetes.io/name: myapp-edge}}
    spec:
      containers:
        - name: myapp
          image: myapp:1.2
          imagePullPolicy: IfNotPresent
          ports: [{name: http, containerPort: 5000}]
          env:
            - {name: REDIS_HOST, value: redis}
            - {name: UPSTREAM_URL, value: "http://myapp.myapp.svc:5000"}
            - {name: OTEL_SERVICE_NAME, value: myapp-edge}
            - {name: OTEL_EXPORTER_OTLP_ENDPOINT, value: "http://otelcol-opentelemetry-collector.observability.svc:4317"}
            - {name: OTEL_EXPORTER_OTLP_PROTOCOL, value: grpc}
            - {name: OTEL_TRACES_SAMPLER, value: parentbased_always_on}
            - {name: OTEL_PYTHON_FLASK_EXCLUDED_URLS, value: "healthz,metrics"}
            - {name: K8S_POD_IP, valueFrom: {fieldRef: {fieldPath: status.podIP}}}
            - {name: OTEL_RESOURCE_ATTRIBUTES, value: "service.namespace=shop-demo,deployment.environment.name=lab,k8s.pod.ip=$(K8S_POD_IP)"}
          readinessProbe: {httpGet: {path: /healthz, port: http}}
          resources: {requests: {cpu: 50m, memory: 96Mi}, limits: {memory: 256Mi}}
---
apiVersion: v1
kind: Service
metadata: {name: myapp-edge, namespace: myapp, labels: {app.kubernetes.io/name: myapp-edge}}
spec:
  selector: {app.kubernetes.io/name: myapp-edge}
  ports: [{name: http, port: 5000, targetPort: http}]
cd ~/promlab/part8/myapp && docker build -t myapp:1.2 . && kind load docker-image myapp:1.2 --name lab
cd ~/promlab/part8 && kubectl apply -f myapp-otel.yaml
kubectl -n myapp rollout status deploy/myapp && kubectl -n myapp rollout status deploy/myapp-edge
# keep traffic flowing: normal, cross-service and error requests
kubectl -n myapp run loadgen --image=curlimages/curl:8.11.1 --restart=Never --command -- sh -c \
  'while true; do curl -s -o /dev/null myapp-edge:5000/checkout; curl -s -o /dev/null myapp:5000/;
   [ $((RANDOM % 20)) -eq 0 ] && curl -s -o /dev/null myapp:5000/error; sleep 0.5; done'
deployment.apps/myapp configured
deployment.apps/myapp-edge created
service/myapp-edge created
deployment "myapp" successfully rolled out
deployment "myapp-edge" successfully rolled out
pod/loadgen created

The new Deployment manifest no longer contains the PROMETHEUS_MULTIPROC_DIR and emptyDir volume from Lesson 5: the client kubectl apply removes fields that exist in last-applied but are missing from the new manifest. OTEL_RESOURCE_ATTRIBUTES in the k8s.pod.ip helps k8sattributes associate spans with Pods (Module 3). The two Deployments differ only in the environment variables OTEL_SERVICE_NAME and UPSTREAM_URL . curlimages/curl's shell is busybox ash, which supports $RANDOM.

Step 9: verify the three pipelines (about 2 minutes later)

source ~/promlab/part8/env.sh
kubectl -n monitoring port-forward svc/prometheus-operated 9090:9090 >/dev/null 2>&1 &
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 >/dev/null 2>&1 &
# logs: which labels and streams Loki has
curl -s $L/loki/api/v1/labels | jq -c .data
lq '{namespace="myapp", app="myapp"} |= "status=500"' 5m | head -4
# traces: recent traces in Tempo
curl -s -G $T/api/search --data-urlencode 'q={resource.service.name="myapp-edge"}' --data-urlencode limit=3 | jq -c '.traces[] | {traceID, rootServiceName, rootTraceName, durationMs}'
# metrics: exemplars and span metrics
curl -s -G $P/api/v1/query_exemplars --data-urlencode 'query=myapp_http_request_duration_seconds_bucket' --data-urlencode "start=$(date -d '-5 min' +%s)" --data-urlencode "end=$(date +%s)" | jq '[.data[].exemplars[]] | length'
pq 'sum by (service) (rate(traces_spanmetrics_calls_total[5m]))'
["app","container","namespace","service_name"]
{"app":"myapp","container":"myapp","namespace":"myapp","service_name":"myapp"}
["1763460123456789012","ts=2026-11-18T10:02:03 level=ERROR service=myapp trace_id=4bf92f3577b34da6a3ce929d0e0e4736 span_id=00f067aa0ba902b7 msg=request method=GET route=/error status=500 duration_ms=1.2"]
{"traceID":"6e0c63257de34c92bf9efcd03927272e","rootServiceName":"myapp-edge","rootTraceName":"GET /checkout","durationMs":41}
...
137
[{"service":"myapp"},"5.83"]
[{"service":"myapp-edge"},"1.97"]

date -d is GNU date syntax; on macOS use date -v-5M +%s. The service_name labels Loki returns come from Alloy's stage.labels; if a stream lacks that label, Loki infers it from the discover_service_name list automatically (when it cannot infer, the value is unknown_service).

Warm-up: answer from memory (30 seconds)

What do Prometheus “series” and Loki “streams” have in common?

Both are uniquely identified by a “name + set of labels”, and both blow up with high-cardinality labels. The difference is that Prometheus series store numeric samples, while Loki streams store log lines (compressed into chunks). So the label design taught in Lesson 7 applies almost unchanged to Loki; the cost simply shows up as more small chunks and a larger index.

Should trace_id be a Loki label?

No. Each request has a new value, so every log line becomes its own stream — the most typical Loki cardinality incident. Put it in structured metadata (not indexed, but filterable), or leave it in the log line and extract it with a parser.

Environment self-check list

Module 1 · The three pillars of observability: when to use metrics, logs and traces

00:00 – 06:00 · Metrics tell you “is something broken and how badly”, traces tell you “which hop is slow”, and logs tell you “what exactly happened at that moment”. The real value lies not in the three pillars themselves but in the “keys” that connect them
6 minmetrics · logs · traces★★★★★
Learning objectives
  • For each signal, state: the data shape, the question it answers, typical storage (Prometheus / Loki / Tempo), what drives cost, and the order of magnitude of retention.
  • Name the correlation “keys” between the three signals: resource attributes (service.name,k8s.namespace.name,k8s.pod.name),trace_id / span_id, exemplars, and time windows.
  • Troubleshoot along the standard path: alert (metrics) → find a representative request (exemplar / TraceQL) → locate the slow hop (trace) → read the details at that moment (logs).
Prerequisites: Lesson 1 metric types and the RED method; Lesson 6 Module 6 OTel basics. Importance:★★★★★

What: the shape of each signal

MetricsLogsTraces
Data shape(name + labels) → numeric time series; pre-aggregatedtimestamped text / structured events, one event per linea span tree: each span has a start time, duration, attributes, status and parent span
Question it answersIs something broken? How badly? Trend? (alerting, SLOs)What exactly happened at that moment? Error text, parameters, business contextWhich services did a request pass through? Where did the time go? Which hop did the error start at?
Backend in this lessonPrometheus (Lessons 1–7)Loki v3.7.10Tempo v3.1.1
Query languagePromQLLogQLTraceQL
What cost mainly scales withNumber of active series (label cardinality)Log bytes (volume) + number of streams (label cardinality)Number of spans × retention; sampling rate decides almost everything
Typical retention15 days – 13 months (long-term storage downsampled)7–30 days (compliance may require more)2–14 days (for troubleshooting only, usually sampled)
Main blind spotCannot see individual requests; high-cardinality dimensions do not fitHard to stitch across services; high volume and expensive; formats vary wildlyRequests dropped by sampling are invisible; no aggregated trends (derived metrics needed)

Why: why you need all three

With metrics alone you know “P99 rose from 200ms to 2s”, but not which requests or which downstream is slow; with logs alone you stitch one request together by hand across timestamps in five services; with traces alone you see a waterfall of one slow request but cannot tell whether it is “occasional” or “5% of requests do this”. The three are good at respectively detection (metrics),localization (traces), and explanation (logs). Lesson 7's cardinality section already warned: user_id,request_id such high-cardinality dimensions should not trace_id go into metrics — they belong in trace attributes and log content, and can be retrieved through

How: the four correlation keys

  1. Resource attributes (the same “who”): OpenTelemetry's service.name,k8s.namespace.name, and k8s.pod.name; in Prometheus these correspond to job/namespace/pod labels, and in Loki to stream labels (this lesson's namespace,app, and service_name). The naming differs slightly across the three, so the Grafana correlation config needs a mapping (Module 7).
  2. trace_id (the same “request”): log lines carry trace_id (injected by this lesson's OTel logging instrumentation); traces are keyed by trace_id.
  3. exemplar (a “sample request” in a metric): a bucket of a histogram carries an trace_id, shown in Grafana graphs as a small diamond; clicking it jumps to Tempo.
  4. Time window (the same “moment”): the fallback when there is no ID: logs and metrics for the same service and time range.

When: which signal to use first for which question

QuestionUse firstThen use
“Is something broken now? How big is the impact?”Metrics (RED, SLO burn rate, Lesson 6)—
“Which downstream is making requests slow?”Traces (TraceQL to find slow traces, service graph)Metrics (span metrics to confirm whether it is widespread)
“What is the exact error text of this 500?”Logs (LogQL filter status=500)Traces (jump from the log's trace_id to see the context)
“Why did an order a customer complained about fail?”Logs (search by order number / user in log content)Traces
“Is capacity enough, do we need to scale?”Metrics—
Common misconceptions① “With traces you don’t need logs” — span events can record a little detail, but stack traces, business fields and third-party library output remain in logs, and requests dropped by sampling are only visible in logs. ② “Write everything as logs and compute metrics from them” — it can supplement (Module 4), but it is costly and slow; alerts and SLOs should still be based on native metrics. ③ “Three pillars = buy three products” — the key is consistent resource attributes and trace_id propagation; otherwise the three systems are just three islands. ④ “OpenTelemetry is a backend” — OTel only produces and transports (SDK, Collector, OTLP); storage and querying are still done by Prometheus / Loki / Tempo (Lesson 6 Module 6).

The three signals one request produces, and where they go

myapp-edge→ myapp → redisOTel SDK metrics /metricshistogram + exemplar logs stdoutlogfmt + trace_id span (OTLP push)traceparent propagation Prometheus scrapepull · OpenMetrics Grafana Alloyloki.source.kubernetes OTel Collectork8sattributes · batch PrometheusTSDB + exemplars Lokiindexed labels · chunks store content Tempostored by trace_id Grafanaexemplar →trace → logslogs → trace metrics-generatorRED · service graph remote write
Figure 1-1: metrics are “pulled”, logs and traces are “pushed”; Tempo's metrics-generator turns traces back into metrics (dashed line)

Correlation keys: who connects to whom

Metrics (Prometheus)job · namespace · pod Traces (Tempo)trace_id · service.name Logs (Loki)stream labels · trace_id metadata exemplar (trace_id) trace → metrics (label mapping) trace → logs (trace_id + time) derived field (logs → trace) fallback: same resource labels + same time window (Explore split view)
Figure 1-2: the four solid lines are one-click jumps configurable in Grafana; the dashed line is the manual correlation used when there is no ID

Core animation: the three signals of one request, from production to being linked together in Grafana

Play or step through: a request enters myapp-edge → calls myapp → Redis slows; the three signals reach three backends via Prometheus scraping, Alloy and the OTel Collector; finally in Grafana you jump from the alert to an exemplar, a trace and logs.

Production (app)
request GET /checkoutclient
histogram + exemplarmetric
logfmt line + trace_idlog
3 spans (edge/myapp/redis)trace
Transport (collection)
Prometheus scrapes /metricspull
Alloy: parsing + metadatapush
Collector: k8sattributespush
metrics-generatorRED
Storage and presentation
Prometheus (exemplars)TSDB
Loki (streams + chunks)logs
Tempo (live-store)traces
Grafana: alert → trace → logsUI
Click “Play” or “Next step”.
$ # the real data snippet for each step will appear here

The same request, queried once in each of the three backends

BackendAPI / commandDescription
PrometheusGET /api/v1/query_exemplars?query=…&start=…&end=…returns exemplars (containing trace_id labels, values, timestamps); requires exemplar-storage
TempoGET /api/search?q={TraceQL},GET /api/v2/traces/<traceID>search by TraceQL or fetch a whole trace by ID
LokiGET /loki/api/v1/query_range?query={LogQL},logcli queryquery logs by stream selector + filters
GrafanaExplore (split view), Drilldown apps (Logs / Traces / Metrics)view all three kinds of data side by side over the same time range
source ~/promlab/part8/env.sh
# 1) get the trace_id of a slow request from a metric (exemplar, the one with the largest value)
TID=$(curl -s -G $P/api/v1/query_exemplars \
  --data-urlencode 'query=myapp_http_request_duration_seconds_bucket{route="/checkout"}' \
  --data-urlencode "start=$(date -d '-10 min' +%s)" --data-urlencode "end=$(date +%s)" \
  | jq -r '[.data[].exemplars[]] | max_by(.value | tonumber) | .labels.trace_id')
echo "trace_id=$TID"
# 2) fetch the whole trace from Tempo, list each span's service, name and duration
curl -s $T/api/v2/traces/$TID | jq -r '.trace.resourceSpans[] | (.resource.attributes[] | select(.key=="service.name") | .value.stringValue) as $svc
  | .scopeSpans[].spans[] | "\($svc)\t\(.name)\t\(((.endTimeUnixNano|tonumber)-(.startTimeUnixNano|tonumber))/1e6)ms"'
# 3) query all logs for the same trace_id in Loki (across services)
lq "{namespace=\"myapp\"} | trace_id=\"$TID\"" 15m
trace_id=6e0c63257de34c92bf9efcd03927272e
myapp-edge	GET /checkout	41.8ms
myapp-edge	price.calculate	30.2ms
myapp-edge	GET	9.9ms
myapp	GET /	7.1ms
myapp	INCR	0.6ms
{"app":"myapp-edge","container":"myapp","namespace":"myapp","service_name":"myapp-edge"}
["1763460321000000000","ts=2026-11-18T10:05:21 level=INFO service=myapp-edge trace_id=6e0c63257de34c92bf9efcd03927272e span_id=… msg=request method=GET route=/checkout status=200 duration_ms=41.8"]
{"app":"myapp","container":"myapp","namespace":"myapp","service_name":"myapp"}
["1763460321000000000","ts=2026-11-18T10:05:21 level=INFO service=myapp trace_id=6e0c63257de34c92bf9efcd03927272e span_id=… msg=request method=GET route=/ status=200 duration_ms=7.1"]

How to verify: The same 32-digit hex trace_id appears in all three places. Common errors: Tempo v2 API span timestamps are strings and require tonumber; | trace_id="…" is a label filter on structured metadata (Module 4), and writing it as {trace_id="…"} returns nothing because it is not a stream label. Production use: the three-step “alert to logs” script in the on-call runbook.

Lab 1: describe the same slow request with three signals (about 6 minutes)

Create a slow request: make myapp-edge's /checkout cart larger (sleep longer in the manual span) and inject 200ms latency into Redis.
#!/usr/bin/env sh
# Block Redis for about 0.2 seconds with a busy-wait Lua script, once per second, for N seconds (default 120) — simulates downstream jitter.
# Redis 7 disables the DEBUG command by default (enable-debug-command no), so DEBUG SLEEP is not used.
N=${1:-120}
kubectl -n myapp exec deploy/redis -- sh -c "for i in \$(seq $N); do
  redis-cli EVAL \"local s=redis.call('TIME') while true do local n=redis.call('TIME')
  if (n[1]-s[1])*1000000+(n[2]-s[2]) > 200000 then break end end return 1\" 0 >/dev/null; sleep 0.8; done"
chmod +x ~/promlab/part8/redis-lag.sh && ~/promlab/part8/redis-lag.sh 120 &

While the Lua script runs, Redis (single-threaded) cannot process other commands, so all INCR queue up — the effect matches a real “slow downstream”. A script only triggers BUSY after busy-reply-threshold (default 5 seconds); here it is only 0.2 seconds.

Metrics view: P95 and error rate.
pq 'histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[2m])))'
pq 'sum by (service) (rate(traces_spanmetrics_calls_total{status_code="STATUS_CODE_ERROR"}[2m]))'
[{"route":"/"},"0.21"]
[{"route":"/checkout"},"0.24"]
[{"service":"myapp"},"0.09"]

Metrics only tell you that P95 on both routes rose to about 200ms. They do not tell you which downstream it is.

Trace view: use TraceQL to find traces where the Redis span exceeds 100ms.
curl -s -G $T/api/search --data-urlencode 'q={ span.db.system = "redis" && duration > 100ms }' --data-urlencode limit=3 \
  | jq -c '.traces[] | {traceID, rootServiceName, durationMs}'
{"traceID":"a1f3…","rootServiceName":"myapp-edge","durationMs":238}

In the waterfall, INCR span takes 200ms: the slow hop is Redis. Attribute names follow the actual instrumentation; Redis instrumentation may use db.system or newer semantic conventions db.system.name; in Grafana's Tempo search, look at one span's attributes before writing the query.

Log view: myapp logs at the same time.
lq '{namespace="myapp", app="myapp"} | logfmt | duration_ms > 100' 5m | head -4

Logs give per-request latency but cannot by themselves say “slow at Redis” — unless the application logged Redis timing. Together the three form complete evidence.

Fill in the review:
signal | what it answers                     | what it does not answer
metrics | P95 ↑ to ~200ms, both routes affected | which hop, which request
traces | slow in redis INCR span, ~200ms      | whether it is widespread (check span metrics)
logs | per-request latency, trace_id          | cross-service causality

Case 1: three systems, three islands

Problem: A team has Prometheus, ELK and a commercial APM, but the service is named checkout,checkout-svc and Checkout API in the three places, and logs contain no trace_id. During one incident the on-call engineer spent 40 minutes aligning times by hand across three UIs. Approach: unify on the OTel resource attribute service.name as the single service name, add trace_id to the log format, and configure exemplars and trace → logs in Grafana. Result:“From alert to first relevant log” dropped from tens of minutes to one or two minutes (team's own report, not quantitatively verified).

Case 2: alerting on logs instead of metrics

Problem: To keep things simple, every alert was written as “ERROR lines in the last 5 minutes > N”. Log collection delays and log volume spikes made Loki queries time out, and alerts frequently fired falsely or missed incidents. Approach: Move critical SLO alerts back to native metrics (Lesson 6 burn rate); use log alerts only for “events metrics do not capture” (such as specific exception text, audit events).

Case 3: full trace collection eats the budget

Problem: After enabling OTel with 100% sampling, Tempo's object storage and Collector CPU rose several-fold in a month, while 99% of traces were never looked at. Approach: head sampling at 10% + tail sampling that keeps all errors and slow requests (Module 6), and RED metrics generated by metrics-generator before sampling (or generated before sampling with the spanmetrics connector in the Collector), so the metrics are not skewed.

Common errors and fixes

No exemplar diamonds on the Grafana graph

Chain of causes:① Prometheus does not have exemplar-storage enabled; ② the scrape negotiated something other than OpenMetrics (the classic text format carries no exemplars); ③ the application did not attach exemplars when observing (for example, prometheus_client multiprocess mode does not support exemplars); ④ the panel query does not have the Exemplars toggle on. Diagnosis:curl -s -H 'Accept: application/openmetrics-text' myapp:5000/metrics | grep '# {'; query_exemplars API. See Module 7.

trace_id appears in logs, but this trace cannot be found in Tempo

Cause: the trace was dropped by sampling (the logging instrumentation still writes trace_id,otelTraceSampled=False), the Collector export failed, the trace is past Tempo retention, or the log contains an ID passed in from upstream that this service did not export. Diagnosis: check the Collector's otelcol_exporter_send_failed_spans; check the sampled flag in the logs; check whether the time is earlier than tempo.retention.

The service names differ across the three places, so the query is empty after a Grafana jump

Cause: In Tempo it is service.name="myapp", in the Loki stream label it is app="myapp", and in Prometheus it is job="myapp/myapp" and similar. Fix: write a key → value mapping in the Tempo data source's tracesToLogsV2.tags / tracesToMetrics.tags ; the long-term fix is to emit one unified service_name label at the collection side.

Command-line questions
1. Write a command that pulls the trace_id of the slowest /checkout request in the last 10 minutes from Prometheus exemplars.
curl -s -G $P/api/v1/query_exemplars --data-urlencode 'query=myapp_http_request_duration_seconds_bucket{route="/checkout"}' \
  --data-urlencode "start=$(date -d '-10 min' +%s)" --data-urlencode "end=$(date +%s)" \
  | jq -r '[.data[].exemplars[]] | max_by(.value|tonumber) | .labels.trace_id'
2. Use LogQL to find logs for the same trace_id across all services in the myapp namespace.
{namespace="myapp"} | trace_id="6e0c63257de34c92bf9efcd03927272e"

trace_id is structured metadata: express it with a label filter expression, not in the stream selector.

Scenario analysis questions
The boss asks: “We already have Prometheus. Why spend money on logs and traces?” Explain the division of labor using one real troubleshooting case.

Take a “P99 spike” as an example: the Prometheus burn-rate alert detects the problem and quantifies the impact (detection); but it cannot tell you which downstream — an exemplar or TraceQL finds a slow trace, and the waterfall shows the time is spent in the payment gateway span (localization); jump from that trace to the logs and see the gateway returned rate limit exceeded and the request parameters (explanation). Without traces you must stitch logs across several services by time by hand; without logs you know only that it is “slow”, not “why”. On cost, sampling, short retention and making only low-cardinality dimensions labels control it (Module 8).

Verified instructional videos

▶
Correlate Your Metrics, Logs & Traces with the curated OSS observability stack from Grafana Labs — Grafana
English · official demo: correlating metrics, logs and traces in Grafana, exactly the subject of this module
▶
Grafana is the goat... Let's deploy the LGTM stack — Fireship
English · fast-paced overview of where Loki / Grafana / Tempo / Mimir each fit

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Scene: a request, like a little ball, passes through myapp-edge, myapp and Redis, leaving behind three coloured trails: blue (metrics), yellow (logs), purple (spans).
Narration: one request produces three kinds of signals at once.
Shot 2 · 20–50s
Scene: the three trails flow into Prometheus, Loki and Tempo respectively; metrics are “pulled” away, while logs and spans are “pushed” out.
Narration: they take different routes and live in different systems.
Shot 3 · 50–80s
Scene: a diamond appears on the latency graph in Grafana; clicking it expands the waterfall, and clicking a span shows logs with the same trace_id.
Narration: what links them is the trace_id and the unified service name.
Shot 4 · 80–90s
Scene: three words light up in turn: detect, localize, explain.
Narration: metrics detect, traces localize, logs explain.
or get a score of ≥ 70% in the quiz

Module 2 · Loki architecture and deployment: labels, streams and chunk storage

06:00 – 13:00 · Loki's core trade-off: index only labels, and compress log content into chunks placed in object storage. Understand “stream = set of labels” and you understand Loki's cost, performance and nearly all of its failures
7 minLoki v3.7.10 · chart 21.4.0★★★★★
Learning objectives
  • Explain the four concepts of stream, chunk, TSDB index and structured metadata, and the trade-off of “index only labels”.
  • Draw the write path (distributor → ingester → chunks + index → object storage) and the read path (query-frontend → querier → ingester / storage), and state the roles of compactor, ruler and index-gateway.
  • Compare Monolithic, Simple Scalable (deprecated, removed in Loki 4) and Microservices deployment modes, and know when object storage is required.
  • Use logcli series --analyze-labels,/loki/api/v1/index/volume and Loki self-monitoring metrics to assess label cardinality, and read maximum active stream limit exceeded.
Prerequisites: Lesson 7 Module 3 on series and cardinality. Importance:★★★★★

What: four core concepts

ConceptWhat it isExample in this lessonDesign points
Streama unique set of label key-values; logs of the same stream are appended in time order{namespace="myapp", app="myapp", container="myapp", service_name="myapp"}more streams → smaller and more fragmented chunks, larger index, higher ingester memory
Chunklogs of one stream over a period of time, compressed (gzip by default) and written to object storagetarget 1.5 MB compressed (chunk_target_size 1572864)flushed when full, after 30 minutes idle (chunk_idle_period) or after 2 hours (max_chunk_age)
Indexlabel → chunk references; schema v13 uses the TSDB index, split into 24h tablesloki_index_ prefixcovers labels only, not log content
Structured metadatakey-value pairs attached to each log line; not in the index; filterable in queriestrace_id,detected_levelthe right place for high-cardinality fields (requires schema v13 + allow_structured_metadata)

Why: why “do not index full text”

Systems like Elasticsearch build an inverted index for every word, so queries are fast but the index is often as big as the raw data, and writing and storage are expensive. Loki does the opposite: the index is tiny (labels only), log content is compressed and stored in cheap object storage; at query time labels first narrow the scope to a few streams, then the chunks are scanned in parallel “brute force” (line filtering, parsing). So Loki's performance rule is: the more precise the stream selector and the shorter the time range, the faster the query; the lower the label cardinality, the cheaper writing and storage are.

How: write and read paths (Loki 3.x)

  1. distributor: receives pushes (/loki/api/v1/push or OTLP /otlp/v1/logs), validates (labels ≤ 15, line size ≤ 256KB, timestamps no older than 7 days…), rate-limits (default 4 MB/s per tenant, burst 6 MB), and hashes by stream to replication_factor ingesters.
  2. ingester: keeps a “head chunk” per stream in memory while writing a WAL; when a chunk is full or times out it is compressed and flushed to object storage, and the index is written into TSDB index files (uploaded by the index shipper).
  3. query-frontend: splits queries by time and shard, queues them, and caches results; querier: fetches recent data from ingesters and historical chunks from storage, and executes LogQL; index-gateway: serves index queries centrally in large deployments.
  4. compactor: merges daily indexes and performs retention (retention_enabled) and deletion requests; ruler: periodically runs LogQL alerting / recording rules (Module 4); pattern ingester: automatically extracts log patterns (used by Grafana Logs Drilldown).

When: the three deployment modes

ModeShapeSuited forStatus (chart 21.4.0 / official docs, 2026-11-18)
Monolithicone process -target=all; can run multiple replicas (requires object storage)labs, small scale, or a meta-monitoring stack, up to roughly tens of GB per dayrecommended for small scale; used in this lesson
Simple Scalable (SSD)read / write / backend groups of threemedium scale (historically around 1 TB/day)deprecated, the chart notes state it is removed in Loki 4; do not choose it for new deployments
Microservices (Distributed)each component deployed and scaled independentlyproduction, high availability, large scalethe officially recommended production mode; Grafana Labs uses it internally

all except single-replica Monolithic must use object storage (S3, GCS, Azure Blob or a compatible implementation). The chart's bundled MinIO subchart is deprecated (official docs say it will be removed 2026-10-31); use cloud object storage in production. On Azure, Blob can be accessed with Workload Identity (useFederatedToken), and on AWS S3 with IRSA / Pod Identity.

Preview of Loki 4 Loki v4.0.0 is an RC in 2026-11 (rc.3 released 2026-11-07); the chart already includes dataobj and logline component families (requires Loki ≥ 4.0 and Distributed mode); one of rc.3's breaking changes is that the S3 storage class supports only STANDARD and STANDARD_IA. This lesson is written for 3.7.x; after the 4.0 GA, check its upgrade guide.
Common misconceptions① “More labels make queries faster” — labels only help narrow the set of streams; each added high-cardinality label multiplies the stream count, fragments chunks, and makes queries open more chunks, so they get slower. ② “Promote every JSON field to a label for easy filtering” — use parsers (| json) to extract at query time instead. ③ “Loki cannot query by trace_id” — it can: store it in structured metadata or the log line and filter with | trace_id="…" ; you only need to narrow the scope first with a stream selector. ④ “Setting retention_period means deletion happens” — you must also have the compactor retention_enabled: true and configure delete_request_store.

Loki write and read paths

Alloy / OTelpush · OTLP distributorvalidation · rate limiting · hashing ingester ×RFone head chunk per stream (memory)WAL · chunk flushfull / 30m idle / 2h object storagechunks (gzip compressed)TSDB index (24h tables)S3 · GCS · Blob compactormerge indexesretention · deletion write path ↑ · read path ↓ GrafanaLogQL query-frontendsplit · queue · cache queriermerge · filter · parse index-gatewaylabels → chunk list rulerLogQL rules → AM recent data historical chunks Monolithic mode: all the boxes above are in the same process (-target=all); loki-0 in this lesson works this way
Figure 2-1: the write path only does “split by labels + append and compress”; the read path queries the index first and then scans chunks

The same logs, two label designs

Good: low-cardinality labels {namespace, app, container} stream 1: myapp / myapp — chunks ≈ 1.5 MB, few flushes stream 2: myapp-edge / myapp — chunks ≈ 1.5 MB trace_id, status, user → structured metadata / log contentquery: {app="myapp"} | logfmt | status >= 500 Bad: trace_id as a label {namespace, app, container, trace_id} one stream per request, each chunk has only 1–2 lines (a few hundred bytes) index bloat · ingester memory spike · flush storm quickly triggers maximum active stream limit exceeded
Figure 2-2: Loki label design is the same as Prometheus: labels are “index dimensions”, not “data fields”

Interaction: label cardinality → number of streams → chunk size calculator

Tick the fields you want as Loki labels, set the log volume, and observe the number of active streams, the write rate per stream, the average chunk size at flush time, and whether tenant limits are triggered (defaults max_global_streams_per_user 5000,max_label_names_per_series 15). The compression ratio is roughly estimated as 8:1.

Tick a label above to start.
$ # estimation result

Observe Loki: labels, streams, chunks, limits

command / APIPurpose
logcli labels,logcli labels applist label names and the values of a label
logcli series '{namespace="myapp"}' --analyze-labelscount matching streams and how many distinct values each label contributes (find the cardinality culprit)
GET /loki/api/v1/index/stats?query={…}stream count, chunk count, entry count, bytes (index-based estimates)
GET /loki/api/v1/index/volume?query={…}log volume aggregated by label (requires volume_enabled)
GET /config,GET /loki/api/v1/status/buildinfoeffective configuration and version
self-monitoring metricsloki_ingester_memory_streams,loki_ingester_chunks_flushed_total{reason},loki_discarded_samples_total{reason},loki_distributor_bytes_received_total
source ~/promlab/part8/env.sh
export LOKI_ADDR=$L          # logcli reads this variable
logcli labels
logcli series '{namespace="myapp"}' --analyze-labels
curl -s -G $L/loki/api/v1/index/stats --data-urlencode 'query={namespace="myapp"}' | jq -c .
curl -s -G $L/loki/api/v1/index/volume --data-urlencode 'query={namespace="myapp"}' --data-urlencode 'since=1h' \
  | jq -c '.data.result[] | {m: .metric, bytes: .value[1]}'
# key limits from the effective configuration
curl -s $L/config | grep -E 'max_global_streams_per_user|ingestion_rate_mb|max_label_names_per_series|chunk_target_size|retention_period'
app
container
namespace
service_name
Total Streams:  2
Unique Labels:  4

Label Name    Unique Values  Found In Streams
app           2              2
service_name  2              2
container     1              2
namespace     1              2
{"streams":2,"chunks":6,"bytes":3815290,"entries":15622}
{"m":{"namespace":"myapp"},"bytes":"3815290"}
  ingestion_rate_mb: 4
  max_label_names_per_series: 15
  max_global_streams_per_user: 5000
  retention_period: 1w
  chunk_target_size: 1572864
# Loki self-monitoring: kps Prometheus needs to scrape Loki (the chart's monitoring.serviceMonitor can enable it, see the lab)
pq 'sum(loki_ingester_memory_streams)'
pq 'sum by (reason) (increase(loki_ingester_chunks_flushed_total[1h]))'
pq 'sum by (reason) (rate(loki_discarded_samples_total[5m]))'

How to verify: two applications in one namespace, so the stream count should be 2. Common errors:/config the output is full YAML,retention_period may appear as 1w ; the logcli version should be close to the server version. Production use:--analyze-labels the first command to run when investigating a Loki cardinality incident.

Lab 2: deliberately create and then fix a stream explosion (about 7 minutes)

Let kps scrape Loki's own metrics (the chart's ServiceMonitor; requires kps's selector label):
cd ~/promlab/part8
helm upgrade loki grafana-community/loki --version 21.4.0 -n observability -f loki-values.yaml \
  --set monitoring.serviceMonitor.enabled=true --set-string monitoring.serviceMonitor.labels.release=kps
sleep 60; pq 'sum(loki_ingester_memory_streams)'
[{},"2"]
Inject: temporarily lower Loki's stream limit to 200, then in Alloy wrongly promote trace_id to a label.
helm upgrade loki grafana-community/loki --version 21.4.0 -n observability -f loki-values.yaml \
  --reuse-values --set loki.limits_config.max_global_streams_per_user=200
sed 's/values = { "service_name" = "service" }/values = { "service_name" = "service", "trace_id" = "" }/' alloy-values.yaml > alloy-bad.yaml
helm upgrade alloy grafana/alloy --version 1.16.0 -n observability -f alloy-bad.yaml
sleep 90
kubectl -n observability logs deploy/alloy --since=2m | grep -m2 'stream limit'
ts=… level=error msg="final error sending batch, no retries left, dropping data" component_path=/ component_id=loki.write.default status=429 tenant="" error="server returned HTTP status 429 Too Many Requests (429): maximum active stream limit exceeded when trying to create stream {app=\"myapp\", …, trace_id=\"…\"}, reduce the number of active streams (reduce labels or reduce label values), or contact your Loki administrator to see if the limit can be increased, user: 'fake'"

The error text comes from v3.7.10 pkg/validation/validate.go of StreamLimitErrorMsg; the field order in Alloy's logs depends on the actual output. Note: over-limit logs are discarded, and Alloy does not retry 4xx (except 429), and retries of 429 are capped.

Diagnosis:
pq 'sum(loki_ingester_memory_streams)'
pq 'sum by (reason) (rate(loki_discarded_samples_total[2m]))'
logcli series '{namespace="myapp"}' --since=5m --analyze-labels | head -8
[{},"200"]
[{"reason":"stream_limit"},"6.4"]
Total Streams:  200
Unique Labels:  5

Label Name    Unique Values  Found In Streams
trace_id      198            198
...
Fix and reset: restore the Alloy config (trace_id goes back to structured metadata) and the Loki limits; old streams are flushed after 30 minutes idle and removed from ingester memory.
helm upgrade alloy grafana/alloy --version 1.16.0 -n observability -f alloy-values.yaml
helm upgrade loki grafana-community/loki --version 21.4.0 -n observability -f loki-values.yaml \
  --set monitoring.serviceMonitor.enabled=true --set-string monitoring.serviceMonitor.labels.release=kps
rm alloy-bad.yaml
Think about it: if the limit were the default 5000, how would this incident play out? (Answer: it would take longer to error, and during that time ingester memory and chunk counts keep growing; limits are guardrails, not a fix — the correct approach is to forbid high-cardinality labels in the Alloy pipeline.)

Case 1: using the Pod name as a label doubles the stream count on each release

Problem: A service with 300 Pods is released 10 times a day; pod labels keep doubling the stream count, and ingesters OOM at release peaks. Approach: keep only namespace,app and container (plus cluster and environment) as stream labels; put the Pod name in structured metadata; to query one Pod, use | pod="…". Trade-off: filtering by Pod means scanning the whole application's chunks, so a single query is somewhat slower, but overall cost and stability improve greatly.

Case 2: planning an upgrade away from Simple Scalable mode

Problem: The team deployed Loki in Simple Scalable mode in 2024; the chart now marks SSD as deprecated and Loki 4 will remove it. Approach: follow the transition mode the chart provides SimpleScalable<->Distributed and migrate step by step to Distributed; the object storage and schema stay the same; verify in pre-production first. Lesson: when choosing a deployment mode, check the official documentation's current recommendation, not old blog posts.

Case 3: retention did not take effect, and object storage bills keep rising

Problem: We set retention_period: 30d, but six months later found chunks from six months ago still in storage. Cause: the compactor did not enable retention_enabled, and in Simple Scalable mode the compactor runs on the backend but lacks object storage delete permissions. Approach: enable retention, grant the compactor delete permissions, and add alerts monitoring loki_compactor_* metrics; object-storage lifecycle rules can also serve as a fallback (slightly longer than retention).

Common errors and fixes

maximum active stream limit exceeded when trying to create stream …

Cause: the tenant's active streams exceed max_global_streams_per_user (default 5000). Diagnosis:logcli series '{…}' --analyze-labels find the label with the most distinct values. Fix: remove high-cardinality labels at the collection side (move them to structured metadata); raise the limit only when truly needed.

ingestion rate limit exceeded for user fake (limit: 4194304 bytes/sec) while attempting to ingest '…' lines totaling '…' bytes, reduce log volume or contact your Loki administrator to see if the limit can be increased

Cause: tenant write rate exceeds ingestion_rate_mb (default 4) / ingestion_burst_size_mb (default 6). Diagnosis:rate(loki_distributor_bytes_received_total[5m]),loki_discarded_samples_total{reason="rate_limited"}. Fix: first find the source of the spike (debug logs, looping errors); drop noisy lines at the collection side (Module 3 stage.drop); raise the limit sensibly.

entry for stream '…' has timestamp too old: …, oldest acceptable timestamp is: …

Cause: log timestamps are older than reject_old_samples_max_age (default 7 days) — common when the collector backfills after a backlog, or when a wrong time field in the logs gets parsed. Fix: check the timestamp stage and time zone at the collection side; when backfilling, accept the drops or temporarily relax the limit.

Helm install fails: Cannot run more than 1 Monolithic replica without an object storage backend.

Cause: chart validation: filesystem storage supports only a single replica. Fix: lab environment singleBinary.replicas: 1; when HA is needed, configure object storage and set replication_factor and the replica count both to 3.

query reports maximum number of series (500) reached for a single query; consider reducing query cardinality …

Cause: the number of result series of a metric-type LogQL query exceeds max_query_series (default 500). Fix:sum by (…) aggregate to fewer dimensions, add a more precise selector, or use topk (Module 4).

Command-line questions
1. Find the label in the myapp namespace that contributes the most streams.
logcli series '{namespace="myapp"}' --since=1h --analyze-labels

Look at the row with the largest “Unique Values”.

2. Use the API to view the log bytes per app in the myapp namespace over the last 24 hours.
curl -s -G $L/loki/api/v1/index/volume --data-urlencode 'query={namespace="myapp"}' \
  --data-urlencode 'targetLabels=app' --data-urlencode 'since=24h' | jq -c '.data.result[] | {app: .metric.app, bytes: .value[1]}'
Scenario analysis question
A team wants HTTP status code, user ID and request path all as Loki labels, so that Grafana dropdown filters are convenient. How do you respond?

Status codes have low cardinality (dozens), so they can be considered but usually are not needed; user IDs and raw paths are unbounded and cause stream explosions. Suggestion: keep only namespace / app / container (plus environment and cluster) as stream labels; keep status codes and paths in log content, filtered with | logfmt | status >= 500 ; put the user ID in structured metadata. Grafana dropdown filters can be based on parsed fields (Logs Drilldown detects fields automatically), so indexed labels are not needed. Use --analyze-labels and index volume data to explain the cost difference.

Verified instructional videos

▶
All the Components of Loki Explained | Grafana Labs — Grafana
English · official walkthrough of distributor, ingester, querier and other components, matching Figure 2-1
▶
How to Get Started with Loki | Zero to Hero: Loki | Grafana — Grafana
English · first episode of an introductory series
▶
Grafana Loki design basics with Ed Welch (Grafana Office Hours #27) — Grafana
English · Loki's design trade-offs and label best practices
▶
All about Structured Metadata in Loki (Loki Community Call August 2025) — Grafana
English · the background of structured metadata

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Scene: log lines flow in like water and are split by labels into two “channels” (two streams); the logs in each channel are packed into boxes (chunks).
Narration: Loki only splits streams by labels; content is compressed and stored in object storage.
Shot 2 · 25–60s
Scene: someone adds trace_id as a label; the two channels instantly split into hundreds or thousands of thin streams, the boxes hold only one or two lines, and a red 429 appears in the top right.
Narration: high-cardinality labels explode the streams, chunks become fragmented, limits trigger, and logs are dropped.
Shot 3 · 60–90s
Scene: trace_id is moved into small labels beside each log line (structured metadata), and the channels return to two.
Narration: high-cardinality fields go into structured metadata; labels keep only low-cardinality dimensions.
or get a score of ≥ 70% in the quiz

Module 3 · Log collection: Grafana Alloy and the OpenTelemetry Collector

13:00 – 21:00 · Promtail reached end of life on 2026-03-02; Alloy is Grafana's OTel-compatible collector, and the OTel Collector is the vendor-neutral standard pipeline. Both are directed graphs of “receive → process → export”; the choice depends on your backend and team
8 minAlloy v1.22.0 · Collector v0.165.0★★★★★
Learning objectives
  • State Promtail's status (EOL 2026-03-02; only lambda-promtail is outside the deprecation) and the migration path (alloy convert --source-format=promtail).
  • Read and write Alloy configuration: component = type + label,forward_to / output wired into a graph; master discovery.kubernetes,discovery.relabel,loki.source.kubernetes,loki.process,loki.write.
  • Read and write OTel Collector configuration: receivers / processors / exporters / connectors and service.pipelines; understand the position of memory_limiter,k8sattributes,batch and the renames of otlp → otlp_grpc,otlphttp → otlp_http since v0.144.
  • Understand Loki's OTLP intake: which resource attributes become indexed labels and which go into structured metadata.
Prerequisites: Lesson 1 relabel, Lesson 6 Module 6 Collector basics. Importance:★★★★★

What: the state of the collector family (2026-11)

CollectorStatusNotes
PromtailEOL (2026-03-02)Official Promtail docs: commercial support has ended, no further updates, all new features are developed in Alloy; lambda-promtail is outside the deprecation
Grafana Agent (Static / Flow)replaced by AlloyAlloy evolved from Agent Flow; alloy convert Supports static Format conversion
Grafana AlloyCurrent (v1.22.0, 2026-11-13)One binary handles metrics, logs, traces and profiles, with many built-in otelcol.* components (wrapping upstream Collector components) and loki.*/prometheus.* native components
OpenTelemetry CollectorCurrent (v0.165.0, 2026-11-07)CNCF standard; core and contrib distributions (this lesson uses contrib, which includes k8sattributes, tail_sampling, filelog); vendor distributions also exist (e.g. ADOT in lesson 4)
Fluent Bit / VectorActive third-partyagents can all write to Loki; keep using them if you already have an investment in them

Why: why a “processing” step is needed

Container stdout is just lines of text. Before writing to Loki we need to: ① add “whose log is this” (Kubernetes metadata → labels); ② decide which fields become labels, which become structured metadata, and which stay in the line; ③ drop noise (health checks, debug logs) and redact sensitive data; ④ batch, compress, retry and rate-limit. This logic belongs in the collector, where it is cheaper and more consistent than putting it in every application.

How: Alloy's component graph

  • Each block is a component: <type> "<label>" { … }, for example loki.process "myapp". A component's output is referenced by expressions: discovery.relabel.pods.output,loki.write.default.receiver.
  • Log pipeline: discovery.kubernetes (find Pods) → discovery.relabel (generate labels,__ meta-labels with the reserved prefix are dropped at the end) → loki.source.kubernetes (read logs through the API, with no privileges or hostPath needed; the cost is higher CPU and network overhead on the kubelet) or loki.source.file (a DaemonSet reads node files) → loki.process (stage pipeline) → loki.write.
  • Common stages: stage.logfmt / stage.json / stage.regex (extract into a temporary map),stage.labels (promote to labels),stage.structured_metadata,stage.timestamp,stage.drop,stage.match,stage.multiline (Java stack traces),stage.replace (redaction).

How: the OTel Collector pipeline

  • receivers: otlp (gRPC 4317 / HTTP 4318),filelog (reads the node's /var/log/pods),prometheus (scrape)…
  • processors (order matters): memory_limiter (place first; it refuses data when over the limit instead of OOM-ing) → k8sattributes (match by source IP or k8s.pod.ip etc. to associate Pods, adding namespace, pod, deployment, and so on) resource / attributes / transform → sampling (tail_sampling, module 6) → batch Added in v0.165: the queue_batch processor (beta) and the exporter's built-in sending_queue::batch is the new direction for batching; enabling both triggers a warning at startup.
  • exporters: otlp_grpc (formerly otlp),otlp_http (formerly otlphttp, renamed in v0.144; the old name remains usable as a deprecated alias),debug,prometheusremotewrite…; connectors connectors: an exporter in one pipeline plus a receiver in another, for example spanmetrics (traces → metrics).

Loki's OTLP ingestion

Loki 3 natively accepts OTLP logs (endpoint /otlp/v1/logs; the otlp_http exporter writes http://loki:3100/otlp is enough). By default, a set of resource attributes (such as service.name,service.namespace,deployment.environment,k8s.namespace.name,k8s.pod.name etc., with dots converted to underscores) as index labels, while the remaining resource attributes, log attributes,trace_id,span_id are stored as structured metadata; it can be adjusted with limits_config.otlp_config . Note that the default list includes k8s.pod.name: with many Pods and frequent deployments, you need to evaluate the stream count (module 2, case 1).

When: Alloy or the OTel Collector?

ScenarioLeaning towardReason
Backend is the Grafana stack (Loki / Mimir / Tempo / Grafana Cloud)Alloyloki.* Native components, Loki write features (structured metadata, rate-limited handling), debugging UI; Grafana's k8s-monitoring chart is built on it
Multiple backends, vendor-neutral, team already knows Collector YAMLOTel CollectorStandard config format with the most community components; compatible with vendor distributions (ADOT, etc.)
Applications already push OTLP using the OTel SDKEither worksAlloy's otelcol.receiver.otlp is equivalent to the Collector
This lessonEach does its own jobAlloy reads container stdout → Loki; the Collector receives OTLP traces → Tempo (and also demonstrates OTLP logs → Loki)
Common misconceptions① “Promtail still works, so we don't need to migrate yet” — EOL means no security fixes; use alloy convert the converter; the bulk of the migration usually takes only a few minutes. ② “A DaemonSet reading files is the same as reading logs through the API” —loki.source.kubernetes avoids privileges but adds load on the kubelet / API; large clusters usually use a DaemonSet + loki.source.file (or a Collector filelog)”. ③ “batch Putting memory_limiter at the front also works” —memory_limiter should be the first processor, otherwise data piles up in memory before it takes effect. ④ “After OTLP logs are sent to Loki, every attribute can be queried as a label” — only the promoted ones are index labels; the rest are structured metadata (use | key="value" to filter).

The two collection pipelines in this lesson

Alloy (logs: container stdout → Loki) discovery.kubernetesrole=pod · ns=myapp discovery.relabelnamespace/app/container loki.source.kubernetesAPI: pods/log loki.processlogfmt · metadata · labels loki.write→ /loki/api/v1/push OTel Collector (traces + OTLP logs) receiver: otlpgRPC 4317 · HTTP 4318 memory_limiterFirst k8sattributesIP → Pod metadata resourcecluster=lab batch otlp_grpc → Tempo otlp_http → Loki /otlp The two pipelines are independent: an Alloy failure only affects logs, and a Collector failure only affects traces (and OTLP logs) — this is itself a form of fault isolation
Figure 3-1: Alloy and the Collector are both “directed graphs”, differing only in configuration language (Alloy syntax vs YAML)

How one log line changes inside loki.process

Raw: ts=2026-11-18T10:05:21 level=ERROR service=myapp trace_id=4bf9…4736 span_id=00f0…02b7 msg=request route=/error status=500 stage.logfmt → temporary maplevel=ERROR · trace_id=4bf9… · service=myapp stage.structured_metadatatrace_id → per-line metadata (not indexed) stage.labelsservice_name=myapp → stream label (low cardinality) The log line itselfKept unchanged; level is automatically detected by Loki as detected_level
Figure 3-2: values extracted into the map are only candidates; only those used by the labels / structured_metadata stages are written to Loki

Interactive: step-by-step transformation of a log line through the collection pipeline

Select an input log, then step through it: each step shows the current labels, the temporary extracted map, structured metadata and the log line; the last step shows the JSON pushed to Loki (/loki/api/v1/push 's streams structure).

Select a log to start.
$ # current state

Common Alloy and Collector commands

CommandPurpose
alloy fmt config.alloyFormat / syntax check
alloy convert --source-format=promtail -o config.alloy promtail.yamlConvert Promtail config (also supports otelcol,prometheus,static; --report outputs diagnostics; --bypass-errors skips unsupported items)
curl localhost:12345/-/ready,/-/reloadreadiness check and config hot reload (POST)
Alloy UI → Components → Live debuggingView the data a component receives and sends in real time
otelcol-contrib validate --config=…Collector config validation
Collector self-monitoring :8888/metricsotelcol_receiver_accepted_spans,otelcol_exporter_sent_spans,otelcol_exporter_send_failed_spans,otelcol_processor_refused_* (metric names depend on the actual version)
# 1) Alloy: component health and loki.write metrics
kubectl -n observability port-forward deploy/alloy 12345:12345 >/dev/null 2>&1 &
curl -s localhost:12345/metrics | grep -E '^loki_write_(sent_entries_total|dropped_entries_total|request_duration_seconds_count)' | head
# 2) Promtail → Alloy conversion (runs offline with the Alloy image, no installation needed)
cat > promtail.yaml <<'EOF'
server: {http_listen_port: 9080}
clients: [{url: http://loki:3100/loki/api/v1/push}]
scrape_configs:
  - job_name: pods
    kubernetes_sd_configs: [{role: pod}]
    pipeline_stages:
      - cri: {}
      - logfmt: {mapping: {level: ""}}
      - labels: {level: ""}
    relabel_configs:
      - {source_labels: [__meta_kubernetes_namespace], target_label: namespace}
      - {source_labels: [__meta_kubernetes_pod_uid, __meta_kubernetes_pod_container_name], separator: /, target_label: __path__, replacement: /var/log/pods/*$1/*.log}
EOF
docker run --rm -v "$PWD":/w -w /w grafana/alloy:v1.22.0 convert --source-format=promtail -o converted.alloy promtail.yaml
head -30 converted.alloy
loki_write_sent_entries_total{component_id="loki.write.default",…,host="loki.observability.svc:3100"} 48211
loki_write_dropped_entries_total{component_id="loki.write.default",…,reason="…"} 0
discovery.kubernetes "pods" {
	role = "pod"
}

discovery.relabel "pods" {
	targets = discovery.kubernetes.pods.targets
	rule {
		source_labels = ["__meta_kubernetes_namespace"]
		target_label  = "namespace"
	}
...
local.file_match "pods" {
	path_targets = discovery.relabel.pods.output
}
loki.process "pods" {
	forward_to = [loki.write.default_0.receiver]
	stage.cri { }
	stage.logfmt { mapping = { level = "" } }
...
# 3) Collector: self-monitoring metrics (8888; the module 0 values already change the listen address to 0.0.0.0)
kubectl -n observability port-forward deploy/otelcol-opentelemetry-collector 8888:8888 >/dev/null 2>&1 &
curl -s localhost:8888/metrics | grep -E '^otelcol_(receiver_accepted|exporter_sent|exporter_send_failed)_(spans|log_records)' | head

How to verify:loki_write_dropped_entries_total Should be 0; the Collector's sent and accepted counts should be roughly equal. Common errors: components in the converted config carry a _0 suffix and comments are lost; clean these up manually; __path__ the rule means DaemonSet + hostPath reads files and requires the chart's mounts.varlog: true. Collector internal metric names and ports change between versions; use the /metrics actual output as the reference. Production use: Turn loki_write_dropped_entries_total and otelcol_exporter_send_failed_* into alerts — “log loss” usually shows up here first (module 8).

Lab 3: modify the Alloy pipeline + try OTLP logs (about 8 minutes)

Check the current state: in Grafana Explore (Loki data source), run {namespace="myapp"}, expand a row: you can see Labels (stream labels) and Structured metadata (trace_id,detected_level). You can also use the API:
curl -s -G $L/loki/api/v1/query_range --data-urlencode 'query={app="myapp"}' --data-urlencode limit=1 \
  --data-urlencode 'categorize_labels=true' -H 'X-Loki-Response-Encoding-Flags: categorize-labels' | jq -c '.data.result[0].values[0]'
["1763460321000000000","ts=… level=INFO service=myapp trace_id=… msg=request …",{"structuredMetadata":{"trace_id":"6e0c…272e"},"parsed":{}}]

The classification structure returned in the third element depends on request headers and version; use the actual output as the reference. The grouping in the Grafana UI is the most intuitive way to observe it.

Add a drop rule and a redaction rule: drop lines with level=DEBUG; redact the value of provider=… . In alloy-values.yaml , the loki.process "myapp" block, after stage.logfmt , add:
        stage.drop {
          source = "level"
          value  = "DEBUG"
          drop_counter_reason = "debug_noise"
        }
        stage.replace {
          expression = "provider=(\\S+)"
          replace    = "***"
        }
helm upgrade alloy grafana/alloy --version 1.16.0 -n observability -f alloy-values.yaml
kubectl -n myapp exec deploy/myapp -- python -c "import urllib.request as u; u.urlopen('http://localhost:5000/error')" 2>/dev/null
lq '{app="myapp"} |= "payment provider"' 2m
["…","ts=… level=ERROR service=myapp trace_id=… span_id=… msg=\"payment provider timeout\" provider=***"]

stage.replace Only the first capture group is replaced; backslashes inside strings need escaping in Alloy syntax ("\\S+"). Dropped lines are counted in loki_process_dropped_lines_total{reason="debug_noise"} (metric names follow the actual Alloy output).

OTLP logs → Loki: use telemetrygen to send 20 OTLP logs through the Collector and observe which resource attributes become labels.
kubectl -n observability run telemetrygen --rm -i --restart=Never \
  --image=ghcr.io/open-telemetry/opentelemetry-collector-contrib/telemetrygen:v0.165.0 -- \
  logs --otlp-endpoint otelcol-opentelemetry-collector.observability.svc:4317 --otlp-insecure --logs 20 --service otlp-demo
sleep 10
curl -s -G $L/loki/api/v1/series --data-urlencode 'match[]={service_name="otlp-demo"}' | jq -c '.data[]'
{"k8s_cluster_name":"lab","k8s_namespace_name":"observability","k8s_pod_name":"telemetrygen","service_name":"otlp-demo"}

k8s.namespace.name and k8s.pod.name are added by the Collector's k8sattributes based on the connection's source IP; k8s.cluster.name come from resource/cluster; both are in Loki's default list of resource attributes promoted to index labels. For telemetrygen's parameters, refer to its --help documentation.

Comparison and cleanup: for logs in the same myapp namespace, the Alloy path's labels are the four you carefully picked in discovery.relabel ; the OTLP path's labels are set by Loki's default otlp_config , which includes the Pod name. Both paths need label review in production.

Case 1: migrating Promtail to Alloy

Problem: A 300-node cluster runs the Promtail DaemonSet, which has not received security updates since 2026-03. Approach:① alloy convert --source-format=promtail --report=report.txt Generate a draft; ② manually clean up component names and keep the original label set (label changes create new streams and break dashboard queries); ③ canary: switch 10% of one node pool first and compare loki_write_sent_entries_total with Promtail's send volume; ④ after the full rollout, remove the Promtail position-file mount. Pitfall: Whether Alloy reads a file from the end or the start by default depends on whether a positions record exists; during the switch, a few logs may be duplicated or lost, so communicate this in advance.

Case 2: k8sattributes cannot associate Pods

Problem: After forwarding through a “gateway Collector”, every span's k8s.pod.name is the gateway's own Pod. Cause:k8sattributes Association uses the connection's source IP by default; after a second forwarding hop, the source IP becomes the upstream Collector. Fix: Do the association at the first hop (agent / DaemonSet Collector), or have the application include k8s.pod.ip / k8s.pod.uid in resource attributes and configure pod_association to prefer resource attributes. This lesson's myapp does exactly that in OTEL_RESOURCE_ATTRIBUTES , by including k8s.pod.ip.

Case 3: log collection saturates the node

Problem: When a service misbehaves it prints tens of thousands of stack-trace lines per second, the DaemonSet collector saturates its CPU and affects other workloads on the same node. Fix: Set a CPU limit and sensible requests on the collector; use stage.limit (Alloy) to rate-limit per stream; fix the logging loop in the application; set per-stream rate limits in Loki as the last line of defense.

Common errors and fixes

Alloy log: final error sending batch … status=400 … error at least one label pair is required per stream

Cause:discovery.relabel once the labels are dropped, no non- __ label remains (for example, a faulty rule drops everything). Fix: In the Alloy UI, check discovery.relabel 's Exports and keep at least one label.

Alloy log: … 403 Forbidden … pods "myapp-…" is forbidden: User "system:serviceaccount:observability:alloy" cannot get resource "pods/log"

Cause: A custom rbac.rules or disabled RBAC caused loss of the pods/log permission. Fix: Restore the chart's default rules, or add pods,pods/log with get/list/watch verbs.

Collector fails to start: 'exporters' unknown type: "otlp_grpc"

Cause: The Collector version in use is older than v0.144 (before the rename). Fix: Upgrade the image, or keep using otlp / otlphttp on the old version. Conversely, the old name still works in newer versions but prints a deprecation warning.

Collector log: Exporting failed. Will retry the request after interval … rpc error: code = Unavailable desc = connection error

Cause: the backend (Tempo) is unreachable, or the port / TLS config is wrong (plaintext gRPC requires tls.insecure: true). Diagnosis:kubectl -n observability get svc tempo, the Collector's otelcol_exporter_send_failed_spans. Data is dropped once the retry queue is full.

Kubernetes metadata is empty in Loki; only service_name is present

Cause:k8sattributes RBAC is missing (the preset is not enabled), or the association rules don't match, or the processor was not added to the pipeline. Fix: Enable presets.kubernetesAttributes, and confirm service.pipelines.logs.processors includes k8sattributes.

Command-line exercises
1. Convert a Promtail config to an Alloy config and output a diagnostic report.
alloy convert --source-format=promtail --report=report.txt -o config.alloy promtail.yaml
2. Write an Alloy stage that puts the user field from logfmt into structured metadata instead of labels.
stage.logfmt {
  mapping = { "user" = "" }
}
stage.structured_metadata {
  values = { "user" = "" }
}
Scenario analysis
The platform team must design log collection for a 200-node production cluster: there is container stdout, and some services push OTLP logs directly with the OTel SDK. Provide the architecture and key configuration points.

A node-level DaemonSet (Alloy's loki.source.file reads /var/log/pods, or the Collector's filelog receiver) handles stdout; the same DaemonSet opens OTLP ports to receive pushes from applications on its node and completes k8sattributes association at the first hop; an optional gateway layer (Deployment) handles tail sampling, unified export and credential management. Key points: a label allowlist (namespace / app / container / cluster / env), high-cardinality fields go into structured metadata,memory_limiter and resource limits, dropping noise, redaction, alerts on export failures, and per-team tenant separation (X-Scope-OrgID), and canary rollout of config changes.

Verified instructional videos

▶
What is Alloy and when does it make sense to use it? | Grafana Alloy for Beginners Ep 2 — Grafana
English · Alloy's positioning and use cases
▶
Alloy Configuration Language 101 | Grafana Alloy for Beginners Ep 3 — Grafana
English · components, arguments, exports and connections
▶
OpenTelemetry Collector: EVERYTHING you need to know [to get started] — Adam Gardner
English · Collector receivers / processors / exporters
▶
Docker Tutorial: Getting started with Grafana Loki and Alloy | Complete Promtail Migration Guide — Free Linux Tutorials
English · migrating from Promtail to Alloy in a Docker environment

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: an “EOL 2026-03-02” stamp over the Promtail icon, with an arrow pointing to Alloy.
Narration: Promtail is retired; use Alloy or the OTel Collector for new log collection.
Shot 2 · 20–60s
Visual: a log line passes through five blocks in turn: discovery, relabel, read, process, write; each block changes the labels and metadata.
Narration: the collector is a directed graph where each component does one thing.
Shot 3 · 60–90s
Visual: the Collector pipeline lights up memory_limiter at the front, and k8sattributes tags each span with a Pod name badge.
Narration: memory protection goes first; Kubernetes metadata is filled in at the first hop.
or score ≥ 70% on the quiz

Module 4 · LogQL: filtering, parsing and generating metrics from logs

21:00 – 28:00 · LogQL = stream selector + pipeline. First narrow the streams with labels, then shrink the set with the cheapest line filter, and only then parse and filter by field; wrap it in rate / count_over_time and logs become metrics and alerts
7 minutesLogQL · ruler★★★★★
Learning objectives
  • Write log queries: stream selectors (= != =~ !~), line filters (|= != |~ !~), parsers (json,logfmt,pattern,regexp), label filters (including numeric comparisons),line_format,label_format,drop / keep.
  • Write metric queries: rate,count_over_time,bytes_over_time,sum by,topk,quantile_over_time … | unwrap and handle __error__.
  • Use the Loki ruler to generate alerts from logs and send them to kps' Alertmanager; know when to use native metrics instead of log alerts.
Prerequisites: Lesson 1 PromQL rate and aggregation; module 2 streams. Importance:★★★★★

What: the two types of LogQL queries

TypeFormReturnsExample
Log query{selector} | pipeline …Log lines (streams){app="myapp"} |= "ERROR" | logfmt | status >= 500
Metric queryfunction(log query [range]), can be further aggregatedTime series (same vectors / matrices as PromQL)sum by (route) (rate({app="myapp"} | logfmt | status >= 500 [5m]))

Pipeline stages at a glance

StageSyntaxCostNotes
Line filter|= "x" != "x" |~ "re" !~ "re"LowestSubstring / regex matching on raw lines; put it first, since the earlier lines are dropped the better
Parser| logfmt | json | pattern "<_> status=<status> <_>" | regexp "…"inextracts fields as query-time labels; on parse failure, sets __error__
Label filter| status >= 500 | route="/checkout" | duration_ms > 100 | trace_id="…"LowWorks on stream labels, structured metadata and parsed labels; numbers and durations can be compared directly
Formatting| line_format "{{.route}} {{.status}}",| label_format svc=serviceLowRewrites the output line or labels with Go templates
Label cleanup| drop level,| keep app, routeLowDrops unneeded dimensions before a metric query to avoid too many series
unwrap| unwrap duration_ms,| unwrap duration(d)—treats a label's value as the sample value, for use by sum_over_time,quantile_over_time etc.

Why: order determines performance

Loki first uses the stream selector to query the index for a list of chunks, then decompresses the chunks and runs the pipeline line by line. A line filter only does string comparison, while a parser has to split every line into fields—so putting |= "status=500" before | logfmt | status=500 is much faster than writing only the latter, with the same result. Likewise, a selector needs at least one equality matcher ({app="myapp"}), otherwise a huge number of streams gets scanned; Loki also rejects {app=~".*"} selectors like this that can match empty values.

How: mapping metric queries to PromQL

LogQLMeaningSimilar PromQL
count_over_time({…}[5m])Number of lines in the windowincrease()
rate({…}[5m])Lines per secondrate()
bytes_over_time / bytes_rateBytes in the window / bytes per second— (common for cost analysis)
quantile_over_time(0.95, {…} | logfmt | unwrap duration_ms [5m]) by (route)Quantile computed from a log fieldhistogram_quantile (but this is an exact quantile, which is expensive)
absent_over_time({…}[10m])Returns 1 when there are no logs in the windowabsent_over_time

Note: unwrap Range functions after output one series per label combination— all parsed fields (including trace_id) become dimensions. Always use by (…) or | keep to limit dimensions, otherwise you will hit maximum number of series (500) reached for a single query.

When: log alerts vs metric alerts

  • Use log alerts: events that exist only in log text and not in metrics, such as specific exceptions (OutOfMemoryError,certificate has expired), audit events, and third-party components that only emit logs and no metrics.
  • Use metric alerts: SLOs, error rate, latency. Native metrics are cheaper and more timely (lessons 2 and 6). Computing P95 from logs suits “filling gaps” but should not be the main alert.
  • The Loki ruler uses the same rule format as Prometheus rules (groups / rules / alert / expr / for / labels / annotations), except that the expr is LogQL. Alerts go to Alertmanager; recording rules need remote write configured to write results to Prometheus / Mimir.
Common misconceptions① “|= "error" is case-insensitive” — it is case-sensitive; use |~ "(?i)error". ② “Fields extracted by a parser can go in the stream selector” — no,{status="500"} the selector can only use stream labels. ③ “count_over_time and rate handle counter resets the same way” — they just count log lines and have no concept of reset. ④ “LogQL metric query results can be stored long-term directly as Prometheus metrics” — only recording rules in the ruler plus remote write write them into the time series database.

The execution pipeline of a LogQL query

sum by (route) (rate({app="myapp"} |= "status=5" | logfmt | status >= 500 [5m])) ① Selectorindex lookup → chunk list10 000 lines ② Line filtersubstring match→ 300 lines ③ logfmtparse only 300 linesextract status, route… ④ Label filterstatus >= 500→ 120 lines ⑤ rate + sum byaggregate per step→ 2 series Performance rulesThe more precise the selector, the fewer chunks opened; the earlier the line filter, the fewer lines parsed; the shorter the time range, the less data scanned.The line filter “status=5” is logically redundant, but it means the parser handles 97% fewer lines.
Figure 4-1: the LogQL pipeline runs left to right, line by line; each stage only sees the lines left by the previous stage

Log alert chain

ConfigMaplabel loki_rule rules sidecarwritten to /rules/fake/ Loki rulerrun LogQL every interval Alertmanagerkps · routing notificationLesson 2
Figure 4-2: the same alert lifecycle as Prometheus alerts (pending → firing → Alertmanager), except the expression runs in Loki

Interactive: LogQL pipeline stage-by-stage executor

Below are 8 sample log lines (from myapp and myapp-edge). Select a query, then run it stage by stage to see which lines remain after each stage and which fields were extracted; metric queries show per-step results at the end.

$ # select a query
Select a query.

Common LogQL (myapp log format)

# 1) All 5xx: line filter first, then parse
{namespace="myapp", app="myapp"} |= "status=5" | logfmt | status >= 500

# 2) pattern parser: simpler than regex, and better than logfmt for non-key-value formats
{app="myapp"} | pattern `ts=<ts> level=<level> <_> route=<route> status=<status> <_>` | level="ERROR"

# 3) Only requests with duration > 100ms, and rewrite the output line
{app="myapp"} | logfmt | duration_ms > 100 | line_format "{{.route}} {{.status}} {{.duration_ms}}ms trace={{.trace_id}}"

# 4) Filter by trace_id in structured metadata (across services)
{namespace="myapp"} | trace_id="6e0c63257de34c92bf9efcd03927272e"

# 5) 5xx ratio per route (error rate computed from logs)
sum by (route) (rate({app="myapp"} | logfmt | status >= 500 [5m]))
  / sum by (route) (rate({app="myapp"} | logfmt | __error__="" [5m]))

# 6) P95 latency from logs (keep only the route dimension)
quantile_over_time(0.95, {app="myapp"} | logfmt | __error__="" | unwrap duration_ms [5m]) by (route)

# 7) Bytes written per second per app (cost analysis)
sum by (app) (bytes_rate({namespace="myapp"}[5m]))

# 8) Top 5 Pods by log volume (when pod is not a label, use parsed fields or structured metadata)
topk(5, sum by (app) (count_over_time({namespace="myapp"}[1h])))
source ~/promlab/part8/env.sh; export LOKI_ADDR=$L
logcli query --since=10m --limit=5 '{app="myapp"} |= "status=5" | logfmt | status >= 500'
logcli query --since=30m 'sum by (route) (rate({app="myapp"} | logfmt | status >= 500 [5m]))'
logcli query --since=30m --step=1m 'quantile_over_time(0.95, {app="myapp"} | logfmt | __error__="" | unwrap duration_ms [5m]) by (route)'
logcli instant-query 'sum by (app) (count_over_time({namespace="myapp"}[1h]))'
2026-11-18T10:12:03Z {app="myapp", container="myapp", namespace="myapp", service_name="myapp"} ts=2026-11-18T10:12:03 level=ERROR service=myapp trace_id=… msg=request method=GET route=/error status=500 duration_ms=1.1
...
[
  { "metric": {"route": "/error"}, "values": [[1763460720, "0.098"], …] }
]
[
  { "metric": {"route": "/"}, "values": [[1763460720, "7.9"], …] },
  { "metric": {"route": "/checkout"}, "values": [[1763460720, "38.4"], …] }
]
[ { "metric": {"app": "myapp"}, "value": [1763460900, "14398"] }, { "metric": {"app": "myapp-edge"}, "value": [1763460900, "7210"] } ]

How to verify: The result of query 5 should be close to the error rate calculated in Prometheus by myapp_http_requests_total (about 1/20 of requests to /error in loadgen). Common errors: Query 6 misses by (route) or __error__="": the former makes fields such as trace_id into dimensions and creates too many series; the latter reports unwrap errors because of a few non-logfmt lines (such as gunicorn startup logs). Production use: Query 7 is the basis of Loki's cost allocation report.

Lab 4: compute RED from logs and write a log alert (about 7 minutes)

Rate and Errors: in Grafana Explore (Loki), run query 5 from the command list and switch to the Time series view; then in another split pane, query with Prometheus sum by (route) (rate(myapp_http_requests_total{status=~"5.."}[5m])) / sum by (route) (rate(myapp_http_requests_total[5m])), and compare the two curves.
Duration: run query 6 and compare it with histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket[5m]))) .

Logs compute an exact quantile (in ms), while a histogram computes an in-bucket interpolation (in s); the two are close but not identical. The log version must read every line, so it gets noticeably slower as the time range grows.

Write a Loki alert rule: load via the rules sidecar (label loki_rule, annotation specifying the tenant directory fake).
apiVersion: v1
kind: ConfigMap
metadata:
  name: myapp-log-rules
  namespace: observability
  labels:
    loki_rule: ""
  annotations:
    k8s-sidecar-target-directory: /rules/fake     # tenant is fake when auth_enabled=false
data:
  myapp-logs.yaml: |
    groups:
      - name: myapp-logs
        interval: 1m
        rules:
          - alert: MyappErrorLogsHigh
            expr: |
              sum by (app) (count_over_time({namespace="myapp"} |= "level=ERROR" | logfmt | level="ERROR" [5m])) > 5
            for: 2m
            labels:
              severity: warning
              namespace: myapp
            annotations:
              summary: "{{ $labels.app }} ERROR log lines in the last 5 minutes: {{ $value }}"
          - alert: MyappLogsAbsent
            expr: absent_over_time({namespace="myapp", app="myapp"}[10m])
            for: 5m
            labels: {severity: warning, namespace: myapp}
            annotations:
              summary: "myapp has produced no logs for 10 minutes (collection interrupted or app stopped)"
kubectl apply -f ~/promlab/part8/loki-rules.yaml
sleep 60
curl -s $L/loki/api/v1/rules | head -20
curl -s $L/prometheus/api/v1/rules | jq -c '.data.groups[].rules[] | {name, state, health}'
fake:
    - name: myapp-logs
      interval: 1m
      rules:
        - alert: MyappErrorLogsHigh
...
{"name":"MyappErrorLogsHigh","state":"inactive","health":"ok"}
{"name":"MyappLogsAbsent","state":"inactive","health":"ok"}
Trigger: send continuous requests to /error; after 2–3 minutes the alert appears in the kps Alertmanager.
kubectl -n myapp exec deploy/myapp-edge -- python -c "
import urllib.request as u
for i in range(30):
    try: u.urlopen('http://myapp:5000/error')
    except Exception: pass"
sleep 180
kubectl -n monitoring port-forward svc/alertmanager-operated 9093:9093 >/dev/null 2>&1 &
curl -s localhost:9093/api/v2/alerts | jq -c '.[] | select(.labels.alertname=="MyappErrorLogsHigh") | {labels: .labels.app, state: .status.state}'
{"labels":"myapp","state":"active"}

The sidecar annotation name, tenant directory layout and the chart's ruler storage config are inferred from the chart 21.4.0 template and have not been verified on a real cluster; if the rule does not load, check kubectl -n observability logs loki-0 -c loki-sc-rules (the sidecar container name depends on the actual deployment) and the ruler errors in the Loki logs. You can also use Grafana-managed alerts instead (Alerting → New alert rule → choose Loki as the data source), with the same effect.

Case 1: a “regex full-text search” brought Loki to its knees

Problem: Someone ran a 7-day query in Grafana against {cluster="prod"} with |~ ".*timeout.*", which scanned terabytes of chunks; querier memory spiked, and other teams' queries queued and timed out. Fix:① Set max_query_length,max_query_parallelism,query_timeout tenant limits; ② train users that “selectors must be precise and use |= substring filtering first, and query short ranges”; ③ turn common “statistical” queries into ruler recording rules and write their results to Prometheus.

Case 2: log alerts falsely fire en masse during deployments

Problem:“ERROR line count > 5 within 5 minutes” fires on every rolling deployment, because old Pods log connection-interrupted ERRORs when they shut down. Fix: change the alert expression to an error ratio (error lines / total lines) and add for: 5m; downgrade known shutdown-time errors to WARN. Principle: Log alerts must follow the same alert design principles as lesson 2: symptom-based, ratio-first, with a duration.

Case 3: detecting collection outages with absent_over_time

Problem: After an RBAC change, Alloy could no longer read logs, and no one noticed for two days that no new logs were showing up in Grafana. Fix: Add absent_over_time alerts for each critical application (MyappLogsAbsent in this lab), and also monitor the collector's own loki_write_dropped_entries_total. This matches the approach in lesson 7's absent(up) — silence is the most dangerous failure.

Common errors and fixes

parse error : queries require at least one regexp or equality matcher that does not have an empty-compatible value. For instance, app=~".*" does not meet this requirement, but app=~".+" will

Cause: The selector only has conditions that can match empty values. Fix: Add at least one equality matcher, for example {namespace="myapp"}.

maximum number of series (500) reached for a single query; consider reducing query cardinality …

Cause: The metric query has no aggregation, so high-cardinality parsed fields (trace_id, duration_ms) become dimensions. Fix: Add sum by (…),| keep … or | drop ….

Results show __error__="LogfmtParserErr" or unwrap reports SampleExtractionErr

Cause: Some lines are not logfmt (startup logs, stack traces), or the unwrapped field is not a number. Fix: Add | __error__="" after the parser to drop lines that fail to parse; first use a line filter to keep only lines in the target format.

Rule health=err: … rule evaluation failed … or the rule does not appear at all in /loki/api/v1/rules

Cause: LogQL syntax error, the rule file was not placed in the tenant directory (/rules/<tenant>/), or the ruler is not enabled. Diagnosis: First run the same expression in Explore; check the sidecar write path and the Loki logs.

Query is slow: query timed out, or the UI keeps spinning

Diagnosis: Grafana Query inspector's Stats (Loki returns totalBytesProcessed,totalLinesProcessed and similar statistics). Fix: Shorten the time range, add a precise selector, put line filters before parsers, avoid |~ ".*x.*" regexes wrapped in .* on both ends (use |= "x" instead).

Command-line exercises
1. Write a LogQL query: the number of requests per minute to the /checkout route in myapp (computed from logs).
sum(count_over_time({app="myapp-edge"} |= "route=/checkout" | logfmt | route="/checkout" [1m]))
2. Use logcli to export all myapp logs from the past hour that contain “timeout” (max 5000 lines) to a file.
logcli query --since=1h --limit=5000 --output=raw '{namespace="myapp"} |= "timeout"' > timeout.log

For larger exports, use --parallel-duration / --part-path-prefix sharding (see logcli query --help for parameters).

Scenario analysis
A third-party gateway outputs only logs, not metrics, and needs an alert for “5xx ratio above 2% for 5 minutes”. Design the solution and describe a long-term approach.

Short term: Loki ruler alert sum(rate({app="gateway"} | json | status >= 500 [5m])) / sum(rate({app="gateway"} | json | __error__="" [5m])) > 0.02,for: 5m. Performance: keep the selector precise and put a |= "\"status\":5" line filter early. Long term: use a ruler recording rule to remote write the ratio to Prometheus, or have the collector (Alloy stage.metrics / the Collector's count connector) generate counter metrics directly at collection time, so you can alert and build SLOs on native metrics.

Verified instructional videos

▶
How to query Grafana Loki with LogQL — Grafana
English · official LogQL introduction
▶
Grafana Loki Query Best Practices with LogQL (Loki Community Call December 2024) — Grafana
English · query performance best practices, corresponding to the performance rules in Figure 4-1

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: 10,000 log lines flow in from the left; the first gate (selector) only lets one application's stream through; the second gate (|= "status=5") sends most lines down the drain.
Narration: narrow the streams first, then use the cheapest string filter.
Shot 2 · 25–60s
Visual: the remaining lines are split into field cards by logfmt; cards with status ≥ 500 are picked out and finally stacked into two curves by rate and sum by.
Narration: parsing is done on only a few lines, and then the logs become metrics.
Shot 3 · 60–90s
Visual: the Loki ruler runs this query every minute; once the threshold is exceeded, an alert flies to Alertmanager.
Narration: logs can alert too, but SLO alerts should still be based on native metrics.
or score ≥ 70% on the quiz

Module 5 · distributed tracing basics and Grafana Tempo

28:00 – 35:00 · A trace is a tree of spans; the traceparent header passes “whose child am I” between services. Tempo stores data by trace_id, backed by object storage, and uses TraceQL and metrics-generator to make massive numbers of traces searchable and measurable
7 minutesTempo v3.1.1 · W3C Trace Context★★★★★
Learning objectives
  • Explain trace, span, parent / child, span kind (SERVER / CLIENT / INTERNAL / PRODUCER / CONSUMER), attributes, events, status and resource.
  • Walk through the W3C traceparent (version-traceid-parentid-flags) and tracestate, explaining how context propagation works within a process and across processes, and which steps can “break the chain”.
  • Compare head sampling (parentbased_traceidratio) with tail sampling (Collector tail_sampling) trade-offs.
  • Describe the Tempo 3 architecture (distributor, Kafka, live-store, block-builder, backend scheduler / worker, querier, query-frontend, metrics-generator); write TraceQL searches and TraceQL metrics; read the RED metrics and service graph produced by metrics-generator.
Prerequisites: Module 1's correlation model; basic HTTP header concepts. Importance:★★★★★

What: the tracing data model

ConceptDescriptionExample in this lesson
TraceAn end-to-end request, identified by a 16-byte (32 hex characters) trace ID6e0c63257de34c92bf9efcd03927272e
SpanOne operation: name, start time, duration, 8-byte span ID, parent span ID, kind, attributes, events, statusGET /checkout (SERVER),price.calculate (INTERNAL),GET (CLIENT),INCR (CLIENT)
ResourceAttributes of the entity that produced the span, shared across the whole processservice.name=myapp-edge,k8s.pod.name=…
StatusUNSET / OK / ERROR; HTTP server 5xx is set to ERROR by instrumentation/error 's SERVER span
Span event / linkPoint-in-time events within a span (such as exceptions) / links to other traces (such as batch jobs and message queues)Exception stack traces are recorded as exception events

W3C Trace Context: traceparent

traceparent: 00-6e0c63257de34c92bf9efcd03927272e-b7ad6b7169203331-01
             │  │                                │                └─ trace-flags: 01 = sampled
             │  │                                └─ parent-id: the span that issued this request (8 bytes)
             │  └─ trace-id: 16 bytes, unchanged across the whole chain
             └─ version: 00
tracestate: vendorname=opaque-value,ot=th:8     (optional: vendor / sampling-related extra state)

myapp-edge's requests instrumentation creates a CLIENT span before sending the HTTP request, and writes the ID of this CLIENT span as parent-id into traceparent; myapp's Flask instrumentation reads the request header and creates a SERVER span whose parent is the other side's CLIENT span. Within a process, propagation relies on Context (Python's contextvars), so manual spans and Redis spans automatically attach under the current span.

Why: why propagation breaks

  • Middleware / gateway does not forward traceparent (old Nginx configs, API gateways, Service Mesh default header lists).
  • The two ends use different propagation formats (B3 vs W3C); OTel defaults to OTEL_PROPAGATORS=tracecontext,baggage.
  • Context is lost at async boundaries: thread pools, Celery / message queues,asyncio tasks without context (requires matching instrumentation or manual injection / extraction).
  • The downstream service is not instrumented, or it creates a new trace on its own (for example, instrumentation initialization fails before fork).

How: sampling

Head samplingTail sampling
Where the decision is madeAt trace start, in the SDK (the root service decides; downstream follows the sampled flag)After the trace completes, in the Collector (waiting decision_wait)
ConfigurationOTEL_TRACES_SAMPLER=parentbased_traceidratio,OTEL_TRACES_SAMPLER_ARG=0.1tail_sampling Policies: errors, latency, attributes, probability…
ProsZero extra cost; dropped spans are never generated or transmittedcan “keep all errors and slow requests”
ConsBlind selection: error requests can also be droppedThe Collector must buffer complete traces; spans of the same trace must be routed to the same instance (loadbalancing exporter distributes by trace ID); memory and operational costs are high

How: Tempo 3 architecture

  • Write path: the distributor receives OTLP / Jaeger / Zipkin, validates, shards by trace ID and writes to a Kafka-compatible queue (microservices mode); live-store (replacing the 2.x ingester) keeps recent data in memory and a local WAL, queryable within seconds; block-builder compacts data into Parquet blocks (vParquet) written to object storage. Monolithic mode has no Kafka; the distributor hands data directly in-process to live-store and metrics-generator, and live-store writes the blocks.
  • Background: backend scheduler + backend worker replace the compactor, handling block compaction and retention (block_retention, set in this lesson's chart as tempo.retention: 48h).
  • Query path: the query-frontend splits queries into jobs (recent data → live-store, history → object storage); queriers execute them and merge results; a lookup by trace ID only needs to locate the block, while TraceQL search must scan Parquet columns.
  • metrics-generator (Optional): derive RED metrics from spans (span-metrics) and a service graph (service-graphs), written to Prometheus / Mimir via remote write. TraceQL metrics are GA in 3.0.

When: TraceQL at a glance

NeedTraceQL
Error spans for a service{ resource.service.name = "myapp" && status = error }
Slow Redis calls{ span.db.system = "redis" && duration > 100ms }
Whole trace longer than 1 second{ trace:duration > 1s }
Structural query: myapp errors downstream of edge{ resource.service.name = "myapp-edge" } >> { resource.service.name = "myapp" && status = error }
TraceQL metrics: error rate per service{ status = error } | rate() by (resource.service.name)
TraceQL metrics: P95{ resource.service.name = "myapp" && kind = server } | quantile_over_time(duration, .95) by (span:name)
Common misconceptions① “Tempo generates the trace_id” — it is generated by the root service's SDK; Tempo just stores by it. ② “Span metrics are still accurate after 10% sampling” — metrics-generator only sees sampled spans, so counts run low (Tempo 3 added span_multiplier_key and an option to compensate by reading the sampling threshold from tracestate); a safer approach is to generate RED metrics before sampling (for example, with the Collector's spanmetrics connector placed ahead of tail_sampling). ③ “Tempo has label indexes, so search is fast” — Tempo mainly locates by trace ID; TraceQL search is a columnar scan, and the shorter the time range, the faster. ④ “Tempo 3 still has ingester / compactor” — both were removed in 3.0; old configs must be migrated with tempo-cli migrate config migration.

A trace's span tree and waterfall view

trace 6e0c…272e · 0ms ———————————————————————————————————— 42ms myapp-edge · GET /checkout (SERVER) └ price.calculate (INTERNAL) └ GET (CLIENT) → traceparent myapp · GET / (SERVER) └ INCR (CLIENT, db.system=redis) Each row is a span; indentation = parent-child relationship; bar position = start time, bar length = duration. Cross-service parent-child relationships are established via traceparent. The gap between a CLIENT span and the downstream SERVER span = network + queuing time (about 0.7 ms here).
Figure 5-1: Tempo's trace view in Grafana is exactly this kind of waterfall chart

Tempo 3 write and query paths

CollectorOTLP distributorSharded by trace ID KafkaMicroservices mode only live-storeRecent · memory + WAL block-builderParquet blocks metrics-generatorRED · service graph Object storageS3 · GCS · Blob Prometheusremote write query-frontend+ querierTraceQL Monolithic mode (this lesson): no Kafka or block-builder; the distributor hands data in-process to live-store (which writes the blocks) and metrics-generator
Figure 5-2: Tempo 3: Kafka handles durability, so it can run with replication factor 1; the read path queries live-store for recent data and object storage for history

Core animation: traceparent propagation across services

Step through: loadgen sends a request (no traceparent) → myapp-edge generates a trace ID and root span → manual span → CLIENT span injects traceparent → myapp extracts and creates a child span → Redis span → each exports to the Collector → Tempo assembles them into one tree by trace ID. You can toggle “broken chain” mode (the middle gateway drops the request header).

loadgen / gateway
curl /checkoutclient
(optional) gatewayproxy
myapp-edge
SERVER GET /checkout—
INTERNAL price.calculate—
CLIENT GET → myapp—
myapp
SERVER GET /—
CLIENT INCR (redis)—
Tempo: assemble by trace ID—
Click “Play” or “Next”.
$ # HTTP headers and span IDs are shown here

Tempo HTTP API and TraceQL

APIPurpose
GET /api/search?q=<TraceQL>&start=&end=&limit=TraceQL search; returns trace summaries (traceID, rootServiceName, rootTraceName, durationMs, matched spanSet)
GET /api/v2/traces/<traceID>Get the full trace by ID (OTLP JSON structure)
GET /api/v2/search/tags,/api/v2/search/tag/<tag>/valuesavailable attribute names and values (autocomplete)
GET /api/metrics/query_range?q=<TraceQL metrics>TraceQL metrics (GA in 3.0)
GET /ready,/status/config,/metricsreadiness, effective config, self-monitoring metrics
source ~/promlab/part8/env.sh
# 1) error traces: myapp's /error
curl -s -G $T/api/search --data-urlencode 'q={ resource.service.name = "myapp" && status = error }' --data-urlencode limit=3 \
  | jq -c '.traces[] | {traceID, rootServiceName, rootTraceName, durationMs}'
# 2) structural query: traces entering from edge that contain slow Redis calls in myapp
curl -s -G $T/api/search --data-urlencode 'q={ resource.service.name = "myapp-edge" } >> { span.db.system = "redis" && duration > 5ms }' \
  --data-urlencode limit=3 | jq -c '.traces[] | {traceID, durationMs}'
# 3) attribute names and values (check real attributes before writing TraceQL)
curl -s $T/api/v2/search/tags | jq -c '.scopes[] | {name, n: (.tags | length)}'
curl -s $T/api/v2/search/tag/resource.service.name/values | jq -c '[.tagValues[].value]'
# 4) TraceQL metrics: error spans per second per service (last 15 minutes, 1-minute step)
curl -s -G $T/api/metrics/query_range --data-urlencode 'q={ status = error } | rate() by (resource.service.name)' \
  --data-urlencode "start=$(date -d '-15 min' +%s)" --data-urlencode "end=$(date +%s)" --data-urlencode step=60s \
  | jq -c '.series[] | {labels: [.labels[].value.stringValue], last: .samples[-1].value}'
# 5) RED and service graph that metrics-generator writes to Prometheus
pq 'sum by (service, span_name) (rate(traces_spanmetrics_calls_total{span_kind="SPAN_KIND_SERVER"}[5m]))'
pq 'sum by (client, server) (rate(traces_service_graph_request_total[5m]))'
{"traceID":"9a2f…","rootServiceName":"myapp","rootTraceName":"GET /error","durationMs":2}
{"traceID":"77c1…","durationMs":44}
{"name":"span","n":18}
{"name":"resource","n":14}
["myapp","myapp-edge"]
{"labels":["myapp"],"last":0.1}
[{"service":"myapp","span_name":"GET /"},"5.9"]
[{"service":"myapp-edge","span_name":"GET /checkout"},"1.9"]
[{"client":"myapp-edge","server":"myapp"},"1.9"]
[{"client":"myapp","server":"redis"},"5.9"]

How to verify: The service graph should show at least one edge myapp-edge → myapp; whether Redis appears as a “virtual node” depends on the peer attributes of CLIENT spans (Tempo uses by default peer.service,db.name,db.system etc., depending on the actual version). Common errors: In TraceQL, the &&,>> must be URL-encoded in the URL (using --data-urlencode); attributes must carry a scope prefix (span. / resource.) or use . to match any scope. Returned API fields depend on the actual Tempo 3.1 behavior. Production use: Query 5 is how you get a RED dashboard without changing code.

Lab 5: follow a cross-service trace, then break it yourself (about 7 minutes)

In Grafana, check: Explore → Tempo → Search, and choose myapp-edge as the Service Name, open a trace, confirm 5 spans and 2 services, then switch to the “Service Graph” tab to see the node graph.
Manually send a request with traceparent: we act as the “upstream” ourselves, specify a trace ID, then look it up in Tempo by that ID.
TID=$(openssl rand -hex 16); PID=$(openssl rand -hex 8)
kubectl -n myapp exec deploy/myapp-edge -- python -c "
import urllib.request as u
r = u.Request('http://localhost:5000/checkout', headers={'traceparent': '00-$TID-$PID-01'})
print(u.urlopen(r).read().decode())"
sleep 5; curl -s $T/api/v2/traces/$TID | jq -r '[.trace.resourceSpans[].scopeSpans[].spans[] | .name] | join(" | ")'
checkout ok items=3
GET /checkout | price.calculate | GET | GET / | INCR

The root span GET /checkout 's parentSpanId is the fake parent ID we forged $PID— it does not exist in Tempo. Grafana shows “root span not yet received / missing parent”, which is what it looks like when the upstream never exported its span.

Sampling flag: change flags to 00 and send again (parentbased_always_on ; the sampler respects the parent's “not sampled” decision).
TID2=$(openssl rand -hex 16)
kubectl -n myapp exec deploy/myapp-edge -- python -c "
import urllib.request as u
u.urlopen(u.Request('http://localhost:5000/checkout', headers={'traceparent': '00-$TID2-$(openssl rand -hex 8)-00'}))"
sleep 5; curl -s -o /dev/null -w '%{http_code}\n' $T/api/v2/traces/$TID2
lq "{namespace=\"myapp\"} | trace_id=\"$TID2\"" 5m | head -2
404
{"app":"myapp-edge",…}
["…","ts=… level=INFO service=myapp-edge trace_id=… msg=request method=GET route=/checkout status=200 …"]

Not in Tempo (404), but the trace_id still appears in the logs — this corresponds to the “trace_id in logs but Tempo can't find it” case in module 1 troubleshooting.

Broken chain: insert an nginx between myapp-edge and myapp that drops the trace header, to simulate “gateway does not forward traceparent”.
apiVersion: v1
kind: ConfigMap
metadata: {name: stripper, namespace: myapp}
data:
  default.conf: |
    server {
      listen 8080;
      location / {
        proxy_set_header traceparent "";   # simulates a gateway that drops the trace header
        proxy_set_header tracestate "";
        proxy_pass http://myapp:5000;
      }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: stripper, namespace: myapp}
spec:
  selector: {matchLabels: {app: stripper}}
  template:
    metadata: {labels: {app: stripper}}
    spec:
      containers:
        - name: nginx
          image: nginx:1.29-alpine
          volumeMounts: [{name: conf, mountPath: /etc/nginx/conf.d}]
      volumes: [{name: conf, configMap: {name: stripper}}]
---
apiVersion: v1
kind: Service
metadata: {name: stripper, namespace: myapp}
spec:
  selector: {app: stripper}
  ports: [{port: 8080, targetPort: 8080}]
kubectl apply -f ~/promlab/part8/stripper.yaml && kubectl -n myapp rollout status deploy/stripper
kubectl -n myapp set env deploy/myapp-edge UPSTREAM_URL=http://stripper:8080 && kubectl -n myapp rollout status deploy/myapp-edge
sleep 30
curl -s -G $T/api/search --data-urlencode 'q={ resource.service.name = "myapp-edge" } >> { resource.service.name = "myapp" }' --data-urlencode 'start='$(date -d '-20 sec' +%s) | jq '.traces | length'
curl -s -G $T/api/search --data-urlencode 'q={ resource.service.name = "myapp" && kind = server }' --data-urlencode limit=2 | jq -c '.traces[] | {rootServiceName, rootTraceName}'
0
{"rootServiceName":"myapp","rootTraceName":"GET /"}

edge and myapp become two unconnected traces: myapp becomes a root by itself. In the service graph, the myapp-edge → myapp edge disappears (only edge's CLIENT span pointing to the stripper's virtual node remains, or nothing is shown). In nginx, proxy_set_header X "" means the header is not sent upstream. Use an image tag that can be pulled.

Reset:
kubectl -n myapp set env deploy/myapp-edge UPSTREAM_URL=http://myapp.myapp.svc:5000
kubectl delete -f ~/promlab/part8/stripper.yaml

Case 1: Ingress splits a trace in two

Problem: All traces start at the backend service; the Ingress / gateway segment is invisible, and the frontend cannot be correlated. Cause: The gateway does not have the OpenTelemetry module enabled and only forwards B3 headers. Fix: Enable OTel tracing in ingress-nginx / Envoy Gateway / Istio and use W3C consistently tracecontext; configure both in the SDK OTEL_PROPAGATORS=tracecontext,baggage,b3multi during the transition; remove B3 once migration is complete.

Case 2: upgrading Tempo 2 → 3

Problem: The team runs tempo-distributed 2.x (ingester + compactor). Fix: Follow the official migration guide: first use tempo-cli migrate config to convert the config; prepare a Kafka-compatible queue (required for microservices mode); migrate older vParquet blocks first; the OpenCensus receiver is removed in 3.0, so switch related clients to OTLP. Takeaway: Because Kafka handles durability, it can run with replication factor 1; live-store makes new data queryable within seconds.

Case 3: the service graph reveals a “shadow dependency”

Problem: A database maintenance window caused an unexpected outage. Finding: The metrics-generator service graph showed that a “read-only” reporting service was actually calling the orders database thousands of times per minute. Fix: Make the service graph part of architecture reviews; set alerts on traces_service_graph_request_failed_total as a supplementary signal of dependency health.

Common errors and fixes

Grafana shows “missing span” / root span missing for a trace

Cause: The upstream service did not export its spans (not instrumented, dropped by sampling, or export failed), or the spans have not been written yet (live-store has not received them). Diagnosis: Check the root span's parentSpanId; check whether the upstream service appears in Tempo.

The same request appears as two traces in Tempo

Cause: Context propagation is broken: the gateway drops headers, propagation formats are inconsistent, or Context is lost at async boundaries. Diagnosis: Print the received traceparent downstream (or compare with the nginx method from lab 5). Fix: Standardize on W3C, enable header forwarding on the gateway, add instrumentation or manual injection for queues / thread pools.

Tempo search returns nothing, but lookup by trace ID works

Cause: Attribute name is wrong (old vs new semantic conventions: http.status_code vs http.response.status_code), scope prefix is wrong, or the time range does not cover the data. Fix: Use /api/v2/search/tags to check real attribute names; Python instrumentation can use OTEL_SEMCONV_STABILITY_OPT_IN=http to switch to the stable HTTP conventions (refer to the docs for the matching instrumentation version).

traces_spanmetrics_* metrics do not exist

Cause: metrics-generator is not enabled, processors are not turned on in overrides, or Prometheus has not enabled remote write receiving (remote write returns 404 in Tempo logs). Diagnosis:curl $T/status/config | grep -A5 metrics_generator; Tempo logs; kps' enableRemoteWriteReceiver.

Collector / SDK reports TRACE_TOO_LARGE, or Tempo logs trace_too_large

Cause: A single trace exceeds max_bytes_per_trace (for example, a batch job puts tens of thousands of operations into one trace). Fix: Split the trace (linking the parts with span links), or carefully raise the limit.

Command-line exercises
1. Construct a valid traceparent and explain each part.
echo "00-$(openssl rand -hex 16)-$(openssl rand -hex 8)-01"

Version 00; a 32-hex-character trace-id; a 16-hex-character parent-id; flags 01 means sampled. An all-zero trace-id / parent-id is invalid.

2. Write a TraceQL query: find SERVER spans in myapp that take longer than 200 ms, and compute P99 per route (TraceQL metrics).
{ resource.service.name = "myapp" && kind = server && duration > 200ms }
{ resource.service.name = "myapp" && kind = server } | quantile_over_time(duration, .99) by (span.http.route)
Scenario analysis
Your system produces 2 billion spans per day, and the budget only allows storing 10%. Product requires that “all error requests and slow requests above P99 must be findable”, and SRE requires accurate RED metrics. How would you design this?

① At the first Collector tier, use spanmetrics connector (or have Tempo metrics-generator receive the full stream) to generate RED and the service graph from 100% of spans, ensuring accurate metrics; ② in the second tier (after a trace-ID consistent-hash loadbalancing exporter) do tail sampling: status_code: ERROR keep all latency error traces, keep everything above the latency threshold, and keep the rest with probabilistic probabilistic sampling at about 5–8%; ③ keep the SDK sampler at parentbased_always_on (or a very high head sampling rate) so tail sampling has complete data, weighing network cost; ④ retain Tempo data for 7–14 days; ⑤ monitor the Collector's otelcol_processor_tail_sampling_* metrics and memory; ⑥ keep trace_id in logs, so individual requests from dropped traces can still be located through logs.

Verified instructional videos

▶
What's New in Tempo 3.0 — Grafana
English · official introduction to the new Tempo 3 architecture (corresponding to Figure 5-2)
▶
What's New in Tempo 3.1 — Grafana
English · the 3.1 series used in this lesson
▶
Distributed Tracing Explained | OpenTelemetry Spans & Context — SysMinu
English · span and context propagation basics
▶
Traces to metrics: Ad-hoc RED metrics in Grafana Tempo — Grafana
English · deriving RED metrics from traces

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a traceparent tag is stuck on an HTTP request envelope; the four number segments are enlarged one by one to explain them.
Narration: the trace ID stays the same throughout; at each hop, the parent ID is replaced by the previous span.
Shot 2 · 25–60s
Visual: the envelope passes through a gateway, the tag is torn off, the downstream service generates a new trace ID, and the waterfall splits into two segments.
Narration: if any hop drops the request header, the trace breaks.
Shot 3 · 60–90s
Visual: spans flow into Tempo; one part becomes Parquet blocks in object storage, and another part is turned by metrics-generator into RED curves and a service graph.
Narration: Tempo stores traces and can also turn traces into metrics.
or score ≥ 70% on the quiz

Module 6 · OpenTelemetry instrumentation and the Collector pipeline

35:00 – 42:00 · Auto-instrumentation gives you 80% of the spans; manual instrumentation adds business semantics. The SDK handles span creation and the first sampling decision; the Collector handles enrichment, tail sampling and routing. Where sampling happens determines how accurate the metrics are and how expensive it is.
7 minutesOTel Python 1.45.2 / 0.66b2★★★★
Learning objectives
  • Compare three instrumentation approaches: zero-code (opentelemetry-instrument / Operator injection), code-level instrumentation libraries (myapp in this lesson), and purely manual spans; know the initialization pitfalls of pre-fork servers such as gunicorn.
  • Use OTEL_* environment variables to configure the service name, resource attributes, export endpoint and protocol, sampler and propagator; write manual spans, attributes, events and exception recording.
  • Configure tail_sampling in the Collector, understand its effect on RED metrics, and know that multi-replica tail sampling requires routing by trace ID (loadbalancing exporter).
  • Monitor the Collector itself: received, refused, export failures, queues.
Prerequisites: Module 5 sampling concepts; OTLP from lesson 6, module 6. Importance:★★★★

What: three instrumentation approaches

ApproachHow (Python)ProsNotes
Zero-code (automatic)pip install opentelemetry-distro opentelemetry-exporter-otlp → opentelemetry-bootstrap -a install → opentelemetry-instrument gunicorn app:app; or the OTel Operator's Instrumentation CR auto-injectionNo code changes; covers Flask, requests, redis, database drivers, etc.Pre-fork servers (gunicorn with multiple workers): background threads stop working after fork; the official docs recommend initializing the SDK in post_fork hook; it cannot express business semantics
Code-level instrumentation libraries (this lesson)Create TracerProvider, call FlaskInstrumentor().instrument_app(app) etc.Initialization timing is controllable (when gunicorn does not use --preload , each worker imports the app after fork, which is naturally safe)Dependency versions must match the SDK (SDK 1.45.x ↔ contrib 0.66bX)
Manual spanswith tracer.start_as_current_span("price.calculate") as span: span.set_attribute(…)Express business steps and attributes (cart item count, tenant, order type)Attribute names follow semantic conventions or add an app prefix (app.); do not include passwords or personal information

Common environment variables (SDK specification, common to all languages)

VariableValue in this lessonDescription
OTEL_SERVICE_NAMEmyapp / myapp-edgeThe most important resource attribute; the primary key linking the three pillars
OTEL_RESOURCE_ATTRIBUTESservice.namespace=shop-demo,deployment.environment.name=lab,k8s.pod.ip=…Comma-separated key-value pairs
OTEL_EXPORTER_OTLP_ENDPOINT / _PROTOCOLhttp://otelcol…:4317 / grpcFor the HTTP protocol, port 4318; signal paths (/v1/traces) are appended automatically
OTEL_TRACES_SAMPLER / _ARGparentbased_always_onCommon in production parentbased_traceidratio + 0.1
OTEL_PROPAGATORSDefault tracecontext,baggageAdd when Zipkin compatibility is needed b3multi
OTEL_PYTHON_FLASK_EXCLUDED_URLShealthz,metricsHealth checks and scrapes produce no spans, saving cost
OTEL_PYTHON_LOG_CORRELATION(used with the zero-code approach) trueLets logging instrumentation inject trace context; this lesson calls it in code LoggingInstrumentor().instrument()

Why: where sampling happens

RED metrics (request rate, error rate, latency distribution) must be based on full data; otherwise 10% sampling makes the request rate 10× too low. Options: ① native application metrics (myapp's /metrics, the most reliable); ② the Collector's spanmetrics connector placed before sampling; ③ Tempo metrics-generator receives the full span stream (in which case sampling can only happen after Tempo, which is unrealistic), or uses Tempo 3's span multiplier to compensate. In this lesson's configuration, metrics-generator sits after the Collector, so the lab shows you first-hand how tail sampling makes traces_spanmetrics_calls_total come out low.

How: how tail sampling works

  • tail_sampling Buffer spans by trace ID, waiting decision_wait (e.g. 10s), then evaluate policies on the whole trace: if any one says “sample”, keep it (others: and,composite,drop and similar composite policies).
  • Common policies: status_code (ERROR),latency (threshold_ms),probabilistic (percentage),string_attribute (e.g. VIP tenants),rate_limiting.
  • With multiple replicas, spans of the same trace must reach the same replica: put a tier in front with a loadbalancing exporter (routing_key: traceID) Collectors.
  • Key parameters: num_traces (maximum number of traces held in memory),expected_new_traces_per_sec; spans that arrive after a decision are handled according to the existing decision or dropped.

When: Collector deployment forms

FormResponsibilities
Agent (DaemonSet / sidecar)Receive locally,k8sattributes,memory_limiter, batch; filelog reads logs
Gateway (Deployment, horizontally scalable)Tail sampling, spanmetrics, unified credentials and routing, multi-backend export
This lessonA single Deployment serves both roles (lab scale)
Common misconceptions① “Installing auto-instrumentation gives you a complete trace” — async jobs, homegrown RPC and message queues often need extra instrumentation; business attributes must be added manually. ② “10% head sampling + tail sampling that keeps errors = all errors visible” — traces dropped by head sampling never reach the Collector; for tail sampling to work, the head sampling rate must be high enough. ③ “OTLP gRPC and HTTP use the same port” — gRPC is 4317, HTTP is 4318; a protocol/port mismatch is the most common cause of export failure. ④ “Putting user_id in span attributes is fine” — it works in Tempo (attributes are not index labels), but does it enter spanmetrics dimensions? Only if it is configured in dimensions does it — never configure it.

SDK internals: a span from creation to export

Tracerstart_span SamplerHead sampling decision Span (Context)Attributes · events · status BatchSpanProcessorQueue 2048 · background thread OTLPSpanExportergRPC 4317 → Collector Not sampled: still generates trace_id and context(still propagates and is written to logs), but not exported pre-fork: background thread after forkmust be restarted in each worker The synchronous path (request thread) only does in-memory work; network export is batched by the background thread
Figure 6-1: SDK export is asynchronous and batched; when the queue is full, spans are dropped instead of blocking requests

How the two sampling positions affect RED metrics

A: compute metrics first, then sample (recommended) 100% span spanmetrics connector tail_sampling Tempo (~10%) RED accurate ✓ B: sample first, then Tempo computes metrics (this lesson's default topology + tail sampling enabled in the lab) 100% span tail_sampling Tempo (~10%) metrics-generator Request rate too low ✗
Figure 6-2: metrics must be generated before sampling; otherwise they are only useful for “relative proportions” rather than absolute values

Interactive: sampling decision simulator (head vs tail)

Simulates 1000 traces (about 3% errors, about 5% slower than 300 ms). Adjust the head sampling rate and tail policies, and observe how many error / slow traces are kept, how much is stored, and the RED request-rate error after sampling.




After adjusting parameters, click “Re-simulate”. Each small square represents 10 traces.

Common instrumentation and Collector commands

# zero-code instrumentation (an alternative approach, for comparison; this lesson's myapp uses in-code initialization)
pip install opentelemetry-distro==0.66b2 opentelemetry-exporter-otlp==1.45.2
opentelemetry-bootstrap -a requirements      # list instrumentation packages that should be installed for detected libraries
opentelemetry-bootstrap -a install           # install directly
OTEL_SERVICE_NAME=myapp OTEL_TRACES_EXPORTER=otlp OTEL_METRICS_EXPORTER=none OTEL_LOGS_EXPORTER=none \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 OTEL_PYTHON_LOG_CORRELATION=true \
  opentelemetry-instrument gunicorn -w 1 --threads 8 -b 0.0.0.0:5000 app:app

# debugging: print spans to the console instead of exporting
OTEL_TRACES_EXPORTER=console opentelemetry-instrument flask --app app run
# manual instrumentation snippet: attributes, events, exceptions, status
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer("myapp")

with tracer.start_as_current_span("payment.charge", kind=trace.SpanKind.CLIENT) as span:
    span.set_attribute("app.payment.provider", "demo")
    span.add_event("retry", {"attempt": 2})
    try:
        charge()
    except TimeoutError as e:
        span.record_exception(e)                     # record as an exception event (with stack trace)
        span.set_status(Status(StatusCode.ERROR, "provider timeout"))
        raise
# Collector: effective config, self-monitoring, export failures
kubectl -n observability get cm otelcol-opentelemetry-collector -o jsonpath='{.data.relay}' | head -60
kubectl -n observability port-forward deploy/otelcol-opentelemetry-collector 8888:8888 >/dev/null 2>&1 &
curl -s localhost:8888/metrics | grep -E '^otelcol_(receiver_(accepted|refused)_spans|exporter_(sent|send_failed)_spans|exporter_queue_size|processor_tail_sampling)' | sort | head -20
otelcol_exporter_queue_size{exporter="otlp_grpc/tempo",…} 0
otelcol_exporter_send_failed_spans_total{exporter="otlp_grpc/tempo",…} 0
otelcol_exporter_sent_spans_total{exporter="otlp_grpc/tempo",…} 241830
otelcol_receiver_accepted_spans_total{receiver="otlp",transport="grpc",…} 241830
otelcol_receiver_refused_spans_total{receiver="otlp",transport="grpc",…} 0

How to verify: accepted and sent are equal; failed and refused are 0. Common errors: ConfigMap key names generated by the chart (relay) depend on the actual output; Collector internal metrics have been renamed in some versions (adding _total a suffix, etc.), so rely on the /metrics output. Production use: Create a ServiceMonitor for the Collector (the chart supports serviceMonitor.enabled) and alert on send_failed and refused.

Lab 6: effect of head vs. tail sampling on RED metrics (about 7 minutes)

Baseline: record the three request rates (they should be close).
source ~/promlab/part8/env.sh
pq 'sum(rate(myapp_http_requests_total{route="/"}[2m]))'                                   # app-native metric
pq 'sum(rate(traces_spanmetrics_calls_total{service="myapp",span_kind="SPAN_KIND_SERVER"}[2m]))'  # derived from Tempo
lq 'sum(rate({app="myapp"} |= "route=/ " [2m]))' 5m                                         # derived from logs
[{},"5.92"]
[{},"5.95"]
{}
["…","5.90"]
Head sampling 20%: change only the root service myapp-edge (myapp's parentbased_* spans will follow the parent's decision; requests from loadgen straight to myapp still get 100%, because myapp is itself the root and its sampler is always_on).
kubectl -n myapp set env deploy/myapp-edge OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.2
kubectl -n myapp rollout status deploy/myapp-edge; sleep 180
pq 'sum by (service) (rate(traces_spanmetrics_calls_total{span_name="GET /checkout"}[2m]))'
pq 'sum(rate(myapp_http_requests_total{route="/checkout"}[2m]))'
[{"service":"myapp-edge"},"0.39"]
[{},"1.96"]

Native metrics are unaffected; span metrics drop to about 20%. Note that myapp-edge also exposes myapp_http_requests_total (same image), and the lesson 5 ServiceMonitor only selects the Service myapp; to scrape edge metrics, add the same ServiceMonitor to the myapp-edge Service. The native metric numbers above assume you have done this; otherwise estimate from loadgen's request rate.

Reset head sampling and move to tail sampling in the Collector:
config:
  processors:
    tail_sampling:
      decision_wait: 10s
      num_traces: 20000
      expected_new_traces_per_sec: 50
      policies:
        - {name: keep-errors, type: status_code, status_code: {status_codes: [ERROR]}}
        - {name: keep-slow, type: latency, latency: {threshold_ms: 100}}
        - {name: sample-rest, type: probabilistic, probabilistic: {sampling_percentage: 10}}
  service:
    pipelines:
      traces:
        processors: [memory_limiter, k8sattributes, resource/cluster, tail_sampling, batch]
kubectl -n myapp set env deploy/myapp-edge OTEL_TRACES_SAMPLER=parentbased_always_on OTEL_TRACES_SAMPLER_ARG-
cd ~/promlab/part8
helm upgrade otelcol open-telemetry/opentelemetry-collector --version 0.179.1 -n observability -f otelcol-values.yaml -f otelcol-tail.yaml
kubectl -n observability rollout status deploy/otelcol-opentelemetry-collector
~/promlab/part8/redis-lag.sh 60 &        # generate a batch of slow requests
sleep 180
pq 'sum by (service) (rate(traces_spanmetrics_calls_total{span_kind="SPAN_KIND_SERVER"}[2m]))'
pq 'sum by (service) (rate(traces_spanmetrics_calls_total{span_kind="SPAN_KIND_SERVER",status_code="STATUS_CODE_ERROR"}[2m]))'
curl -s localhost:8888/metrics | grep -E '^otelcol_processor_tail_sampling_(count_traces_sampled|sampling_decision)' | head
[{"service":"myapp"},"1.31"]
[{"service":"myapp-edge"},"0.52"]
[{"service":"myapp"},"0.10"]
otelcol_processor_tail_sampling_count_traces_sampled_total{policy="keep-errors",sampled="true",…} 61
...

The overall request rate is noticeably lower (only "10% + all slow + all errors" remain), but the error rate barely changes— all error traces are kept. This is case B in Figure 6-2. For accurate RED, use the Collector's spanmetrics connector placed before tail_sampling (left as an exercise).

Reset:
helm upgrade otelcol open-telemetry/opentelemetry-collector --version 0.179.1 -n observability -f otelcol-values.yaml

Case 1: traces appear intermittently under gunicorn with multiple workers

Problem: A Flask service is started with opentelemetry-instrument gunicorn --preload -w 4 , and only some workers export spans. Cause: The SDK is initialized in the master process,BatchSpanProcessor 's background thread is not copied by fork. Fix: Remove --preload or in gunicorn's post_fork hook, initialize TracerProvider (see the OTel Python docs “Working With Fork Process Models”). The myapp in this lesson does not use --preload, and it initializes at module top level, so each worker initializes on its own.

Case 2: tail-sampling Collector memory spikes

Problem: During traffic peaks the tail-sampling Collector runs out of memory (OOM) and all traces are lost. Cause:decision_wait: 60s,num_traces are too large, so memory holds several million traces at once. Fix:decision_wait Lower it to 10–15s (just enough to cover the P99.9 trace duration); memory_limiter put it first; scale out horizontally by sharding on trace ID; monitor otelcol_processor_tail_sampling_* and process memory.

Case 3: standardize zero-code instrumentation with the OTel Operator

Fix: The platform team deploys the OpenTelemetry Operator (chart open-telemetry/opentelemetry-operator 0.129.1, 2026-11-17), creates Instrumentation resources; app teams only add an annotation to their Pod instrumentation.opentelemetry.io/inject-python: "true". Trade-offs: Fast to roll out and consistent in version, but dependencies injected by init containers may conflict with app dependencies, and the pre-fork issue still needs attention.

Common errors and fixes

App log: Failed to export traces to …:4317, error code: StatusCode.UNAVAILABLE

Cause: Collector unreachable, wrong DNS name, protocol and port mismatch (HTTP sent to 4317 or gRPC sent to 4318). Diagnosis:kubectl -n myapp exec deploy/myapp -- env | grep OTEL_; from inside the Pod nc -zv test the port.

Transient error StatusCode.RESOURCE_EXHAUSTED encountered while exporting traces

Cause: The Collector's memory_limiter is rejecting data (memory near its limit). Fix: Scale out the Collector, raise the memory limit and limit_percentage, and check whether downstream export is blocked and causing queue backlog.

No k8s.* attributes in spans

Cause: See module 3: k8sattributes not in the traces pipeline, no RBAC, or the source IP is not the Pod IP after a proxy. Fix: Enable the preset; include k8s.pod.ip in the resource attributes.

trace_id=0 (all zeros) in logs

Cause: Logs are printed in a context with no active span (startup logs, background threads), or LoggingInstrumentor is called after basicConfig, so the format fields are missing. Fix: Print request-related logs during request handling; make sure instrument() is configured before the format (the order used in this lesson's app.py).

Collector startup warning: pipeline combines the batch processor with exporterhelper batching

Cause: A check added in v0.165: the same pipeline uses the batch processor and also enables sending_queue::batch in the exporter. Fix: Pick one; for new deployments consider the exporter's built-in batching or the queue_batch processor (beta), per the official migration RFC.

Command-line tasks
1. Change myapp's head sampling to 25%, and make sure downstream services follow the upstream decision.
kubectl -n myapp set env deploy/myapp OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.25
2. Write a tail_sampling policy that keeps app.tenant all traces for vip.
- name: keep-vip
  type: string_attribute
  string_attribute: {key: app.tenant, values: [vip]}
Scenario analysis
After a new service goes live with OTel, its traces in Grafana always show only one span, with no database calls visible. List the troubleshooting order.

① Confirm the database driver has a matching instrumentation package and that it is enabled (opentelemetry-bootstrap -a requirements compare against the installed packages); ② check whether auto-instrumentation takes effect before the driver is imported (zero-code: ensured by opentelemetry-instrument ; for code-based setup, before creating the connection, call instrument()); ③ check whether database calls run in other threads / coroutines and lose Context; ④ check whether the Collector drops CLIENT spans with the filter processor; ⑤ view the trace by trace ID in Tempo to confirm the query UI is not collapsing child spans.

Verified teaching videos

▶
OpenTelemetry & Python: Manual Instrumentation for Beginners — Adam Gardner
English · manual Python instrumentation
▶
Python Flask instrumentation using OpenTelemetry | SigNoz — SigNoz - Open Source Observability Platform
English · Flask auto-instrumentation demo (different backend; the SDK part is common)
▶
OpenTelemetry Head and Tail Sampling: EVERYTHING you need to know! — Adam Gardner
English · animation for this module
▶
Why, How to, and Issues: Tail-Based Sampling in the OpenTelemetry Collector - Reese Lee, New Relic — CNCF [Cloud Native Computing Foundation]
English · production issues with tail sampling

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Scene: the Flask app is wrapped in a transparent shell (auto-instrumentation); every request grows spans automatically; the developer then manually attaches a "cart count" label.
Narration: auto-instrumentation gives the skeleton; manual instrumentation gives the business meaning.
Shot 2 · 25–60s
Scene: 1000 trace squares; head sampling cuts 90%, and about half of the red error squares are cut too; switching to tail sampling keeps every red square.
Narration: head sampling is cheap but blind; tail sampling is smart but expensive.
Shot 3 · 60–90s
Scene: two request-rate curves: the one generated before sampling matches the real value; the one generated after sampling is only a tenth.
Narration: metrics must be generated before sampling.
or score ≥ 70% in the Quiz

Module 7 · Correlated troubleshooting: exemplars, trace-to-logs and Explore

42:00 – 50:00 · The value of the three pillars is in the jumps: a diamond on a metric graph takes you to a trace, a span on that trace takes you to the logs for that moment, and the trace_id in the logs jumps back to the trace. This module configures all of these jumps and walks through them
8 minGrafana 13.3.1★★★★★
Learning objectives
  • Explain the full exemplar path from the app to Grafana: observe(…, exemplar=…) → OpenMetrics exposition → Prometheus exemplar-storage → query_exemplars → data source exemplarTraceIdDestinations.
  • Configure the Tempo data source's tracesToLogsV2,tracesToMetrics,serviceMap, and the Loki data source's derivedFields, and handle label-name mapping.
  • Troubleshoot along the path "alert → panel exemplar → trace → span logs → root cause", using the Explore split view and the Drilldown apps.
Prerequisites: Modules 1–6; lesson 1 histogram. Priority:★★★★★

What: the four jumps and where they are configured

JumpKey it depends onConfig location (in the kps values in this lesson)
Metric → trace (exemplar)The trace_id label in the exemplarPrometheus data source jsonData.exemplarTraceIdDestinations (kps: grafana.sidecar.datasources.exemplarTraceIdDestinations)
Trace → logstrace ID (structured-metadata filter) + span time window + resource attributes → Loki label mappingTempo data source jsonData.tracesToLogsV2
Logs → tracetrace_id in the log line or in labels / metadataLoki data source jsonData.derivedFields
Trace → metrics, service graphResource attributes → Prometheus label mapping; metrics-generator metricsTempo data source tracesToMetrics,serviceMap

The full exemplar path (and how each link fails)

  1. App: LAT.labels(route).observe(dt, exemplar={"trace_id": "…"}). exemplars from prometheus_client only appear in the OpenMetrics output format, which looks like …_bucket{le="0.25",route="/"} 12.0 # {trace_id="4bf9…"} 0.21 1763460321.5. Multi-process mode (PROMETHEUS_MULTIPROC_DIR) does not support exemplars (a limitation listed in the client_python official docs); this is why myapp:1.2 in this lesson switched to single-process, multi-threaded.
  2. Scrape: Prometheus 3's default scrape_protocols negotiates protobuf first, then OpenMetrics. The Python client does not support protobuf, so it negotiates OpenMetrics. If a target is forced to the classic text format (PrometheusText0.0.4), exemplars are lost.
  3. Storage: --enable-feature=exemplar-storage (kps: enableFeatures: [exemplar-storage]); exemplars live in a fixed-size in-memory ring buffer whose size is set by storage.exemplars.max_exemplars (Operator: exemplars.maxSize), and they are not long-term storage.
  4. Query and display: the Grafana panel query turns on the "Exemplars" toggle and calls /api/v1/query_exemplars; the data source config maps the trace_id label to the Tempo data source uid, and clicking the diamond shows "View in Tempo".

Why: label-name mapping is always a pain

The same "service" has three different names: in Tempo it is the resource attribute service.name, in Loki it is the service_name / app generated by Alloy in this lesson (or the service_name auto-generated from OTLP), and in Prometheus it is job,service (the span metrics label is called service). tracesToLogsV2.tags and tracesToMetrics.tags each entry is {key: Tempo attribute, value: label name in the target data source}. If a mapping is wrong, the jump still opens but the query is empty. The safest trace → logs method is filterByTraceID: true: generate {…} | trace_id="…" queries, which depend on trace_id actually being in the logs.

How: a standard troubleshooting path

  1. Alert: MyappLatencyHigh (P95 > 150ms, based on the native histogram).
  2. Open the latency panel of the RED dashboard and turn on Exemplars: a diamond near a spike is "a slow request that really happened at that time"; pick the one with the highest value.
  3. Jump to Tempo: the waterfall shows which span the time is spent in (for example INCR takes 95%).
  4. Click "Logs for this span" on that span: the Loki query automatically carries the trace_id and time window, so you can read the context (retries, timeout errors).
  5. To check whether it is widespread, jump from the span to trace → metrics (span metrics error rate / latency), or aggregate with TraceQL metrics in Explore.

When: Explore, Drilldown or dashboard?

  • Dashboard: the on-call entry point, fixed RED / USE views, with exemplars and data links.
  • Explore: free-form queries; the split view can put one data source on each side, and "Link time ranges" keeps the time in sync.
  • Drilldown apps (Metrics / Logs / Traces Drilldown built into Grafana since 12, formerly Explore Logs / Explore Traces): no query writing; click through labels with automatic comparison; good for people unfamiliar with LogQL / TraceQL.
Common misconceptions① "Turning on exemplar-storage gives you diamonds" — the app must emit exemplars, and scraping must use OpenMetrics. ② "Exemplars last as long as metrics" — they live in an in-memory ring buffer and are lost on restart (there are extra WAL implementation details; follow the actual version), so they only suit recent issues. ③ "trace → logs requires span_id in the logs" — it doesn't; trace_id plus a time window is enough, and span_id narrows it to the exact span. ④ "derived fields only support regex" — Grafana supports the Label type (matching a label, a parsed field, or structured metadata), which this lesson uses.

Four-way jump overview

Alert MyappLatencyHighAlertmanager → on-call Prometheus panelP95 curve + ◆ exemplartrace_id=4bf9… Tempo trace viewWaterfall · slow span INCRLogs / Metrics buttons Loki logs| trace_id="4bf9…"TraceID link (derived field) Service graph · span metricsIs it widespread? How much impact? ① exemplar ② trace → logs ③ derived field ④ trace → metrics
Figure 7-1: each arrow corresponds to one data source config item; when an arrow breaks, troubleshooting falls back to manually copying IDs and matching times

What an exemplar looks like in OpenMetrics

# TYPE myapp_http_request_duration_seconds histogram
myapp_http_request_duration_seconds_bucket{le="0.1",route="/"} 3810.0
myapp_http_request_duration_seconds_bucket{le="0.25",route="/"} 3922.0 # {trace_id="4bf92f3577b34da6a3ce929d0e0e4736"} 0.2113 1.7634603215e+09
myapp_http_request_duration_seconds_bucket{le="0.5",route="/"} 3922.0
...
# EOF

each bucket keeps at most the most recent exemplar (an observation that fell into that bucket); # {…} value timestamp is OpenMetrics syntax. The classic text format (text/plain; version=0.0.4) does not have this part.

Interactive: correlated-jump drill

You are the on-call engineer and an alert has just reached your phone. At each step, choose the next action: a correct choice moves on and shows what you would see in Grafana; a wrong choice explains why that step is inefficient. Goal: find the root-cause logs in as few steps as possible.

$ # the alert has not started yet
Click "Start drill".

Verify the config for each jump

source ~/promlab/part8/env.sh
# 1) Does the app emit exemplars? (must send the OpenMetrics Accept header)
kubectl -n myapp exec deploy/myapp -- python -c "
import urllib.request as u
r=u.Request('http://localhost:5000/metrics', headers={'Accept':'application/openmetrics-text; version=1.0.0'})
print([l for l in u.urlopen(r).read().decode().splitlines() if '# {' in l][:2])"
# 2) Which format did Prometheus actually use to scrape myapp? (Prometheus 3 target API field)
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.labels.namespace=="myapp") | [.labels.pod, .scrapeUrl, .health] | @tsv'
pq 'scrape_samples_scraped{namespace="myapp"}'
# 3) Correlation config for the three data sources in Grafana
for ds in prometheus tempo loki; do
  curl -s -u admin:$GPW $G/api/datasources/uid/$ds | jq -c '{uid, type, ex: .jsonData.exemplarTraceIdDestinations, t2l: .jsonData.tracesToLogsV2.datasourceUid, df: [.jsonData.derivedFields[]?.name]}'
done
# 4) Test Loki trace_id filtering through the data source proxy (equivalent to the query generated by "Logs for this span")
TID=$(curl -s -G $T/api/search --data-urlencode 'q={resource.service.name="myapp"}' --data-urlencode limit=1 | jq -r '.traces[0].traceID')
curl -s -u admin:$GPW -G "$G/api/datasources/proxy/uid/loki/loki/api/v1/query_range" \
  --data-urlencode "query={namespace=\"myapp\"} | trace_id=\"$TID\"" --data-urlencode since=30m | jq '.data.result | length'
['myapp_http_request_duration_seconds_bucket{le="0.01",route="/"} 2051.0 # {trace_id="9be1…"} 0.0071 1763460900.1', …]
myapp-6d9c…-2xk8p	http://10.244.0.52:5000/metrics	up
myapp-6d9c…-q7v4m	http://10.244.0.53:5000/metrics	up
{"uid":"prometheus","type":"prometheus","ex":[{"datasourceUid":"tempo","name":"trace_id","urlDisplayLabel":"View in Tempo"}],"t2l":null,"df":[]}
{"uid":"tempo","type":"tempo","ex":null,"t2l":"loki","df":[]}
{"uid":"loki","type":"loki","ex":null,"t2l":null,"df":["TraceID"]}
1

How to verify: All four items are non-empty. Common errors: kps renders exemplarTraceIdDestinations as an array in the data source JSON (field name name corresponds to traceIdLabelName); follow the actual output, since Grafana API return fields may change between versions. Production use: Put step 3 into CI so that the correlation fields are checked automatically after data source config changes.

Lab 7: follow the jump from the alert all the way to the root-cause logs (about 8 minutes)

Prepare the alert (native histogram; the kps rule selects the label release: kps):
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata: {name: myapp-latency, namespace: myapp, labels: {release: kps}}
spec:
  groups:
    - name: myapp.latency
      rules:
        - alert: MyappLatencyHigh
          expr: histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[2m]))) > 0.15
          for: 1m
          labels: {severity: warning}
          annotations:
            summary: "myapp / route P95 {{ $value | humanizeDuration }}"
            description: "Open the myapp latency panel in Grafana and enable Exemplars"
kubectl apply -f ~/promlab/part8/latency-rule.yaml
~/promlab/part8/redis-lag.sh 300 &     # 5 minutes of Redis jitter
sleep 150; pq 'ALERTS{alertname="MyappLatencyHigh"}'
[{"__name__":"ALERTS","alertname":"MyappLatencyHigh","alertstate":"firing","severity":"warning"},"1"]
① Metric → trace: Grafana → Explore → Prometheus, query histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{route="/"}[$__rate_interval]))), turn on Exemplars in the query options. Diamonds appear on the graph; hovering shows trace_id and the "View in Tempo" button; click it.
② Read the waterfall: myapp's GET / is about 200ms, of which INCR span takes most of it → the root cause is Redis. Note the span's db.statement / command attribute (depends on the instrumentation version).
③ trace → logs: on the GET / span, click "Logs for this span". Grafana generates a query like {namespace="myapp"} | trace_id="…" (the time window is 2 minutes before and after the span). Seeing this request's logs,duration_ms ≈ 200.
④ logs → trace: query in Explore {app="myapp"} | logfmt | duration_ms > 150, expand a row, and click the TraceID link in the Fields / Links area to go back to Tempo.
⑤ Is it widespread: on the trace view click Metrics (the request-rate query configured by tracesToMetrics), or check the latency of the myapp → redis edge in the Service Graph; then use TraceQL metrics:
{ span.db.system = "redis" } | quantile_over_time(duration, .95)

Conclusion: the Redis call P95 rose to about 200ms during the fault, affecting all requests through myapp. This is the root cause (the Lua busy-wait in the lab).

Retrospective: record how long each step took and which step was hardest; compare with the "metrics + kubectl logs only" approach. When done, kubectl delete -f ~/promlab/part8/latency-rule.yaml can be kept for the lesson 9 exercises.

Case 1: no exemplars at all; the cause turned out to be multi-process

Problem: The team enabled exemplar-storage and the Grafana config per the docs, but diamonds never appeared. Investigation: curling the app with the OpenMetrics Accept header → no # {; the app runs gunicorn with multiple workers + PROMETHEUS_MULTIPROC_DIR. Fix: Switch this service to histograms with exemplars from OTel SDK metrics (via Collector → Prometheus OTLP, see lesson 6 module 6), or rely on exemplars from Tempo span metrics.

Case 2: trace → logs always empty

Problem: Tempo's "Logs for this span" generates {service_name="checkout"}, but the stream label in Loki is {app="checkout-api"}. Fix: in tracesToLogsV2.tags map service.name to app, or unify service_name on the collection side; also enable filterByTraceID, so trace_id filtering acts as a fallback.

Case 3: the on-call runbook became "three clicks"

Fix: Each service's RED dashboard has exemplars on by default; the latency panel description states "click the diamond → Logs for this span"; the Alertmanager notification template includes the dashboard link directly (lesson 2). Result: New team members can do the first round of diagnosis without knowing how to write LogQL / TraceQL.

Common errors and fixes

No diamonds on the graph; no exemplars request in the Query inspector

Cause: The panel query has the Exemplars toggle off, or the query type is Instant. Fix: Use a Range query and turn on the toggle.

/api/v1/query_exemplars returns an empty array

Check the chain segment by segment: App (does the OpenMetrics output contain # { ? multi-process?) → scrape (is the target configured as PrometheusText0.0.4?) → storage (is enableFeatures in effect? did Prometheus just restart?) → query time range.

After clicking the diamond, Tempo reports trace not found

Cause: the trace in the exemplar was dropped by sampling (the app wrote an exemplar even when unsampled; this lesson's code only writes when sampled , which avoids it), it is past Tempo retention, or the Collector export failed.

The derived field link does not appear

Cause: With the regex type, matcherRegex does not match (the log contains traceID= rather than trace_id=); with the Label type the field name is inconsistent; or the data source uid is wrong. Fix: Paste a real log line into the derived field debug box on the data source settings page to test. Alternative regex: matcherRegex: 'trace_id=(\w+)'.

Datasource tempo was not found (when jumping from Prometheus)

Cause:datasourceUid The name was used instead of the uid, or the Tempo data source has no provisioned uid. Fix: Pin uid: tempo in additionalDataSources (this lesson's approach).

Command-line tasks
1. Use curl to prove that myapp's exemplars appear only in the OpenMetrics format.
kubectl -n myapp port-forward svc/myapp 5000:5000 &
curl -s localhost:5000/metrics | grep -c '# {'                                         # 0
curl -s -H 'Accept: application/openmetrics-text' localhost:5000/metrics | grep -c '# {'   # > 0
2. In the Loki data source, write a regex-type derived field that extracts trace_id=… from the line and links it to Tempo.
derivedFields:
  - name: TraceID
    matcherRegex: 'trace_id=(\w+)'
    datasourceUid: tempo
    url: '$${__value.raw}'
    urlDisplayLabel: View trace
Scenario analysis
A team says: "We have traces and logs, but nobody ever uses traces, because it's impossible to find which one to look at." How would you improve this?

The problem is at the entry point: traces need to be reached from a "metric anomaly". ① Enable exemplars on native histograms so the RED panels show diamonds by default; ② enable the metrics-generator service graph and span metrics to provide an "is it widespread" link back from the trace view; ③ include a dashboard link in alert notifications; ④ enable derived fields on logs so error lines found with grep jump to the trace in one click; ⑤ roll out the Traces Drilldown app to click through by service / error / latency without writing TraceQL; ⑥ write the "three clicks" path into the on-call runbook as a standard action and drill it.

Verified teaching videos

▶
Unifying Observability: Correlating Metrics, Traces, and Logs with Exemplars an... K.P. Simha, C. Le — CNCF [Cloud Native Computing Foundation]
English · tying the three pillars together with exemplars (KubeCon talk)
▶
7. Observability Coordinated: Prometheus Exemplars (Metrics) — Grafana Tempo (Traces) — Loki (Logs) — Linh Vu
English · hands-on demo of exemplar → Tempo → Loki
▶
Traces Drilldown (Previously Explore Traces) in Public Preview | Demo | Grafana Labs — Grafana
English · Drilldown app demo (recorded during the public preview)

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Scene: a phone alert "P95 > 150ms"; open the latency graph, with a few diamonds floating above the spike.
Narration: the diamonds are the slow requests that really happened at that time.
Shot 2 · 20–55s
Scene: click the diamond → the waterfall expands, with a long red INCR span bar; click "Logs for this span" → logs with the same trace_id slide up from the bottom.
Narration: one click to the trace, another click to the logs.
Shot 3 · 55–90s
Scene: the TraceID link in the logs jumps back to the waterfall; the myapp → redis edge in the service graph turns red.
Narration: the four-way jumps turn three pillars into one network.
or score ≥ 70% in the Quiz

Module 8 · Cost, retention, troubleshooting and self-assessment

50:00 – 60:00 · Logs and traces are usually an order of magnitude more expensive than metrics. This module first works out where the money goes and how to set retention, then wraps up with four injected faults (log loss, label cardinality, OOM, broken traces) and an interactive troubleshooting tree
10 minfault-obs.shInteractive troubleshooting tree★★★★★
Learning objectives
  • Estimate log and trace storage and cost; know the four most effective levers: write less (drop noise), fewer labels, sampling, shorter retention.
  • Configure Loki global and per-stream retention (retention_period,retention_stream), Tempo block retention (block_retention), and understand the roles of the compactor and backend worker.
  • Diagnose four common faults: log loss, label cardinality, ingester / live-store OOM, and broken traces; write one guardrail alert for each.
Prerequisites: Modules 1–7. Priority:★★★★★

What: where the money goes

BackendMain cost itemsGrows withMost effective levers
LokiObject storage (compressed blocks), ingester memory, query computelog bytes × retention days; number of streamsDrop at the collector (debug logs, health checks, repeated stack traces); low-cardinality labels; shorter per-stream retention
TempoObject storage (Parquet), live-store memory, Kafka (microservices mode), metrics-generator seriesnumber of spans × average size × retention daysSampling (head + tail), exclude health-check spans, limit attribute size, short retention
Prometheus (span metrics / service graph)active seriesservice × span name × status × dimensionsDo not add high-cardinality attributes to spanmetrics dimensions; parameterize span names (GET /users/{id} rather than GET /users/123)

How to set retention

  • Loki: limits_config.retention_period (global / per tenant),retention_stream set different retention by selector (e.g. audit logs 90 days, debug logs 3 days); you must enable compactor.retention_enabled and configure delete_request_store. Deletion is asynchronous (compactor cycle + deletion delay).
  • Tempo: block_retention (the chart's tempo.retention renders to the backend scheduler / worker); recent data in the live-store has its own retention window.
  • exemplar: an in-memory ring buffer, not long-term data; after a Prometheus restart, the range recovered from the WAL is limited (follow the actual version).
  • Object-storage lifecycle rules can serve as a fallback, but must be slightly longer than the application-level retention, otherwise blocks still referenced by the index get deleted and queries fail.

Why: four common faults

FaultTypical symptomPrimary evidenceGuardrail
Log lossNo logs in Grafana for a period; alert absent_over_timecollector loki_write_dropped_entries_total, Loki loki_discarded_samples_total{reason}, collector logs with 4xx / 5xxalert on dropped / discarded; leave headroom in Loki limits
Label cardinality429 stream limit, rising ingester memory, slow queriesloki_ingester_memory_streams,logcli series --analyze-labelsallowlist labels on the collection side; limits as the last line of defense
ingester / live-store OOMPod repeatedly OOMKilled; after restart, WAL replay OOMs again; writes failkubectl describe pod (Last State: OOMKilled), memory curve, stream / trace countsmemory limit covers the replay peak; rate limiting; reduce cardinality; scale out
Broken traceOne request becomes several traces; gaps in the service graph; missing root spandownstream SERVER span has no parent; gateway request headersunify W3C propagation; gateway forwards headers; monitor service-graph edge count

How: the minimal self-monitoring set

# log pipeline
sum by (reason) (rate(loki_discarded_samples_total[5m])) > 0
sum(rate(loki_write_dropped_entries_total[5m])) > 0
sum(loki_ingester_memory_streams) > 0.8 * 5000
# trace pipeline
sum(rate(otelcol_exporter_send_failed_spans_total[5m])) > 0
sum(rate(otelcol_receiver_refused_spans_total[5m])) > 0
# storage component restart (OOM)
increase(kube_pod_container_status_restarts_total{namespace="observability"}[15m]) > 0

metric names follow each component's actual /metrics (Collector internal metric names change across versions); Loki and Tempo both ship official mixins (alerts and dashboards); prefer them in production.

When: when is it worth paying for

Rule of thumb: each signal's retention is set by "who uses it, and when". Traces are almost only used to troubleshoot the last few days, so 7 days is usually enough; logs are tiered by purpose (security / audit per compliance requirements, application logs 14–30 days, debug logs a few days); metrics are kept long-term and downsampled (lesson 6).

Common misconceptions① "Object storage is cheap, so full retention is fine" — query cost, ingester memory, network egress and PUT/GET request fees are all significant. ② "When Loki returns 429, just raise the limit" — first check whether it is cardinality or a log storm. ③ "Tempo OOM, so add memory" — first look at trace size and the trace count in the live-store; oversized traces should be split. ④ "Broken traces are Tempo's problem" — almost always a propagation issue; Tempo only stores by ID.

Where the four faults sit in the pipeline

App / gatewayInstrumentation · propagation Alloy / CollectorLabels · sampling · retry distributorValidation · limits ingester / live-storeMemory · WAL Object storageRetention ④ broken trace ① log loss (retries exhausted)② label cardinality (at the source) ① 429 / 400 rejected② stream limit ③ OOM · replay loop cost · retention First ask: at which segment does the data disappear? Did the collector send it (sent / dropped)? Did the backend receive it (received / discarded)? Was it stored (query)?
Figure 8-1 follows the same idea as the eight-segment chain in lesson 7: locate the segment first, then gather evidence

Interactive: log and trace cost estimator

Enter your scale to estimate daily ingest, storage over retention, and monthly object-storage cost at example unit prices. Unit prices are examples only (replace them with your cloud vendor's prices); the compression ratio and span size are rough empirical values.

Drag the sliders to see the estimate.

fault-obs.sh: inject and reset four faults

Save as ~/promlab/part8/fault-obs.sh. Prerequisites: all values files from module 0, and module 5's stripper.yaml exists. Only modify the observability and myapp objects in the namespaces.

#!/usr/bin/env bash
# Lesson 8 fault blind box: ./fault-obs.sh 1..4 | random | reveal | reset
set -uo pipefail
D=~/promlab/part8; ANS=$D/.answer
hl() { helm upgrade "$@" >/dev/null; }

reset() {
  hl loki grafana-community/loki --version 21.4.0 -n observability -f $D/loki-values.yaml \
     --set monitoring.serviceMonitor.enabled=true --set-string monitoring.serviceMonitor.labels.release=kps
  hl alloy grafana/alloy --version 1.16.0 -n observability -f $D/alloy-values.yaml
  hl tempo grafana-community/tempo --version 3.2.1 -n observability -f $D/tempo-values.yaml
  kubectl -n observability scale statefulset/loki --replicas=1 >/dev/null
  kubectl -n myapp set env deploy/myapp-edge UPSTREAM_URL=http://myapp.myapp.svc:5000 >/dev/null
  kubectl delete -f $D/stripper.yaml --ignore-not-found >/dev/null
}
# 1 Log loss: Loki stops for 3 minutes (the collector drops data after retries are exhausted)
f1() { kubectl -n observability scale statefulset/loki --replicas=0 >/dev/null
       echo "Symptom: log queries for myapp in Grafana fail or come back empty for the last few minutes."; }
# 2 Label cardinality: trace_id promoted to a label + stream limit 200
f2() { sed 's/values = { "service_name" = "service" }/values = { "service_name" = "service", "trace_id" = "" }/' \
         $D/alloy-values.yaml > $D/.alloy-bad.yaml
       hl alloy grafana/alloy --version 1.16.0 -n observability -f $D/.alloy-bad.yaml
       hl loki grafana-community/loki --version 21.4.0 -n observability -f $D/loki-values.yaml \
          --set loki.limits_config.max_global_streams_per_user=200
       echo "Symptom: some new logs cannot be found; 429 appears in the Alloy logs."; }
# 3 OOM: Tempo memory limit squeezed to 96Mi
f3() { hl tempo grafana-community/tempo --version 3.2.1 -n observability -f $D/tempo-values.yaml \
          --set tempo.resources.limits.memory=96Mi --set tempo.resources.requests.memory=64Mi
       echo "Symptom: Tempo queries in Grafana fail intermittently; tempo-0 restart count goes up."; }
# 4 Broken trace: edge calls myapp through an nginx that drops headers
f4() { kubectl apply -f $D/stripper.yaml >/dev/null
       kubectl -n myapp set env deploy/myapp-edge UPSTREAM_URL=http://stripper:8080 >/dev/null
       echo "Symptom: the myapp-edge → myapp edge disappears from the service graph; myapp traces are all single-service."; }

case "${1:-random}" in
  reset)  reset; rm -f $ANS $D/.alloy-bad.yaml; echo "Reset done (fully recovers in about 1–2 minutes)";;
  reveal) echo "Fault number this round: $(cat $ANS 2>/dev/null || echo none)";;
  random|[1-4])
    reset; n=${1:-random}; [ "$n" = random ] && n=$(( RANDOM % 4 + 1 ))
    echo $n > $ANS; echo "Injected; symptoms appear in 1–3 minutes."; f$n;;
  *) echo "Usage: $0 1..4|random|reveal|reset"; exit 1;;
esac

Standard diagnostic bundle (run it first in every round)

source ~/promlab/part8/env.sh
kubectl -n observability get pods -o wide
kubectl -n observability get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\t"}{.status.containerStatuses[0].lastState.terminated.reason}{"\n"}{end}'
pq 'sum by (reason) (rate(loki_discarded_samples_total[5m]))'
pq 'sum(loki_ingester_memory_streams)'
kubectl -n observability logs deploy/alloy --since=5m | grep -E 'level=(warn|error)' | tail -3
kubectl -n observability logs deploy/otelcol-opentelemetry-collector --since=5m | grep -iE 'error|dropping' | tail -3
pq 'sum by (client, server) (rate(traces_service_graph_request_total[5m]))'
alloy-7b9f…            0
loki-0                 0
otelcol-…              0
tempo-0                4    OOMKilled
...

Note: During fault 1, Prometheus also cannot scrape Loki's metrics (up{job=~".*loki.*"} == 0 is itself evidence). Whether the fault 3 memory value is enough to trigger OOM depends on traffic; lower it to 64Mi if needed. For the Tempo chart resource key names, follow 3.2.1.

Lab 8: blind-box drill (about 3 minutes per round, at least 3 rounds)

Draw:
cd ~/promlab/part8 && chmod +x fault-obs.sh && ./fault-obs.sh random
Injected; symptoms appear in 1–3 minutes.
Symptom: the myapp-edge → myapp edge disappears from the service graph; myapp traces are all single-service.
Diagnose: run the standard diagnostic bundle from the Commands page and locate the segment using Figure 8-1: does the data disappear at the collector, the distributor, the ingester / live-store, or the propagation step? Write down your conclusion before ./fault-obs.sh reveal.
Fix and guardrails: ./fault-obs.sh reset, and write one alert expression for this fault (refer to the self-monitoring set on the Principles page).
Retention config exercise: set a separate 1-day retention for debug logs:
# append under loki-values.yaml → loki.limits_config
retention_stream:
  - selector: '{namespace="myapp", level="DEBUG"}'
    priority: 1
    period: 24h

retention_stream selectors can only use stream labels; in this lesson level is not a stream label, so this rule matches no streams. That is the point of the exercise: to set retention by level, level must be a (low-cardinality) stream label, or you must split by app / namespace. Think about it: is it worth it?

Record table:
Round | Symptom | Segment | Decisive evidence | Root cause | Fix | Guardrail alert | Time spent
1    |      |      |            |      |      |          |

Case 1: the log bill doubles in one month

Problem: A release accidentally set the log level to DEBUG. Finding:sum by (app) (bytes_rate({…}[1h])) 's cost panel shows that one application accounts for 70%. Fix: Drop DEBUG lines at the collector stage.drop (exception: debugging sessions with a specific marker); a weekly cost report is split by application and sent to team leads.

Case 2: Loki ingester OOM loop

Problem: After the stream count grew from 20k to 300k, the ingester kept getting OOMKilled, and WAL replay on restart OOMed again. Stop the bleeding: temporarily raise the memory limit to finish replay; remove high-cardinality labels at the collector; clear the WAL if necessary (unflushed data will be lost, so assess first). Root fix: label allowlist + stream-count alert (at 80% of the limit) + capacity planning. This is the same "cardinality → OOM → replay loop" pattern as Prometheus in lesson 7.

Case 3: service-graph edge count as a propagation health metric

Fix: Turn count(sum by (client, server) (rate(traces_service_graph_request_total[1h]))) into a trend panel; alert when the edge count drops sharply after a gateway upgrade. This is much earlier than finding out about broken traces only when troubleshooting.

Interactive troubleshooting tree: logs and traces

Start from the symptom you see and choose step by step; the leaf nodes give the diagnostic commands and fixes.

Command-line tasks
1. Write one LogQL query that computes the bytes each application wrote to Loki in the past 24 hours, sorted by size, top 5.
topk(5, sum by (app) (bytes_over_time({namespace=~".+"}[24h])))

Long-range instant queries are heavy; in production, use the index volume API or a ruler recording rule instead.

2. Find the containers in the observability namespace that restarted due to OOM.
kubectl -n observability get pods -o json | jq -r '.items[] | .metadata.name as $p | .status.containerStatuses[] | select(.lastState.terminated.reason=="OOMKilled") | "\($p)/\(.name) restarts=\(.restartCount)"'
Scenario analysis
Finance requires the storage cost of logs and traces to drop 50%, without hurting troubleshooting ability. Give a plan and a verification method.

① Measure: by application, the bytes_rate, span count and Tempo block size; find the top 10. ② Write less: drop health checks, DEBUG, and repeated stack traces (stage.drop,stage.limit), exclude health-check and scrape spans; ③ Sampling: head 20–50% + tail retention of errors and slow requests, with RED generated before sampling; ④ Tiered retention: retention_stream set by namespace / application (except audit), with traces kept for 7 days; ⑤ Label governance to reduce the stream count (larger chunks, better compression); ⑥ Verify: compare MTTR, on-call investigation records, the number of "can't find it" reports before and after, and the cost panel.

Verified teaching videos

▶
How to run Loki at scale on Kubernetes (Loki Community Call January 2025) — Grafana
English · lessons from running Loki at scale, including capacity and limits
▶
Loki's New Architecture: 10x Faster Logs at Petabyte Scale | Grafana Labs — Grafana
English · Loki's new architecture direction (related to Loki 4; read according to release status)
▶
The Ultimate Guide to Sampling in OpenTelemetry — Is it Observable
English · sampling and cost

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Scene: three bars on a bill, logs the highest; four knobs: write less, fewer labels, sampling, shorter retention; turn each one down and the bars shrink.
Narration: the four cost levers.
Shot 2 · 25–65s
Scene: on the pipeline diagram, four spots smoke in turn: collector drop, distributor 429, ingester OOM, and a gateway stripping request headers.
Narration: first ask at which segment the data disappears.
Shot 3 · 65–90s
Scene: next to each puff of smoke an alert expression appears, and the smoke clears.
Narration: every fix leaves behind a guardrail.
or score ≥ 70% in the Quiz

Command cheat sheet

Common logs and traces commands, queries, config snippets and exact error messages (Loki 3.7.10 · Tempo 3.1.1 · Alloy 1.22.0 · Collector 0.165.0 · Grafana 13.3.1)
LogQL
{app="myapp"} |= "status=5" | logfmt | status >= 500
{app="myapp"} | json | level="error" | line_format "{{.msg}}"
{app="myapp"} | pattern `<_> route=<route> status=<status> <_>`
{namespace="myapp"} | trace_id="<32-digit hex>"
sum by (route) (rate({app="myapp"} | logfmt | status >= 500 [5m]))
quantile_over_time(0.95, {app="myapp"} | logfmt | __error__="" | unwrap duration_ms [5m]) by (route)
sum by (app) (bytes_rate({namespace="myapp"}[5m]))
absent_over_time({app="myapp"}[10m])
TraceQL
{ resource.service.name = "myapp" && status = error }
{ span.db.system = "redis" && duration > 100ms }
{ trace:duration > 1s }
{ resource.service.name = "myapp-edge" } >> { status = error }
{ status = error } | rate() by (resource.service.name)
{ kind = server } | quantile_over_time(duration, .95) by (resource.service.name)
Loki / logcli
export LOKI_ADDR=http://localhost:3100
logcli labels; logcli labels app
logcli series '{namespace="myapp"}' --analyze-labels
logcli query --since=1h --limit=100 '{app="myapp"} |= "ERROR"'
logcli instant-query 'sum by (app) (count_over_time({namespace="myapp"}[1h]))'
curl -s $L/ready; curl -s $L/config | grep retention
curl -s -G $L/loki/api/v1/index/volume --data-urlencode 'query={namespace="myapp"}'
curl -s $L/loki/api/v1/rules
Tempo API
curl -s -G $T/api/search --data-urlencode 'q={…}' --data-urlencode limit=20
curl -s $T/api/v2/traces/<traceID>
curl -s $T/api/v2/search/tags
curl -s $T/api/v2/search/tag/resource.service.name/values
curl -s -G $T/api/metrics/query_range --data-urlencode 'q={…} | rate()' --data-urlencode step=60s
curl -s $T/status/config | grep -A5 metrics_generator
OTel SDK environment variables
OTEL_SERVICE_NAME=myapp
OTEL_RESOURCE_ATTRIBUTES=service.namespace=shop-demo,deployment.environment.name=lab
OTEL_EXPORTER_OTLP_ENDPOINT=http://otelcol:4317   # use 4318 for HTTP
OTEL_EXPORTER_OTLP_PROTOCOL=grpc                  # or http/protobuf
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1
OTEL_PROPAGATORS=tracecontext,baggage
OTEL_PYTHON_FLASK_EXCLUDED_URLS=healthz,metrics
OTEL_PYTHON_LOG_CORRELATION=true                  # inject trace context with zero code
Collector snippet
processors:
  memory_limiter: {check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 25}
  k8sattributes: {}            # or chart presets.kubernetesAttributes
  tail_sampling:
    decision_wait: 10s
    policies:
      - {name: errors, type: status_code, status_code: {status_codes: [ERROR]}}
      - {name: slow, type: latency, latency: {threshold_ms: 300}}
      - {name: rest, type: probabilistic, probabilistic: {sampling_percentage: 10}}
  batch: {}
exporters:
  otlp_grpc/tempo: {endpoint: tempo:4317, tls: {insecure: true}}   # old name otlp
  otlp_http/loki: {endpoint: http://loki:3100/otlp}                # old name otlphttp
Alloy snippet
loki.process "app" {
  stage.logfmt { mapping = { "level" = "", "trace_id" = "" } }
  stage.structured_metadata { values = { "trace_id" = "" } }
  stage.drop { source = "level"  value = "DEBUG" }
  forward_to = [loki.write.default.receiver]
}
// alloy convert --source-format=promtail -o config.alloy promtail.yaml
// alloy fmt config.alloy
Grafana correlation (kps values)
grafana.sidecar.datasources.exemplarTraceIdDestinations:
  {datasourceUid: tempo, traceIdLabelName: trace_id}
Tempo jsonData:
  tracesToLogsV2: {datasourceUid: loki, filterByTraceID: true}
  tracesToMetrics: {datasourceUid: prometheus}
  serviceMap: {datasourceUid: prometheus}
Loki jsonData:
  derivedFields: [{name: TraceID, matcherType: label, matcherRegex: trace_id, datasourceUid: tempo, url: '$${__value.raw}'}]
prometheus.prometheusSpec: {enableFeatures: [exemplar-storage], enableRemoteWriteReceiver: true}

Error message quick reference

Error / symptomComponentModule
maximum active stream limit exceeded when trying to create stream …Loki distributor / ingesterModule 2
ingestion rate limit exceeded for user … (limit: … bytes/sec) …Loki distributorModule 2
entry for stream '…' has timestamp too old: …Loki distributorModule 2
max entry size '…' bytes exceeded for stream '…' …Loki distributorModule 2
stream '…' includes structured metadata, but this feature is disallowed …Loki (schema / limits)Module 2
maximum number of series (500) reached for a single query; …Loki querierModule 4
queries require at least one regexp or equality matcher that does not have an empty-compatible value …LogQL parsingModule 4
error at least one label pair is required per streamLoki / Alloy relabelModule 3
'exporters' unknown type: "otlp_grpc"Legacy CollectorModule 3
Failed to export traces …, error code: StatusCode.UNAVAILABLEOTel Python SDKModule 6
"missing span" in a trace / missing root spanPropagation / samplingModule 5
Cannot run more than 1 Monolithic replica without an object storage backend.Loki chartModule 0

Capstone lab + final quiz

Deliver a three-pillars-plus-correlation observability setup for the K8s course's shop (or myapp), and prove it works with one injected fault
About 60–90 minutesLocal kind · no cost
Scenario

You are the observability lead for the platform team. The business side complains: "the alert fires but only says it's slow, not where; digging through logs takes half an hour." On the kind cluster lab for myapp-edge → myapp → Redis (or the K8s course's shop: podinfo api + nginx web + postgres), build complete logs and traces, configure four-way correlation, log alerts and cost guardrails, and finally use one injected downstream fault to demo "locating the root cause in three clicks".

1. Infrastructure: complete all the module 0 steps (Loki, Tempo, Collector, Alloy, kps upgrade), and put all values files under Git (the monitoring-config repo from lesson 5, or a new directory).
2. Instrumentation: deploy two services with myapp:1.2; add one more manual span in /checkout (for example inventory.reserve) and one business attribute; verify that logs carry trace_id and histograms carry exemplars.
curl -s -G $T/api/search --data-urlencode 'q={ span:name = "inventory.reserve" }' --data-urlencode limit=1 | jq '.traces | length'
3. Label and collection review: use logcli series --analyze-labels to prove the stream count is ≤ 10; in Alloy, drop DEBUG and redact one field.
4. Correlation: all four-way jumps work (step 3 on the module 7 Commands page: all four items non-empty); save screenshots of "diamond → waterfall → logs → back to trace".
5. Alerts: one latency alert based on the native histogram (module 7), one Loki log alert (module 4), one log-absence alert (absent_over_time), and two pipeline self-monitoring alerts (Loki discarded, Collector send_failed).
kubectl apply -f ~/promlab/part8/latency-rule.yaml -f ~/promlab/part8/loki-rules.yaml
curl -s $P/api/v1/rules | jq -r '.data.groups[].rules[] | select(.name|test("Myapp")) | "\(.name) \(.health)"'
curl -s $L/prometheus/api/v1/rules | jq -r '.data.groups[].rules[] | "\(.name) \(.health)"'
6. Fault demo: ~/promlab/part8/redis-lag.sh 300 &, timed: from alert firing to reading the root-cause logs (target < 3 minutes); record every click.
7. Cost and retention: use the module 8 estimator and bytes_rate measured data to write a one-page capacity and cost note: daily log volume, span count, retention, sampling strategy and rationale.
8. Cleanup (skip this if you keep the environment for the lesson 9 exercises):
kubectl -n myapp delete pod loadgen --ignore-not-found
kubectl delete -f ~/promlab/part8/latency-rule.yaml -f ~/promlab/part8/loki-rules.yaml --ignore-not-found
helm -n observability uninstall alloy otelcol tempo loki
kubectl delete namespace observability          # the PVC is deleted with the namespace
helm upgrade kps prometheus-community/kube-prometheus-stack --version 93.3.0 -n monitoring --reuse-values \
  --set prometheus.prometheusSpec.enableRemoteWriteReceiver=false   # restore the other values from your repo
# To restore the myapp:1.1 multi-process version: kubectl apply -f ~/promlab/k8s/myapp.yaml; kubectl -n myapp delete deploy/myapp-edge svc/myapp-edge
Acceptance checklist

Open-ended self-check

1. Why does Loki choose to index only labels, and what does this require of the queries you write?

To keep writes and storage cheap: the index is small, and content is compressed and stored in object storage. The cost is that queries must scan chunks, so queries must first narrow the scope with precise stream selectors and short time ranges, then use line filters and parsers.

2. Where should trace_id go in Loki, and why?

Structured metadata (or left in the log line). It has one value per request, so making it a label would explode the stream count. Structured metadata is not indexed but can be filtered, and Grafana's trace → logs uses | trace_id="…" to query it.

3. Can head and tail sampling be combined? What should you watch out for?

Yes: head sampling first reduces overall traffic, then tail sampling keeps the important traces. Note that tail sampling never sees traces dropped by head sampling, so the head ratio must be high enough; multi-replica tail sampling needs routing by trace ID; RED metrics are generated before sampling.

4. Why are exemplars unavailable in gunicorn multi-process mode? What are the alternatives?

prometheus_client's multi-process mode merges each worker's values through mmap files in a shared directory, and the official docs explicitly do not support exemplars. Alternatives: single-process multi-threaded (this lesson); OTel SDK metrics (with exemplars) written to Prometheus over OTLP; or exemplars from Tempo span metrics / Collector spanmetrics.

5. What are the fundamental architectural changes between Tempo 3 and 2.x?

2.x relies on the ingester (memory + replication) and the compactor. 3.0 introduces a write path persisted through a Kafka-compatible queue: the distributor writes to Kafka, the live-store serves recent queries, the block-builder creates blocks, and the backend scheduler / worker handles compaction and retention. Monolithic mode needs no Kafka. TraceQL metrics are GA in 3.0.

6. When should you use log alerts, and when metric alerts?

Metric alerts are for symptoms with native metrics, such as SLOs, error rates and latency: cheap and timely. Log alerts are for events that appear only in log text, third-party components and audit. Over the long term, convert important log signals into metrics (a ruler recording rule or counters generated at the collector).

Sources and version notes

Verification basis for this lesson's technical facts (verified 2026-11-18)
TopicVerified conclusionSource (verified 2026-11-18)
VersionsLoki v3.7.10 (2026-11-13), v3.6.22 (2026-11-18, old-branch patch), v4.0.0-rc.3 (2026-11-07, pre-release); Tempo v3.1.1 (2026-10-21), 3.0.0 released 2026-05-28; Alloy v1.22.0 (2026-11-13); OTel Collector v0.165.0 (2026-11-07); OTel Python v1.45.2 (2026-10-29), contrib v0.66b2 (2026-10-29); Grafana v13.3.1 (2026-11-10)GitHub Releases API:loki,tempo,alloy,collector-releases,opentelemetry-python
Helm chartgrafana-community/loki 21.4.0 (appVersion 3.7.10),grafana-community/tempo 3.2.1 (3.1.1),grafana-community/tempo-distributed 3.29.0,grafana/alloy 1.16.0 (v1.22.0),open-telemetry/opentelemetry-collector 0.179.1 (appVersion 0.163.2),open-telemetry/opentelemetry-operator 0.129.1; old grafana/loki 7.6.0 is still in the indexthe three repos' index.yaml; chart package contents values.yaml,templates/validate.yaml,_helpers.tpl,_pod.tpl (Loki 21.4.0),values.yaml (Tempo 3.2.1, Alloy 1.16.0)
Loki chart location and deployment modesThe Loki chart is maintained by the community in grafana-community/helm-charts. Monolithic is recommended for small scale; SSD is being deprecated (chart comment: removed in Loki 4); Microservices is recommended for production; the MinIO subchart is deprecated (the docs say it will be removed on 2026-10-31); filesystem storage cannot have more than 1 replicaInstall Loki with Helm,Install monolithic; chart 21.4.0 template
Promtail“Promtail is end of life (EOL) as of March 2, 2026”; commercial support has ended and there are no further updates; lambda-promtail is not in the deprecation scopePromtail docs; Loki v3.7.10 repository docs/sources/send-data/promtail/_index.md
Loki defaults and errorsingestion_rate_mb 4, burst 6, max_label_names_per_series 15, max_line_size 256KB, reject_old_samples_max_age 7d, max_global_streams_per_user 5000, max_entries_limit 5000, max_query_series 500, max_query_length 721h, per-stream 3MB/s with a 15MB burst, structured metadata 64KB / 128 entries, allow_structured_metadata defaults to true; chunk_target_size 1572864, chunks-idle-period 30m, max_chunk_age 2h, chunks-block-size 256KB, chunk_encoding defaults to gzip; exact error messages (stream limit, rate limit, timestamp too old, max entry size, structured metadata disallowed, max series)Loki v3.7.10 pkg/validation/limits.go,pkg/validation/validate.go,pkg/ingester/ingester.go,pkg/logqlmodel/error.go,pkg/logql/engine.go,pkg/distributor/distributor.go
Tempo 3 architectureKafka-compatible queue (microservices mode), live-store replaces the ingester, block-builder, backend scheduler / worker replaces the compactor; monolithic mode has no Kafka; TraceQL metrics GA; tempo-cli migrate config; OpenCensus and others removed; span multiplier and tracestate compensation optionsTempo architecture; v3.0.0 release notes
Alloy componentsloki.source.kubernetes (GA; reads logs via the API, compared with loki.source.file it uses more kubelet resources),loki.process 's stage list,otelcol.processor.k8sattributes (GA),otelcol.exporter.loki; alloy convert supports otelcol / prometheus / promtail / static; parameter --output --report --bypass-errors; the chart's default ClusterRole includes pods/logAlloy v1.22.0 repository docs/sources/reference/components/,docs/sources/reference/cli/convert.md; chart 1.16.0 values.yaml
Collectorv0.144: otlp → otlp_grpc,otlphttp → otlp_http (old names remain as deprecated aliases); v0.165: a startup warning is raised when the batch processor and exporterhelper batching are used together,queue_batch processor is promoted to betaopentelemetry-collector CHANGELOG
ExemplarIn Prometheus, exemplar storage is still a feature flag --enable-feature=exemplar-storage (fixed-size ring buffer); client_python multi-process mode: “Exemplars are not supported”; kps values enableFeatures,enableRemoteWriteReceiver,grafana.sidecar.datasources.exemplarTraceIdDestinations,additionalDataSourcesPrometheus feature flags,client_python multiprocess; kube-prometheus-stack 93.3.0 values.yaml
OTel Python log correlationOTEL_PYTHON_LOG_CORRELATION (default false); inject otelTraceID,otelSpanID,otelServiceName,otelTraceSampledlogging instrumentation
Grafana data sourcesYAML examples for Loki derived fields (datasourceUid,matcherRegex,name,url: '$${__value.raw}',urlDisplayLabel) and the two types “Regex in log line / Label”; provisioning examples for the Tempo data source's tracesToLogsV2, tracesToMetrics, serviceMap and nodeGraphConfigure Loki data source,Provision Tempo data source
W3C Trace Contexttraceparent four-part format (version-traceid-parentid-flags)W3C Recommendation

Video verification notes

The following videos were checked for titles and channels via the YouTube oEmbed API (https://www.youtube.com/oembed?url=…&format=json 2026-11-18): Grafana “Correlate Your Metrics, Logs & Traces with the curated OSS observability stack from Grafana Labs” (qVITI34ZFuk), “All the Components of Loki Explained | Grafana Labs” (_hv4i84Z68s), “How to Get Started with Loki | Zero to Hero: Loki | Grafana” (1uk8LtQqsZQ), “Grafana Loki design basics with Ed Welch (Grafana Office Hours #27)” (3uFMJLufgSo), “All about Structured Metadata in Loki (Loki Community Call August 2025)” (IKdRzjwFXYI), “What is Alloy and when does it make sense to use it? | Grafana Alloy for Beginners Ep 2” (bFyGd_Sr5W4), “Alloy Configuration Language 101 | Grafana Alloy for Beginners Ep 3” (fN0uwuwm1Fo), “How to query Grafana Loki with LogQL” (57dQwcmqkpQ), “Grafana Loki Query Best Practices with LogQL (Loki Community Call December 2024)” (d61nQX-n91c), “What's New in Tempo 3.0” (JEOne1NHeyo), “What's New in Tempo 3.1” (87mI6N8L9Z8), “Traces to metrics: Ad-hoc RED metrics in Grafana Tempo” (xOolCpm2F8c), “Traces Drilldown (Previously Explore Traces) in Public Preview | Demo | Grafana Labs” (a3uB1C2oHA4), “How to run Loki at scale on Kubernetes (Loki Community Call January 2025)” (lAr0GwuZHiw), “Loki's New Architecture: 10x Faster Logs at Petabyte Scale | Grafana Labs” (0yJPA_xwON0); Fireship “Grafana is the goat... Let's deploy the LGTM stack” (1X3dV3D5EJg); Adam Gardner “OpenTelemetry Collector: EVERYTHING you need to know [to get started]” (_CJrFW_yjRo), “OpenTelemetry & Python: Manual Instrumentation for Beginners” (iVQmhMLEkS0), “OpenTelemetry Head and Tail Sampling: EVERYTHING you need to know!” (EuE8xnVOQ3M); Free Linux Tutorials “Docker Tutorial: Getting started with Grafana Loki and Alloy | Complete Promtail Migration Guide” (3W99Go4S39E); SysMinu “Distributed Tracing Explained | OpenTelemetry Spans & Context” (2JU3qeCCVb4); SigNoz “Python Flask instrumentation using OpenTelemetry | SigNoz” (50t8T2iL6sA); CNCF “Why, How to, and Issues: Tail-Based Sampling in the OpenTelemetry Collector - Reese Lee, New Relic” (l4PeclHKl7I), “Unifying Observability: Correlating Metrics, Traces, and Logs with Exemplars an... K.P. Simha, C. Le” (zYF1JIZmpI4); Linh Vu “7. Observability Coordinated: Prometheus Exemplars (Metrics) — Grafana Tempo (Traces) — Loki (Logs)” (4YjaR-c0Cjc); Is it Observable “The Ultimate Guide to Sampling in OpenTelemetry” (7T-KoxtU5GU). Durations, upload dates and detailed content were not checked one by one; some videos were recorded in the Promtail / Tempo 2.x era, so follow this lesson for version details. All videos are in English.

Audio narration notes

The “Audio” tab reads the narration script aloud with the browser Web Speech API (en-US); English terms are pronounced with en-US; results depend on the OS speech packs. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; the narration script can be passed directly to a TTS tool to produce audio. The courseware also cannot generate video directly, so each module has a storyboard instead.

Known limitations

  • All commands in this lesson were written from the source code, chart templates and official docs of the versions above,but have not actually been run against a kind cluster in the environment that generated this courseware (including the Helm install, the myapp:1.2 image build, Alloy / Collector config, the Loki ruler sidecar, and fault-obs.sh); trace IDs, Pod name suffixes, times, counts and durations in the “expected output” are examples.
  • Loki rules sidecar annotation (k8s-sidecar-target-directory) and tenant directory,matcherType: label YAML key names, the exact JSON structure of kps-rendered exemplarTraceIdDestinations, and the Collector chart's ConfigMap key names (relay) were inferred from templates and docs, not verified line by line; follow the actual output.
  • Collector internal metric names (otelcol_*) and the Alloy / Loki self-monitoring metric names change between versions; for Tempo HTTP API return fields, follow the actual 3.1 output.
  • Span attribute names produced by OTel Python instrumentation depend on the semantic-conventions version (http.status_code and http.response.status_code,db.system and db.system.name), so adjust the attributes in the TraceQL examples to match your actual spans.
  • The image tags for telemetrygen, curlimages/curl:8.11.1, nginx:1.29-alpine, python:3.13-slim and others are written as commonly available versions and were not pulled in this environment; the compression ratio, span size and unit prices in the cost estimator are example rule-of-thumb values.
  • Loki 4.0 is in the RC stage; after GA the deployment modes, chart and storage format may change; this lesson follows 3.7.x.