OpenTelemetry & Observability
Stop flying blind in microservices. Master OpenTelemetry auto-instrumentation, Collector pipeline design, Grafana Tempo distributed tracing, Loki log correlation, eBPF zero-code observability with Beyla, and span-level SLOs. From "we have logs" to "we have answers in 30 seconds" for any production incident.
Lesson objective
- What it teaches
- OTel Architecture: The Three Pillars · OTel Collector: Enterprise Pipeline · Beyla: eBPF Zero-Code Instrumentation · Grafana Tempo + TraceQL · Hands-On Labs · Troubleshooting · Securing the eBPF Agent: Scope Privilege with Pod Security
- Why it matters
- A required lesson for SRE, MLOps / LLMOps Engineer, Observability Engineer. Recommended for Platform Engineer, DevOps / Platform Architect. See the role paths
- What you demonstrate
-
- Simulated lab: TraceQL — Grafana Tempo's query language. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 7 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Real Incident: "Checkout is slow for 8% of users"
Symptom: P99 checkout latency >8s (SLO breach). Prometheus shows average latency fine. No errors. 3 teams pointing fingers.
Without tracing: 4 engineers spending 3 hours looking at logs, metrics, guessing. Eventually blame shifts to "must be the database."
With OpenTelemetry + Tempo:
# Query Tempo for slow traces (>3s) in checkout service # TraceQL — Grafana Tempo's query language { .service.name = "checkout-api" && duration > 3s } # Result: 8% of traces show a specific span slow: # checkout-api → inventory-service → [SLOW: 6.2s avg] # └─ span: inventory.check_availability # └─ db.query: SELECT * FROM inventory WHERE sku_id IN (...) # └─ db.rows_returned: 84,000 rows ← no index on sku_id! # Cross-correlate with Loki logs using trace_id {app="inventory-service"} |= "trace_id=abc123def456" 2024-01-15T14:22:33Z WARN slow query detected duration=6.2s query="SELECT..." rows=84000 2024-01-15T14:22:33Z INFO trace_id=abc123def456 span_id=xyz789
Resolution: 22 minutes to identify root cause. Added index on sku_id. P99 dropped from 8s to 180ms. No more guessing, no more blaming teams.
OTel Architecture: The Three Pillars 17.1
OTel SDK Auto-Instrument] App2[Node.js Service
OTel SDK Auto-Instrument] App3[Java Service
OTel Java Agent] Beyla[eBPF Beyla
Zero-code sidecar] end subgraph "OTel Collector (DaemonSet)" Recv[OTLP Receiver
:4317 gRPC / :4318 HTTP] Proc[Processors
Batch, Filter, Tail-Sampling] Export[Exporters] end subgraph "Backends" Tempo[Grafana Tempo
Traces] Loki[Grafana Loki
Logs] Prom[Prometheus
Metrics] Grafana[Grafana
Unified Dashboard + Alerts] end App1 -->|OTLP| Recv App2 -->|OTLP| Recv App3 -->|OTLP| Recv Beyla -->|OTLP| Recv Recv --> Proc Proc -->|traces| Tempo Proc -->|logs| Loki Proc -->|metrics| Prom Tempo --> Grafana Loki --> Grafana Prom --> Grafana
OTel Collector: Enterprise Pipeline 17.2
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
cors:
allowed_origins: ["https://*.acme.com"]
prometheus:
config:
scrape_configs:
- job_name: 'k8s-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
processors:
batch:
timeout: 5s
send_batch_size: 1024
memory_limiter:
check_interval: 1s
limit_mib: 512
spike_limit_mib: 128
resource:
attributes:
- action: upsert
key: cluster.name
value: prod-eks-us-east-1
- action: upsert
key: deployment.environment
from_attribute: k8s.namespace.name
# Add trace IDs to logs for correlation
transform/logs:
log_statements:
- context: log
statements:
- set(attributes["trace_id"], trace_id.string) where trace_id != SpanID(0x0000000000000000)
exporters:
otlp/tempo:
endpoint: tempo.monitoring.svc.cluster.local:4317
tls:
insecure: true
loki:
endpoint: http://loki.monitoring.svc.cluster.local:3100/loki/api/v1/push
labels:
resource:
service.name: "service_name"
k8s.namespace.name: "namespace"
prometheusremotewrite:
endpoint: http://prometheus.monitoring.svc.cluster.local:9090/api/v1/write
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch, resource]
exporters: [otlp/tempo]
logs:
receivers: [otlp]
processors: [memory_limiter, batch, transform/logs]
exporters: [loki]
metrics:
receivers: [otlp, prometheus]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]# Tail-based sampling — make decisions AFTER seeing full trace
# Critical for high-volume services (>10k req/s)
# Head sampling (random %) loses important error traces
processors:
tail_sampling:
decision_wait: 10s
num_traces: 100000
expected_new_traces_per_sec: 10000
policies:
# Always keep error traces
- name: error-policy
type: status_code
status_code: {status_codes: [ERROR]}
# Always keep slow traces (>500ms)
- name: latency-policy
type: latency
latency: {threshold_ms: 500}
# Keep 1% of healthy fast traces (for baseline)
- name: probabilistic-policy
type: probabilistic
probabilistic: {sampling_percentage: 1}
# Always keep traces with specific attributes
# (e.g., payment transactions, new user signup)
- name: always-sample-payments
type: string_attribute
string_attribute:
key: transaction.type
values: [payment, refund, chargeback]
# Composite: slow OR error in checkout service
- name: checkout-composite
type: composite
composite:
max_total_spans_per_second: 1000
policy_order: [error-policy, latency-policy]
composite_sub_policy:
- name: checkout-service-filter
type: string_attribute
string_attribute:
key: service.name
values: [checkout-api]apiVersion: apps/v1
kind: DaemonSet
metadata:
name: otel-collector
namespace: monitoring
spec:
selector:
matchLabels:
app: otel-collector
template:
metadata:
labels:
app: otel-collector
spec:
serviceAccountName: otel-collector
containers:
- name: otel-collector
image: otel/opentelemetry-collector-contrib:0.95.0
args: ["--config=/conf/otel-collector-config.yaml"]
resources:
requests:
cpu: 200m
memory: 400Mi
limits:
cpu: 1000m
memory: 1Gi
ports:
- containerPort: 4317 # OTLP gRPC
- containerPort: 4318 # OTLP HTTP
- containerPort: 8888 # Prometheus metrics (self-monitoring)
volumeMounts:
- name: config
mountPath: /conf
env:
- name: KUBE_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumes:
- name: config
configMap:
name: otel-collector-config# OpenTelemetry Operator — inject instrumentation automatically
# No code changes needed. Just add an annotation to the Deployment.
apiVersion: opentelemetry.io/v1alpha1
kind: Instrumentation
metadata:
name: acme-instrumentation
namespace: production
spec:
exporter:
endpoint: http://otel-collector.monitoring.svc.cluster.local:4317
propagators:
- tracecontext
- baggage
- b3
sampler:
type: parentbased_traceidratio
argument: "1.0" # 100% sampling (use tail sampling in collector)
python:
image: ghcr.io/open-telemetry/opentelemetry-operator/autoinstrumentation-python:0.43b0
java:
image: ghcr.io/open-telemetry/opentelemetry-operator/autoinstrumentation-java:1.32.0
nodejs:
image: ghcr.io/open-telemetry/opentelemetry-operator/autoinstrumentation-nodejs:0.41.0
go:
image: ghcr.io/open-telemetry/opentelemetry-operator/autoinstrumentation-go:0.8.0
---
# Just add this annotation to any Deployment — zero code changes!
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout-api
namespace: production
spec:
template:
metadata:
annotations:
instrumentation.opentelemetry.io/inject-python: "acme-instrumentation"
# For Java: instrumentation.opentelemetry.io/inject-java: "acme-instrumentation"Collector-to-Tempo Mutual TLS & memory_limiter Backpressure Diagnostics
Telemetry transport security and load-shedding diagnostics. Assumptions: OpenTelemetry Collector v0.95.0+, Grafana Tempo v2.6.0+, and gRPC mTLS. See official OTel Collector TLS Configuration, Memory Limiter Processor, and Tempo Distributor TLS. Synthetic configuration and diagnostic exercises; no live PKI generated.
In shared Kubernetes clusters, sending unencrypted spans over cluster networks leaks HTTP headers, query parameters, and PII. Configuring mutual TLS enforces bidirectional authentication and encryption between the Collector exporter and Tempo distributor receiver:
# /etc/otelcol/config.yaml - OTLP Exporter with mTLS
exporters:
otlp/tempo:
endpoint: tempo-distributor.monitoring.svc.cluster.local:4317
tls:
insecure: false
ca_file: /etc/otel/certs/ca.crt
cert_file: /etc/otel/certs/collector.crt
key_file: /etc/otel/certs/collector.key
server_name_override: tempo-distributor.monitoring.svc.cluster.local
min_version: "1.3"
# Tempo Distributor receiver configuration
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /etc/tempo/certs/server.crt
key_file: /etc/tempo/certs/server.key
client_ca_file: /etc/tempo/certs/ca.crtMemory Limiter vs Cgroup OOM: The memory_limiter processor protects the Collector from Linux cgroup OOM termination by refusing incoming telemetry under memory pressure, forcing upstream SDKs and collectors to back off:
processors:
memory_limiter:
check_interval: 1s
limit_mib: 1536 # Hard limit: refuse incoming spans above 1536 MiB
spike_limit_mib: 384 # Soft threshold: starts load-shedding at 1152 MiB (1536 - 384)# 1. Query Collector internal metrics for memory-limiter refusals
curl -s http://localhost:8888/metrics | grep otelcol_processor_refused_spans
# 2. PromQL alert expression for sustained Collector load-shedding
# rate(otelcol_processor_refused_spans[5m]) > 0
# 3. Differentiate memory_limiter refusal from kernel OOM:
# If kernel OOM: container exit code 137, dmesg prints "oom-kill:constraint=CONSTRAINT_MEMCG"
# If memory_limiter: container stays alive, HTTP 429/503 returned to upstream clientsBeyla: eBPF Zero-Code Instrumentation 17.3
Grafana Beyla uses eBPF to capture HTTP/gRPC traces, RED metrics (Rate, Errors, Duration), and TCP connections from any application without code changes, SDKs, or language-specific agents. Ideal for legacy apps, compiled binaries, or polyglot environments.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: beyla
namespace: monitoring
spec:
template:
spec:
hostPID: true # Required for eBPF process inspection
containers:
- name: beyla
image: grafana/beyla:1.4.0
securityContext:
privileged: true # Required for eBPF
runAsUser: 0
env:
- name: BEYLA_KUBE_METADATA_ENABLE
value: "true"
- name: BEYLA_OTEL_EXPORTER_ENDPOINT
value: "http://otel-collector.monitoring.svc.cluster.local:4317"
- name: BEYLA_SERVICE_NAMESPACE
value: "production"
volumeMounts:
- name: beyla-config
mountPath: /config
args: ["--config=/config/beyla-config.yaml"]
volumes:
- name: beyla-config
configMap:
name: beyla-configdiscovery:
services:
# Instrument ALL HTTP services on standard ports
- k8s_namespace: production
k8s_deployment_name: .* # regex: all deployments
open_ports: 8080,8443,3000,9090
trace:
print_traces: false
otel_traces_export:
endpoint: http://otel-collector.monitoring.svc.cluster.local:4317
otel_metrics_export:
endpoint: http://otel-collector.monitoring.svc.cluster.local:4317
features:
# Export RED metrics: http_server_request_duration_seconds histogram
- otel-metrics-net
- application
# Filter out health check noise
filters:
application:
- metadata.name: health.*
action: excludeGrafana Tempo + TraceQL 17.4
# Find all slow traces in checkout service
{ .service.name = "checkout-api" && duration > 2s }
# Find traces with errors in any service
{ status = error }
# Find traces involving both payment-api and fraud-service
{ .service.name = "payment-api" } >> { .service.name = "fraud-service" }
# Count slow DB queries per service (span-level analysis)
{ .db.system = "postgresql" && duration > 500ms }
| by(.service.name)
| count() > 10
# P99 latency per service — use in alerting
{ .service.name =~ ".*-api" }
| by(.service.name)
| p99(duration)
# Find traces where inventory span is slow but parent is healthy
{ .service.name = "inventory-service" && duration > 1s && parent.duration < 200ms }# Step 1: Find slow trace IDs in Tempo (TraceQL)
{ .service.name = "checkout-api" && duration > 3s }
# → Returns trace IDs like: abc123def456, xyz789abc012
# Step 2: Jump to Loki logs for that trace (Grafana does this automatically)
# In Loki data source, Derived Fields config:
# Name: TraceID
# Regex: "trace_id=(\w+)"
# Internal Link: Tempo data source
# Query: ${__value.raw}
# Step 3: LogQL to find all logs in that trace
{namespace="production"} |= "trace_id=abc123def456"
# Step 4: LogQL with JSON parsing to find the actual error
{app="checkout-api"} | json | level="error" | duration_ms > 3000
# Step 5: Histogram of log volume correlated with error rate
sum by (app) (
rate({namespace="production", level="error"}[5m])
)# Python FastAPI — Prometheus exemplars linking metrics to traces
from prometheus_client import Histogram
from opentelemetry import trace
REQUEST_DURATION = Histogram(
'http_request_duration_seconds',
'HTTP request duration',
['method', 'endpoint', 'status']
)
@app.middleware("http")
async def metrics_middleware(request: Request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
# Get current trace context for exemplar
span = trace.get_current_span()
trace_id = format(span.get_span_context().trace_id, '032x')
# Record histogram with exemplar (trace_id attached to data point)
REQUEST_DURATION.labels(
method=request.method,
endpoint=request.url.path,
status=response.status_code
).observe(
duration,
exemplar={'TraceID': trace_id} # Links metric spike to trace
)
return response
# In Grafana: enable exemplars on Prometheus data source
# When you see a latency spike, click the diamond = jump to traceSpan-Derived SLOs: OTel spanmetrics Connector & Multi-Window Alerting
Service level objective engineering from trace spans. Assumptions: OTel Collector Contrib v0.95.0+, Prometheus v2.50+. See official OTel spanmetrics Connector, OpenTelemetry Sampling Concepts, and Google SRE Multiwindow Alerting. Synthetic calculations; no live traffic evaluated.
Critical Architectural Warning: Span Sampling Survival Bias: You must never calculate SLIs or SLOs from head- or tail-sampled trace data. If tail sampling retains 100% of errors and only 1% of successful requests, computing error rates from sample traces reports a false ~50% error rate when the true error rate is 0.5%. To avoid survival bias, deploy the OTel Collector spanmetrics connector before any sampling processor:
connectors:
spanmetrics:
histogram:
explicit:
buckets: [10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s]
dimensions:
- name: http.status_code
- name: http.route
- name: service.name
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter]
exporters: [spanmetrics, otlp/tempo] # spanmetrics processes 100% of spans before sampling!
metrics/spanmetrics:
receivers: [spanmetrics]
exporters: [prometheus]With unsampled metrics emitted by the connector, define a production multi-window multi-burn-rate PromQL alert rule for checkout-api (SLO target: 99.0% requests under 500ms over 30 days):
groups:
- name: span-slo-alerts
rules:
- alert: CheckoutLatencyBudgetBurnHigh
expr: |
(
sum(rate(traces_spanmetrics_latency_bucket{service_name="checkout", le="0.5"}[1h]))
/
sum(rate(traces_spanmetrics_calls_total{service_name="checkout"}[1h])) < 0.90
)
and
(
sum(rate(traces_spanmetrics_latency_bucket{service_name="checkout", le="0.5"}[5m]))
/
sum(rate(traces_spanmetrics_calls_total{service_name="checkout"}[5m])) < 0.90
)
for: 2m
labels:
severity: critical
tier: p1
annotations:
summary: "14.4x burn rate: Checkout 500ms latency SLO error budget exhausting rapidly"Tempo & Loki Storage Sizing, Compaction & Retention Architecture
Object store capacity planning and compaction parameters. Assumptions: Grafana Tempo v2.6+ (Apache Parquet storage format), Grafana Loki v3.2+ (TSDB index). See official Tempo Storage Architecture and Loki Retention & Compactor. Worked sample arithmetic; no live object storage billed.
Storage sizing depends on ingestion rates, uncompressed payload sizes, columnar compression ratios, and retention durations. The worked table below demonstrates capacity calculation for a 5,000 requests/second production fleet:
| Parameter | Loki (Logs) | Tempo (Traces with Parquet) |
|---|---|---|
| Raw Ingress Rate | 5,000 logs/sec @ 800 bytes = 4.0 MB/sec | 5,000 spans/sec @ 1.2 KB = 6.0 MB/sec |
| Daily Raw Volume | 4.0 MB/sec × 86,400s = 345.6 GB/day | 6.0 MB/sec × 86,400s = 518.4 GB/day |
| Storage Engine Format | TSDB chunks (Gzip compression ~85%) | Apache Parquet v2 (Snappy / Zstd ~80%) |
| Compressed Daily Disk | 345.6 GB × 0.15 = 51.8 GB/day | 518.4 GB × 0.20 = 103.7 GB/day |
| Retention Period | 30 days | 14 days |
| Compactor Headroom | +25% compactor work buffer | +30% compaction block staging buffer |
| Total Required S3/GCS | 51.8 × 30 × 1.25 = 1,942 GB (1.9 TB) | 103.7 × 14 × 1.30 = 1,887 GB (1.9 TB) |
Retention enforcement in object storage is driven by the backend compactor workers. Configuration knobs must be coordinated between compactor execution and index schemas:
# Tempo compactor retention config (tempo.yaml)
compactor:
compaction:
block_retention: 336h # 14 days block retention in S3/GCS
compacted_block_retention: 1h
retention_concurrency: 4
# Loki compactor retention config (loki.yaml)
compactor:
retention_enabled: true
retention_delete_delay: 2h
delete_request_store: s3
schema_config:
configs:
- from: "2024-01-01"
store: tsdb
object_store: s3
schema: v13
limits_config:
retention_period: 720h # 30 days stream retentionHands-On Labs 17.5
Observability Labs — Grafana Stack on kind
- Deploy Grafana stack (Tempo, Loki, Prometheus, Grafana) via Helm on kind cluster
- Deploy OTel Collector as DaemonSet with the enterprise config — verify OTLP receiver working
- Install OTel Operator, create Instrumentation CR, annotate a Python app — verify traces in Tempo
- Write TraceQL query to find all error traces with duration >1s in last 1 hour
- Configure Loki Derived Fields to create trace ID links — jump from log line to trace
- Build a tail-sampling policy that keeps 100% of errors + slow spans, 1% of healthy spans
- Deploy Grafana Beyla as DaemonSet — verify RED metrics appear without code changes
Troubleshooting 17.6
Traces not appearing in Tempo
Check OTel Collector logs: kubectl logs -n monitoring ds/otel-collector. Common issues: application not exporting to correct endpoint (check OTEL_EXPORTER_OTLP_ENDPOINT env var), network policy blocking port 4317, Tempo not receiving via its OTLP ingestion endpoint. Use otelcol --feature-gates=telemetry.useOtelForInternalMetrics to debug collector internals.
OTel auto-instrumentation not injecting
Check: (1) Instrumentation CR namespace matches Deployment namespace. (2) The correct annotation key used (e.g., inject-python vs inject-java). (3) OTel Operator webhook is running: kubectl get pods -n opentelemetry-operator-system. (4) Pod must be restarted after annotation added. Check operator logs for admission webhook errors.
Collector OOMKilling at high trace volume
Add memory_limiter processor (first in pipeline). Increase DaemonSet memory limits. Consider scaling to a Gateway Collector deployment for high-volume scenarios. Enable tail sampling to reduce volume before exporting. Monitor collector's own metrics via :8888/metrics.
Securing the eBPF Agent: Scope Privilege with Pod Security 17.7
Beyla (section 17.3) needs privileged: true, hostPID: true and root to attach eBPF probes to every process on the node. That is node-level access: a compromised agent can read any process's memory. Do not lower the guard for everything to make it run. Keep product namespaces at the Pod Security baseline level and give the agent a namespace of its own that is allowed privileged.
Recorded from a real run of scripts/recordings/observability.sh; every output below is pasted from scripts/recordings/observability.out. Cover the output, predict it, then compare.
Environment: minikube v1.34.0 (Kubernetes v1.31.0, built-in Pod Security admission). apps is labelled enforce=baseline, beyla is labelled enforce=privileged.
# Beyla needs eBPF access to every process on the node: privileged, hostPID, root.
# The namespace it runs in decides whether Pod Security admission lets those pods exist.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: beyla
spec:
selector:
matchLabels:
app: beyla
template:
metadata:
labels:
app: beyla
spec:
hostPID: true
containers:
- name: beyla
image: grafana/beyla:1.4.0
securityContext:
privileged: true
runAsUser: 0
env:
- name: BEYLA_OPEN_PORT
value: "8080"
- name: BEYLA_TRACE_PRINTER
value: text# Namespace labels $ kubectl label ns apps pod-security.kubernetes.io/enforce=baseline $ kubectl label ns beyla pod-security.kubernetes.io/enforce=privileged # Apply the DaemonSet in the product namespace $ kubectl -n apps apply -f beyla-daemonset.yaml Warning: would violate PodSecurity "baseline:latest": host namespaces (hostPID=true), privileged (container "beyla" must not set securityContext.privileged=true) daemonset.apps/beyla created # Did any pod start? $ kubectl -n apps get ds beyla -o jsonpath='desired={.status.desiredNumberScheduled} current={.status.currentNumberScheduled}'; echo desired=1 current=0 # Why not $ kubectl -n apps get events --field-selector reason=FailedCreate -o custom-columns=MESSAGE:.message --no-headers | tail -1 (combined from similar events): Error creating: pods "beyla-6hm2b" is forbidden: violates PodSecurity "baseline:latest": host namespaces (hostPID=true), privileged (container "beyla" must not set securityContext.privileged=true) # The same manifest in the dedicated namespace $ kubectl -n beyla apply -f beyla-daemonset.yaml daemonset.apps/beyla created # Did any pod start this time? $ kubectl -n beyla get ds beyla -o jsonpath='desired={.status.desiredNumberScheduled} current={.status.currentNumberScheduled}'; echo desired=1 current=1
Pod Security only warns when a controller such as a DaemonSet is created; it enforces when the pods are, so the failure shows up as FailedCreate events and current=0, not as an apply error. Restrict who can create workloads in the privileged namespace with RBAC. The Tempo exporter in section 17.2 uses tls: insecure: true; across a network, set insecure: false with a ca_file so spans, which can carry user data in attributes, are encrypted in transit.