Lab: from a latency alert to the slow span
Send ask-api's telemetry through an OpenTelemetry Collector to Prometheus and Jaeger, inject a slow dependency, and follow the regression from a firing alert to an exemplar, from the exemplar to the slow span, and from the span's logs to the cause, then confirm it across all requests.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start the telemetry backends
- Step 2: Point the services at the Collector and record a baseline
- Step 3: Ship the regression and watch the alert fire
- Step 4: From the alert to a slow trace
- Step 5: Ask the logs why, then confirm with metrics
- Step 6: Roll back and watch the alert clear
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Observability
- Three signals and the questions each one answers Concept · 15 min
- Lab: instrument a service and its outbound calls, including a model call, with OpenTelemetry Lab · 35 min
- PromQL and a rate-errors-duration dashboard Worked example · 25 min
- SLOs, black-box probes and alerts worth waking up for Concept · 25 min
- Lab: from a latency alert to the slow span Lab · 25 min
- Check: alert and dashboard review Knowledge check · 8 questions
What you will learn
- Use logs, metrics and traces together to localize a latency or error regression to a specific component.
01. Goal and setup
In this lab a teammate ships version 1.4.0 of the search service, and from then on about one search in five takes close to a second. Nobody tells you. What you see is a latency alert on ask-api. Your job is to find which component is slow and why, using the three signals in the order that narrows the search fastest: metrics, then traces through exemplars, then logs, then metrics again to confirm.
You need: the ask-service folder from lab 2 with make_dashboard.py from lesson 3, Docker with the Compose plugin (the docker compose command), about 2.5 GB of disk for the images (OpenTelemetry Collector Contrib 0.165.0, Jaeger 2.23.0, Prometheus v3.16.0, Grafana 13.3.1) and free ports 3000, 4318, 9090 and 16686. The services still run on your machine; only the backends run in containers. No new Python packages are needed.
ask-service/ from lab 2, plus:
├── make_dashboard.py from lesson 3
├── load.py step 2: steady traffic, 10 requests a second
├── promq.py step 2: run a PromQL query from the terminal
├── exemplars.py step 4: trace IDs of the slowest recent requests
├── show_trace.py step 4: one trace from Jaeger as a tree
└── stack/
├── compose.yaml Collector, Jaeger, Prometheus, Grafana
├── otel-collector.yaml OTLP in; traces to Jaeger, metrics to Prometheus
├── prometheus.yml OTLP receiver settings and the rule file
├── rules.yml the latency alert
└── grafana/ data source and dashboard provisioning02. Step 1: Start the telemetry backends
The Collector is the one address your services know. It receives OTLP over HTTP on port 4318, batches the data and fans it out: traces to Jaeger, metrics to Prometheus's own OTLP endpoint. Swapping Jaeger for Tempo, or adding Loki for logs, later means editing this file, not the services. The exporter names otlp_grpc and otlp_http are the current ones; older guides call them otlp and otlphttp, which this Collector still accepts with a warning.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
batch: {}
exporters:
otlp_grpc/jaeger:
endpoint: jaeger:4317
tls:
insecure: true
otlp_http/prometheus:
endpoint: http://prometheus:9090/api/v1/otlp
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp_grpc/jaeger]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [otlp_http/prometheus]Prometheus needs three things for pushed OTLP data: the receiver switched on (a command-line flag in the Compose file), exemplar storage switched on (so histogram buckets keep trace IDs), and a little configuration. promote_resource_attributes copies service.version from the resource onto every series, so you can compare releases; job is set from service.name automatically.
global:
evaluation_interval: 15s
otlp:
# Copy service.version onto every series, to compare releases.
promote_resource_attributes: [service.version]
storage:
tsdb: # OTLP pushes can arrive slightly out of order
out_of_order_time_window: 30m
rule_files: [/etc/prometheus/rules.yml]The alert is a lab-sized latency SLI: it fires when more than 5% of /ask requests over the last minute took longer than 0.5 s, the boundary of one of the histogram's buckets. It is labelled ticket; in production you would turn it into burn-rate alerts with the windows from lesson 4.
groups:
- name: ask-api-latency
rules:
- alert: AskApiSlowRequests
# Share of /ask requests slower than 0.5 s, over the last minute.
expr: |
1 - (
sum(rate(http_server_request_duration_seconds_bucket{
job="ask-api", http_route="/ask", le="0.5"}[1m]))
/
sum(rate(http_server_request_duration_seconds_count{
job="ask-api", http_route="/ask"}[1m]))
) > 0.05
for: 30s
labels:
severity: ticket
annotations:
summary: "More than 5% of /ask requests take longer than 0.5 s"Grafana is provisioned from files: a Prometheus data source whose exemplars link to the Jaeger UI, and the dashboard folder that lesson 3's script writes into. $$ stops Grafana from treating ${__value.raw} as an environment variable when it reads the file.
apiVersion: 1
datasources:
- name: Prometheus
uid: prom
type: prometheus
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 15s
# Turn the trace_id label of an exemplar into a link to the Jaeger UI.
exemplarTraceIdDestinations:
- name: trace_id
url: http://localhost:16686/trace/$${__value.raw} # $$ = literal $apiVersion: 1
providers:
- name: files
type: file
options:
path: /var/lib/grafana/dashboardsservices:
collector:
image: otel/opentelemetry-collector-contrib:0.165.0
command: ["--config=/etc/otelcol/config.yaml"]
volumes: ["./otel-collector.yaml:/etc/otelcol/config.yaml:ro"]
ports: ["4318:4318"] # OTLP over HTTP from the services
depends_on: [jaeger, prometheus]
jaeger:
image: jaegertracing/jaeger:2.23.0
ports: ["16686:16686"] # UI and query API
prometheus:
image: prom/prometheus:v3.16.0
command:
- --config.file=/etc/prometheus/prometheus.yml
- --web.enable-otlp-receiver # accept OTLP metrics pushes
- --enable-feature=exemplar-storage # keep trace IDs on buckets
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./rules.yml:/etc/prometheus/rules.yml:ro
ports: ["9090:9090"]
grafana:
image: grafana/grafana:13.3.1-slim
volumes:
- ./grafana/provisioning:/etc/grafana/provisioning:ro
- ./grafana/dashboards:/var/lib/grafana/dashboards:ro
ports: ["3000:3000"] # log in as admin / adminpython make_dashboard.py
cd stack && docker compose up -d && cd ..
sleep 30
curl -s http://127.0.0.1:9090/-/ready
curl -s -o /dev/null -w 'jaeger %{http_code}\n' http://127.0.0.1:16686/
curl -s -o /dev/null -w 'grafana %{http_code}\n' http://127.0.0.1:3000/loginwrote stack/grafana/dashboards/ask-api-red.json with 3 panels
Prometheus Server is Ready.
jaeger 200
grafana 20003. Step 2: Point the services at the Collector and record a baseline
setup_telemetry() from lab 2 already switches to OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set: spans go through a batch processor and metrics are pushed every five seconds. The services keep writing JSON logs to logs/, now appending. Two small helpers do the rest: load.py sends steady traffic and reports what clients saw, and promq.py runs a PromQL query through Prometheus's HTTP API.
"""Send steady traffic to /ask and summarise what the clients saw."""
import asyncio
import statistics
import sys
import time
import httpx
TOTAL = int(sys.argv[1]) if len(sys.argv) > 1 else 300
PER_SECOND = 10
QUESTIONS = ["How do I drain the queue?", "When are refunds paid?", "Who is on call?"]
async def one(client: httpx.AsyncClient, i: int, results: list) -> None:
started = time.perf_counter()
resp = await client.post("/ask", json={"question": QUESTIONS[i % 3]})
results.append((resp.status_code, time.perf_counter() - started))
async def main() -> None:
results: list[tuple[int, float]] = []
async with httpx.AsyncClient(base_url="http://127.0.0.1:8000", timeout=10) as c:
tasks = []
for i in range(TOTAL):
tasks.append(asyncio.create_task(one(c, i, results)))
await asyncio.sleep(1 / PER_SECOND)
await asyncio.gather(*tasks)
seconds = sorted(s for _, s in results)
ok = sum(1 for code, _ in results if code == 200)
p50 = statistics.median(seconds)
p95 = seconds[int(0.95 * len(seconds)) - 1]
print(f"{len(results)} requests, {ok} OK, p50 {p50:.2f} s, p95 {p95:.2f} s")
asyncio.run(main())"""Run a PromQL instant query against Prometheus and print the result."""
import sys
import httpx
query = sys.argv[1]
resp = httpx.get("http://127.0.0.1:9090/api/v1/query", params={"query": query})
rows = resp.json()["data"]["result"]
for row in sorted(rows, key=lambda r: sorted(r["metric"].items())): # stable order
labels = ",".join(f"{k}={v}" for k, v in row["metric"].items() if k != "__name__")
print(f"{{{labels}}} {float(row['value'][1]):.3f}")Stop the lab 2 processes if they are still running: in the terminal that started them, kill $SEARCH_PID $MODEL_PID $API_PID; from any other terminal, kill $(lsof -t -iTCP:8000-8002 -sTCP:LISTEN), which stops only your own processes that listen on the lab ports. Then start all three with the endpoint set, in the same terminal you will use for the rest of the lab, and send 30 seconds of traffic. Each ..._PID=$! line saves the process ID of the service just started, so later steps can restart or stop exactly that process.
export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
SERVICE_NAME=search-stub uvicorn stubs:app --port 8001 --no-access-log \
>> logs/search-stub.jsonl 2>> logs/search-stub.err &
SEARCH_PID=$!
SERVICE_NAME=model-stub uvicorn stubs:app --port 8002 --no-access-log \
>> logs/model-stub.jsonl 2>> logs/model-stub.err &
MODEL_PID=$!
uvicorn app:app --port 8000 --no-access-log >> logs/ask-api.jsonl 2>> logs/ask-api.err &
API_PID=$!
sleep 3
python load.py 300300 requests, 300 OK, p50 0.15 s, p95 0.16 sWait about 15 seconds for the last metrics to arrive, then take the baseline p95 of every route of every service. (http_route!="" skips requests to unknown paths, which have no route label.)
python promq.py 'histogram_quantile(0.95, sum by (le, job, http_route) (
rate(http_server_request_duration_seconds_bucket{http_route!=""}[5m])))'{http_route=/ask,job=ask-api} 0.242
{http_route=/search,job=search-stub} 0.024
{http_route=/v1/messages,job=model-stub} 0.242Write these numbers down: a regression is a difference from a baseline. Read them as bucket positions, not exact timings. Every /ask and model request takes between 0.1 and 0.25 s, so all of them land in the bucket with those edges, and histogram_quantile() assumes requests are spread evenly inside a bucket: the 95th percentile comes out at 0.1 + 0.95 × 0.15 ≈ 0.242 s for both routes, although the requests really took about 0.15 s and 0.12 s. Search requests land in the 0.01–0.025 s bucket, hence 0.024. The baseline is still useful: when slow requests start landing in higher buckets, the p95 moves. Open http://localhost:3000 (user admin, password admin) to see the same data on the RED dashboard from lesson 3.
04. Step 3: Ship the regression and watch the alert fire
Restart the search stub as version 1.4.0 with the fault switched on: every fifth search sleeps an extra 800 ms. Then send 90 seconds of traffic, enough for the alert's one-minute window and its 30-second for, and list the alerts that are firing. wait returns once the old stub has exited, and bash may print a Terminated line for it; that is expected.
kill $SEARCH_PID
wait $SEARCH_PID # until the old stub has exited and freed port 8001
SERVICE_NAME=search-stub SERVICE_VERSION=1.4.0 SLOW_EVERY=5 SLOW_MS=800 \
uvicorn stubs:app --port 8001 --no-access-log \
>> logs/search-stub.jsonl 2>> logs/search-stub.err &
SEARCH_PID=$!
sleep 3
python load.py 900
python promq.py 'ALERTS{alertstate="firing"}'900 requests, 900 OK, p50 0.16 s, p95 0.96 s
{alertname=AskApiSlowRequests,alertstate=firing,severity=ticket} 1.000Read the client summary closely. The median barely moved (0.15 s to 0.16 s) while p95 rose sixfold, from 0.16 s to 0.96 s. A shift in the tail but not the middle points to something that slows some requests a lot, not everything a little: a cache, a retry, one bad replica, one slow shard. An average would have blurred exactly that distinction. You now know that and when; the next step is where.
05. Step 4: From the alert to a slow trace
You could search Jaeger for slow traces of ask-api in the last few minutes, and in a small system that works. Exemplars are more direct: each histogram bucket kept the trace ID of a real request that landed in it. The OpenTelemetry SDK records exemplars for measurements made inside a sampled span, and Prometheus stored them because exemplar storage is on. exemplars.py asks Prometheus's exemplar API for the last ten minutes and prints the slowest three.
"""List the slowest exemplars of a histogram from the last 10 minutes."""
import sys
import time
import httpx
now = time.time()
params = {"query": sys.argv[1], "start": now - 600, "end": now}
resp = httpx.get("http://127.0.0.1:9090/api/v1/query_exemplars", params=params)
found = [
(float(e["value"]), e["labels"]["trace_id"])
for series in resp.json()["data"]
for e in series["exemplars"]
]
for seconds, trace_id in sorted(found, reverse=True)[:3]:
print(f"{seconds:6.3f} s trace_id={trace_id}")python exemplars.py 'http_server_request_duration_seconds_bucket{job="ask-api"}' 0.965 s trace_id=7e25526d73fc974019420d69b020d991
0.962 s trace_id=0a32c85c7afd17d5ff6bcb8d177d8eff
0.958 s trace_id=f8abfa5ad08afbdffce8798111a124abFetch the first trace from Jaeger's query API and print it as a tree. (/api/traces/{id} is the API the Jaeger UI uses; Jaeger 2 also offers a versioned /api/v3/ API.)
"""Print one trace from Jaeger as an indented tree with durations."""
import sys
import httpx
trace_id = sys.argv[1]
data = httpx.get(f"http://127.0.0.1:16686/api/traces/{trace_id}").json()["data"][0]
services = {key: p["serviceName"] for key, p in data["processes"].items()}
spans = {s["spanID"]: s for s in data["spans"]}
children: dict[str | None, list] = {}
for s in data["spans"]:
parents = [r["spanID"] for r in s["references"] if r["refType"] == "CHILD_OF"]
children.setdefault(parents[0] if parents else None, []).append(s)
def show(span: dict, depth: int) -> None:
label = f"{' ' * depth}{services[span['processID']]}: {span['operationName']}"
print(f"{label:<46} {span['duration'] / 1000:8.1f} ms")
for child in sorted(children.get(span["spanID"], []), key=lambda c: c["startTime"]):
show(child, depth + 1)
for root in children[None]:
show(root, 0)python show_trace.py 7e25526d73fc974019420d69b020d991 # your first trace_idask-api: POST /ask 965.0 ms
ask-api: GET 825.1 ms
search-stub: GET /search 822.9 ms
ask-api: chat claude-sonnet-5 136.8 ms
ask-api: POST 134.2 ms
model-stub: POST /v1/messages 130.6 msRead the tree top-down and follow the time. Of 965 ms, the model branch accounts for 137 ms and the search branch for 825 ms, of which the search service's own handler spent 823 ms. ask-api's code between the calls is a few milliseconds. The slow component is the search service, inside its handler, not the network: the client span and the server span are close in length.
In Grafana, the same jump is one click: the p95 panel of the RED dashboard shows exemplar dots, and the trace_id link on a dot opens the trace in the Jaeger UI.
06. Step 5: Ask the logs why, then confirm with metrics
The trace says where; the logs written during that trace say why. Pull every log line of the trace from all services:
python find_logs.py 7e25526d73fc974019420d69b020d99101:56:22.642 search-stub INFO search
01:56:22.662 search-stub WARNING index segment not cached, reading from disk segment=6
01:56:23.605 ask-api INFO answered hits=2One trace is an anecdote. Before you page the search team, check that the explanation covers all the slow requests, not just this one. The promoted service_version label makes that a single query: p95 by service and version over the last five minutes.
python promq.py 'histogram_quantile(0.95, sum by (le, job, service_version) (
rate(http_server_request_duration_seconds_bucket{http_route!=""}[5m])))'{job=ask-api,service_version=dev} 0.920
{job=model-stub,service_version=dev} 0.242
{job=search-stub,service_version=1.4.0} 0.938
{job=search-stub,service_version=dev} 0.024The case is closed. Search p95 is 0.024 s on dev and 0.938 s on 1.4.0; model latency did not change, so slow searches explain the whole rise in ask-api's tail. You have localised the regression to a component (the search service), a change (version 1.4.0) and a mechanism (index segments read from disk), with evidence from all three signals.
07. Step 6: Roll back and watch the alert clear
Restart the search stub without the fault, as the previous version, send another 90 seconds of traffic and count the firing alerts. or vector(0) makes the query print 0 instead of nothing.
kill $SEARCH_PID
wait $SEARCH_PID
SERVICE_NAME=search-stub uvicorn stubs:app --port 8001 --no-access-log \
>> logs/search-stub.jsonl 2>> logs/search-stub.err &
SEARCH_PID=$!
sleep 3
python load.py 900
sleep 20
python promq.py 'count(ALERTS{alertstate="firing"}) or vector(0)'900 requests, 900 OK, p50 0.16 s, p95 0.16 s
{} 0.000When you have finished, stop everything and remove the containers and their volumes:
kill $SEARCH_PID $MODEL_PID $API_PID
cd stack && docker compose down -v && cd ..08. Troubleshooting
09. Check your understanding
10. Apply it
Stretch tasks for the skill project:
- Inject a different fault: make the model stub fail one request in ten with 529 and walk the same path for an error regression, starting from the error ratio panel and the 502 series.
- Ship logs through the pipeline too: add Loki to the Compose file and a
filelogreceiver forlogs/*.jsonlto the Collector, then find the warning by trace ID in Grafana instead of withfind_logs.py. - Replace the lab alert with the burn-rate rules from lesson 4, driven by a blackbox exporter probe of
POST /ask, and check how long the injected fault takes to page.
11. Review prompt
Without looking back, write the five steps you took from the firing alert to the confirmed cause, naming the signal, the tool and the ID or label that carried you to the next step each time. Then explain why the final metrics query was needed after you had already found a slow trace and its warning.
References
- OpenTelemetry documentation
- OpenTelemetry Collector
- OpenTelemetry Collector: Configuration
- Prometheus: Using Prometheus as an OpenTelemetry backend
- Prometheus: Feature flags
- Prometheus: HTTP API
- Jaeger: Getting started
- Grafana: Introduction to exemplars
- Grafana: Configure the Prometheus data source
- Google SRE Book: Monitoring Distributed Systems
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.