Lab: instrument a service and its outbound calls, including a model call, with OpenTelemetry
Instrument a FastAPI service and its httpx calls to a search service and a model API with the OpenTelemetry Python SDK, record the model call with the GenAI conventions and content capture off, write JSON logs that carry trace and span IDs, and follow one request, including a failed one, across three processes.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: One module that sets up all three signals
- Step 2: Stand-ins for the search service and the model API
- Step 3: The service, with automatic and manual spans
- Step 4: Follow one request across three processes
- Step 5: Read the request metrics
- Step 6: Make the model call fail
- 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
- Instrument a service with OpenTelemetry so it emits structured logs, request metrics and distributed traces that share correlation IDs.
01. Goal and setup
You will build ask-api, a small FastAPI service that answers a question in two outbound calls: it fetches passages from a search service, then sends them to a model API. Two stand-ins play the upstreams, so the lab runs offline and costs nothing: a search stub, and a model stub that speaks the shape of Anthropic's Messages API, including its 529 overloaded_error. By the end, every request produces three kinds of telemetry that share one trace ID:
- traces: a server span per request, a client span per outbound call and a model-call span with
gen_ai.*attributes, continued inside the stubs through the W3Ctraceparentheader; - metrics: the
http.server.request.durationhistogram, by route, method and status code; - logs: one JSON object per line, stamped with
trace_idandspan_id.
You need: Python 3.12, curl, and about 50 MB for the packages below (tested on 17 November 2026 with OpenTelemetry SDK 1.45.2 and instrumentation 0.66b2; the instrumentation packages still carry a beta version number). Telemetry goes to the terminal and to a local /metrics page here; lesson 5 sends the same data through a Collector to Prometheus and Jaeger without changing the application code.
ask-service/
├── telemetry.py step 1: providers, exporters and JSON logs
├── smoke.py step 1: a quick look at the log format
├── stubs.py step 2: stand-ins for the search service and the model API
├── app.py step 3: ask-api itself
├── find_logs.py step 4: every log line of one trace
├── show_metrics.py step 5: the request histogram, compactly
└── logs/ *.jsonl = JSON logs (stdout), *.err = spans (stderr)mkdir -p ask-service/logs && cd ask-service
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install fastapi==0.163.1 uvicorn==0.54.0 httpx==0.28.1 \
opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-http==1.45.2 \
opentelemetry-instrumentation-fastapi==0.66b2 \
opentelemetry-instrumentation-httpx==0.66b2 \
opentelemetry-exporter-prometheus==0.66b202. Step 1: One module that sets up all three signals
Every process in this lab calls one function, setup_telemetry(), before it does anything else. It creates a resource that names the service (every span and metric carries service.name), installs a tracer provider and a meter provider as process-wide globals, and points the root logger at a JSON formatter. Instrumentation libraries look up the global providers when they start, so the order matters: set up telemetry first, then instrument.
"""OpenTelemetry setup shared by ask-api and the two stubs."""
import json
import logging
import os
import sys
from datetime import UTC, datetime
# Emit the stable HTTP conventions: http.server.request.duration, in seconds.
os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "http")
from opentelemetry import metrics, trace
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
)
from opentelemetry.trace import StatusCode
def one_line(span: ReadableSpan) -> str:
"""Format a finished span as one line; IDs are cut to 8 hex digits."""
ctx = span.get_span_context()
trace_id = f"{ctx.trace_id:032x}"[:8]
span_id = f"{ctx.span_id:016x}"[:8]
parent = f"{span.parent.span_id:016x}"[:8] if span.parent else "-"
ms = (span.end_time - span.start_time) / 1e6
name = f"[{span.resource.attributes['service.name']}] {span.name}"
kind = span.kind.name
error = " ERROR" if span.status.status_code is StatusCode.ERROR else ""
return f"{name:<33} {kind:<6} {ms:7.1f} ms {trace_id} {span_id} {parent}{error}\n"
class JsonFormatter(logging.Formatter):
"""One JSON object per line, stamped with the active trace and span IDs."""
def __init__(self, service: str) -> None:
super().__init__()
self.service = service
def format(self, record: logging.LogRecord) -> str:
ctx = trace.get_current_span().get_span_context()
entry = {
"ts": datetime.fromtimestamp(record.created, UTC).isoformat(
timespec="milliseconds"
),
"level": record.levelname,
"service": self.service,
"msg": record.getMessage(),
"trace_id": f"{ctx.trace_id:032x}" if ctx.is_valid else None,
"span_id": f"{ctx.span_id:016x}" if ctx.is_valid else None,
}
entry.update(getattr(record, "fields", {}))
if record.exc_info:
entry["error"] = self.formatException(record.exc_info)
return json.dumps(entry)
def setup_telemetry(service: str, metrics_port: int | None = None) -> logging.Logger:
resource = Resource.create(
{
"service.name": service,
"service.version": os.environ.get("SERVICE_VERSION", "dev"),
}
)
tracer_provider = TracerProvider(resource=resource)
readers = []
if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
# Lab 5: ship everything to a Collector over OTLP/HTTP.
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
OTLPMetricExporter,
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(), export_interval_millis=5000
)
readers.append(reader)
else:
# Local development: spans to stderr, metrics on a /metrics page.
exporter = ConsoleSpanExporter(out=sys.stderr, formatter=one_line)
tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))
if metrics_port:
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from prometheus_client import start_http_server
start_http_server(metrics_port)
readers.append(PrometheusMetricReader())
trace.set_tracer_provider(tracer_provider)
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=readers))
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter(service))
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)
logging.getLogger("httpx").setLevel(logging.WARNING) # spans cover each call
return logging.getLogger(service)Four decisions in this file are worth understanding:
- Stable HTTP names. The FastAPI and httpx instrumentations still emit the older HTTP conventions by default. Setting
OTEL_SEMCONV_STABILITY_OPT_IN=httpswitches them to the stable ones, so you gethttp.server.request.durationin seconds withhttp.routeandhttp.response.status_code, the names the PromQL in lesson 3 uses. - Two export paths. With
OTEL_EXPORTER_OTLP_ENDPOINTset, spans and metrics go out over OTLP (lesson 5). Without it, spans are printed one per line and metrics are served on a Prometheus/metricspage. - Simple versus batch.
SimpleSpanProcessorexports each span as it ends, handy while developing.BatchSpanProcessorqueues spans and exports them from a background thread, so a slow backend does not delay requests (when its queue of 2,048 spans is full, it drops new spans instead of waiting); use it whenever spans leave the process. - Logs read the active span.
JsonFormatterlooks up the current span context for every record, so alog.info()made while handling a request carries that request's IDs without passing them around. Extra fields go in throughextra={"fields": {...}}.
Check the log format with a two-line script, before any web server is involved. Spans go to stderr and logs to stdout, so the pipe pretty-prints only the logs.
from opentelemetry import trace
from telemetry import setup_telemetry
log = setup_telemetry("smoke")
log.info("outside any span")
with trace.get_tracer("smoke").start_as_current_span("demo"):
log.info("inside a span", extra={"fields": {"step": 1}})python smoke.py | python -m json.tool --json-lines[smoke] demo INTERNAL 0.2 ms f01da39b 1906732a -
{
"ts": "2026-11-17T02:01:05.144+00:00",
"level": "INFO",
"service": "smoke",
"msg": "outside any span",
"trace_id": null,
"span_id": null
}
{
"ts": "2026-11-17T02:01:05.145+00:00",
"level": "INFO",
"service": "smoke",
"msg": "inside a span",
"trace_id": "f01da39ba0942cbd7b060ff3a5a65c76",
"span_id": "1906732a315e0170",
"step": 1
}The record written outside any span has null IDs; the one inside carries the IDs of the demo span, whose first eight hex digits appear in the span line. Logs written at start-up, outside any request, will always look like the first record.
03. Step 2: Stand-ins for the search service and the model API
stubs.py is one FastAPI app with two routes. You run it twice under different service names, so traces show two separate upstream services. The search route logs the traceparent header it receives, which lets you see context propagation with your own eyes, and has a switch you will use in lesson 5 to make every Nth search slow. The model route answers in the shape of the Messages API, with token usage, and returns 529 overloaded_error when the prompt contains OVERLOAD, so you can trigger a provider error on purpose.
"""Stand-ins for the two upstreams: a search service and a model API.
Run the same file twice with different SERVICE_NAME values, so each process
reports as its own service in traces.
"""
import asyncio
import itertools
import os
import uuid
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from telemetry import setup_telemetry
SERVICE = os.environ.get("SERVICE_NAME", "stub")
SLOW_EVERY = int(os.environ.get("SLOW_EVERY", "0")) # 0 = never slow
SLOW_MS = int(os.environ.get("SLOW_MS", "800"))
log = setup_telemetry(SERVICE)
app = FastAPI()
FastAPIInstrumentor.instrument_app(app, exclude_spans=["receive", "send"])
calls = itertools.count(1)
DOCS = [
{"id": "runbook-12", "text": "Restart the worker pool before clearing the queue."},
{"id": "faq-3", "text": "Refunds are processed within five working days."},
]
@app.get("/search")
async def search(q: str, request: Request) -> dict:
n = next(calls)
log.info(
"search",
extra={"fields": {"traceparent": request.headers.get("traceparent")}},
)
await asyncio.sleep(0.02)
if SLOW_EVERY and n % SLOW_EVERY == 0:
log.warning(
"index segment not cached, reading from disk",
extra={"fields": {"segment": n % 7}},
)
await asyncio.sleep(SLOW_MS / 1000)
return {"hits": DOCS}
@app.post("/v1/messages")
async def messages(request: Request) -> JSONResponse:
body = await request.json()
prompt = body["messages"][-1]["content"]
if "OVERLOAD" in prompt: # lets the lab trigger a provider error on purpose
log.warning("returning 529 overloaded_error")
error = {"type": "overloaded_error", "message": "Overloaded"}
return JSONResponse({"type": "error", "error": error}, status_code=529)
await asyncio.sleep(0.12)
reply = "Restart the workers, then clear it."
return JSONResponse(
{
"id": f"msg_{uuid.uuid4().hex[:24]}",
"type": "message",
"role": "assistant",
"model": body["model"],
"content": [{"type": "text", "text": reply}],
"stop_reason": "end_turn",
"usage": {"input_tokens": len(prompt) // 4, "output_tokens": 14},
}
)Start both stubs in the background, each writing its JSON logs to a .jsonl file and its span lines and server messages to a .err file. After each &, the shell puts the process ID (PID) of that background process in $!; saving it in a variable lets you stop exactly these processes at the end, so keep using the same terminal. Then call the search stub directly and read its last log record.
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=$!
sleep 3
curl -s 'http://127.0.0.1:8001/search?q=queue' | python -m json.tool
tail -n 1 logs/search-stub.jsonl | python -m json.tool{
"hits": [
{
"id": "runbook-12",
"text": "Restart the worker pool before clearing the queue."
},
{
"id": "faq-3",
"text": "Refunds are processed within five working days."
}
]
}{
"ts": "2026-11-17T02:01:06.482+00:00",
"level": "INFO",
"service": "search-stub",
"msg": "search",
"trace_id": "b715185d29a95286bf38b476b62de776",
"span_id": "4445a37fc4a3a678",
"traceparent": null
}curl sent no traceparent, so the stub's FastAPI instrumentation started a new trace and the log record still has a trace ID. That is how every trace begins: at the first instrumented service that does not receive a context.
04. Step 3: The service, with automatic and manual spans
ask-api uses two instrumentation libraries. FastAPIInstrumentor wraps the app so each request gets a SERVER span named after its route template, and records the duration histogram; exclude_spans drops the tiny internal spans it would otherwise create for each ASGI send and receive. HTTPXClientInstrumentor patches httpx, so every outbound call gets a CLIENT span and a traceparent header. Call .instrument() before you create the client, as the comment says. The client also closes idle pooled connections after 2 s: uvicorn closes idle connections after 5 s, which is also the httpx default, so with equal timeouts a request can reuse a connection at the moment the server closes it and fail with RemoteProtocolError (or, less often, ReadError).
The model call gets one more span, written by hand, because the HTTP span only knows that a POST happened. Following the OpenTelemetry GenAI conventions, it is a CLIENT span named chat {model} with gen_ai.operation.name, gen_ai.provider.name (set at span creation), the requested and returned model, the finish reason, the response ID and the token counts. It does not carry the prompt or the answer: the conventions make message content opt-in, because prompts can hold personal data and secrets. Keep it off unless you have redaction and a retention policy in place. Community instrumentations for model SDKs record the same attributes; writing the span yourself shows you what they contain.
"""ask-api: answers a question from retrieved passages and one model call."""
import os
import httpx
from fastapi import FastAPI, HTTPException
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.trace import SpanKind, Status, StatusCode
from pydantic import BaseModel
from telemetry import setup_telemetry
log = setup_telemetry("ask-api", metrics_port=9464)
HTTPXClientInstrumentor().instrument() # before any client is created
tracer = trace.get_tracer("ask-api")
SEARCH_URL = os.environ.get("SEARCH_URL", "http://127.0.0.1:8001")
MODEL_URL = os.environ.get("MODEL_BASE_URL", "http://127.0.0.1:8002")
MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
HEADERS = {
"x-api-key": os.environ.get("ANTHROPIC_API_KEY", "stub-key"),
"anthropic-version": "2023-06-01",
}
# Close idle pooled connections after 2 s, before uvicorn drops them at 5 s.
client = httpx.AsyncClient(timeout=10.0, limits=httpx.Limits(keepalive_expiry=2.0))
app = FastAPI()
FastAPIInstrumentor.instrument_app(app, exclude_spans=["receive", "send"])
class Question(BaseModel):
question: str
@app.post("/ask")
async def ask(q: Question) -> dict:
found = await client.get(f"{SEARCH_URL}/search", params={"q": q.question})
hits = found.json()["hits"]
context = "\n".join(h["text"] for h in hits)
answer = await call_model(f"{context}\n\nQuestion: {q.question}")
log.info("answered", extra={"fields": {"hits": len(hits)}})
return {"answer": answer, "sources": [h["id"] for h in hits]}
async def call_model(prompt: str) -> str:
attributes = {
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "anthropic",
"gen_ai.request.model": MODEL,
"gen_ai.request.max_tokens": 300,
}
# GenAI conventions: a CLIENT span named "{operation} {model}".
with tracer.start_as_current_span(
f"chat {MODEL}", kind=SpanKind.CLIENT, attributes=attributes
) as span:
payload = {
"model": MODEL,
"max_tokens": 300,
"messages": [{"role": "user", "content": prompt}],
}
resp = await client.post(
f"{MODEL_URL}/v1/messages", json=payload, headers=HEADERS
)
if resp.status_code >= 400:
status = resp.status_code
error_type = resp.json().get("error", {}).get("type", str(status))
span.set_attribute("error.type", error_type)
span.set_status(Status(StatusCode.ERROR, f"model returned {status}"))
log.error(
"model API error",
extra={"fields": {"status": status, "error_type": error_type}},
)
raise HTTPException(status_code=502, detail="model provider unavailable")
body = resp.json()
span.set_attributes(
{
"gen_ai.response.id": body["id"],
"gen_ai.response.model": body["model"],
"gen_ai.response.finish_reasons": [body["stop_reason"]],
"gen_ai.usage.input_tokens": body["usage"]["input_tokens"],
"gen_ai.usage.output_tokens": body["usage"]["output_tokens"],
}
)
# Content capture stays off: no prompt or answer text on the span.
# Join the text blocks: the first content block is not always text.
return "".join(b["text"] for b in body["content"] if b["type"] == "text")uvicorn app:app --port 8000 --no-access-log > logs/ask-api.jsonl 2> logs/ask-api.err &
API_PID=$!
sleep 3
tail -n 1 logs/ask-api.errINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)The model name comes from ANTHROPIC_MODEL (here the default claude-sonnet-5), and the base URL from MODEL_BASE_URL. The request is a valid Messages API call, so to try a real model later, set MODEL_BASE_URL=https://api.anthropic.com, put your key in ANTHROPIC_API_KEY and restart ask-api. The key is read from the environment and never logged or put on a span.
05. Step 4: Follow one request across three processes
Send one question, then print the span lines of ask-api and the last span line of each stub. Each line shows the service and span name, the kind, the duration, and the first eight hex digits of the trace ID, span ID and parent span ID.
curl -s http://127.0.0.1:8000/ask -H 'content-type: application/json' \
-d '{"question": "How do I drain the queue?"}'; echo
sleep 1
grep '^\[' logs/ask-api.err
tail -qn 1 logs/search-stub.err logs/model-stub.err{"answer":"Restart the workers, then clear it.","sources":["runbook-12","faq-3"]}[ask-api] GET CLIENT 37.4 ms f592921d e90a2083 d63b90d8
[ask-api] POST CLIENT 126.7 ms f592921d f570bb66 028db391
[ask-api] chat claude-sonnet-5 CLIENT 128.5 ms f592921d 028db391 d63b90d8
[ask-api] POST /ask SERVER 170.8 ms f592921d d63b90d8 -
[search-stub] GET /search SERVER 21.0 ms f592921d 48ed632a e90a2083
[model-stub] POST /v1/messages SERVER 123.0 ms f592921d 4e96211c f570bb66All six spans share trace f592921d, and the parent column rebuilds the tree. POST /ask has no parent, so it is the root. The GET client span (e90a2083) is the parent of the search stub's server span, and the POST client span (f570bb66) of the model stub's. The chat span sits between the root and that POST, because the call happened while it was active. Spans print as they end, so children come first.
Compare durations too: the client GET took 37 ms, the search handler 21 ms. The gap is time outside the handler, such as opening the first connection; connection-pool and DNS problems show up in gaps like this.
Now use the trace ID as you would during an incident: pull every log line of this request from all services, then look at the header the search stub received.
python find_logs.py f592921d # use the trace ID prefix from your own output
grep f592921d logs/search-stub.jsonl | python -m json.tool | grep traceparent02:01:07.836 search-stub INFO search
02:01:07.987 ask-api INFO answered hits=2
"traceparent": "00-f592921d0950115f23a256f10804c36e-e90a2083c74be56a-03"traceparent has four dash-separated fields: the version (00), the 32-hex trace ID, the 16-hex ID of the caller's span (the GET client span, e90a2083), and flags. Bit 01 means sampled; bit 02, set by recent SDKs, says the trace ID is random, so 03 means both.
"""Print the log lines of one trace, from every service, in time order."""
import json
import pathlib
import sys
prefix = sys.argv[1] # a whole trace ID, or its first few characters
rows = []
for path in pathlib.Path("logs").glob("*.jsonl"):
for line in path.read_text().splitlines():
entry = json.loads(line)
if (entry.get("trace_id") or "").startswith(prefix):
rows.append(entry)
SHOWN = {"ts", "level", "service", "msg", "trace_id", "span_id", "traceparent"}
for e in sorted(rows, key=lambda e: e["ts"]):
extra = " ".join(f"{k}={v}" for k, v in e.items() if k not in SHOWN)
when = e["ts"][11:23] # time of day, to the millisecond
print(f"{when} {e['service']:<11} {e['level']:<7} {e['msg']} {extra}".rstrip())06. Step 5: Read the request metrics
The meter provider serves Prometheus's text format on port 9464. The raw page is long, with OpenTelemetry scope labels on every line, so show_metrics.py parses it with prometheus_client and prints the request histogram compactly, keeping three of the fifteen buckets. Send five more requests first.
"""Print the request-duration histogram from a /metrics page, compactly."""
import sys
import httpx
from prometheus_client.parser import text_string_to_metric_families
URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:9464/metrics"
WANTED = "http_server_request_duration_seconds"
for family in text_string_to_metric_families(httpx.get(URL).text):
if family.name != WANTED:
continue
print(f"{family.name} ({family.type}, {len(family.samples)} samples)")
for s in family.samples:
lab = s.labels
if s.name.endswith("_bucket") and lab["le"] not in {"0.1", "0.25", "+Inf"}:
continue # keep three buckets so the output stays short
suffix = s.name.removeprefix(WANTED)
le = f" le={lab['le']}" if "le" in lab else ""
key = f"{suffix:<8} {lab['http_route']} {lab['http_response_status_code']}{le}"
print(f" {key:<30} {s.value:.4g}")for i in 1 2 3 4 5; do
curl -s -o /dev/null http://127.0.0.1:8000/ask \
-H 'content-type: application/json' -d '{"question": "Who is on call?"}'
done
python show_metrics.pyhttp_server_request_duration_seconds (histogram, 17 samples)
_bucket /ask 200 le=0.1 0
_bucket /ask 200 le=0.25 6
_bucket /ask 200 le=+Inf 6
_count /ask 200 6
_sum /ask 200 0.9233One OpenTelemetry histogram became three Prometheus series families: _bucket with an le (less than or equal) label, _count and _sum, with _seconds added from the unit. In this run all six requests took between 0.1 and 0.25 s; buckets are cumulative, so +Inf always equals the count, and _sum / _count gives the mean, about 0.15 s. No question text, user or trace ID is a label: those stay on spans and logs.
07. Step 6: Make the model call fail
Send a question containing OVERLOAD. The model stub answers 529, ask-api marks its spans as errors, logs the failure and answers its own client with 502. Print the last four span lines of ask-api.
curl -s -w ' %{http_code}\n' http://127.0.0.1:8000/ask \
-H 'content-type: application/json' -d '{"question": "Please OVERLOAD the model"}'
sleep 1
tail -n 4 logs/ask-api.err{"detail":"model provider unavailable"} 502[ask-api] GET CLIENT 24.8 ms 3cd26b34 f31fce93 93f577b3
[ask-api] POST CLIENT 7.0 ms 3cd26b34 7b5db32c 76a2bdfb ERROR
[ask-api] chat claude-sonnet-5 CLIENT 10.2 ms 3cd26b34 76a2bdfb 93f577b3 ERROR
[ask-api] POST /ask SERVER 37.4 ms 3cd26b34 93f577b3 - ERRORpython find_logs.py 3cd26b34
python show_metrics.py | tail -n 502:01:11.331 search-stub INFO search
02:01:11.361 model-stub WARNING returning 529 overloaded_error
02:01:11.363 ask-api ERROR model API error status=529 error_type=overloaded_error
_bucket /ask 502 le=0.1 1
_bucket /ask 502 le=0.25 1
_bucket /ask 502 le=+Inf 1
_count /ask 502 1
_sum /ask 502 0.03774Each signal records the failure in its own way. The httpx span is an error because the upstream answered 5xx; the chat span carries error.type=overloaded_error, the provider's own error code, as the GenAI conventions ask; the server span is an error because ask-api returned 502. Three log lines from three processes share one trace ID, and the histogram gained the 502 series that lesson 3's error ratio divides by the total.
Stop the three processes when you are done, in the terminal that started them: kill $SEARCH_PID $MODEL_PID $API_PID. This stops only the processes you started; a pattern such as pkill -f uvicorn would also stop any other uvicorn server you happen to run. If you closed that terminal, lsof -t -iTCP:8000-8002 -sTCP:LISTEN prints the PIDs of your processes that listen on the lab ports; pass them to kill. Keep the folder: lessons 3 and 5 build on it.
08. Troubleshooting
09. Check your understanding
10. Apply it
Stretch task: add a third outbound call to ask-api, a moderation check before the model call, served by a third stub instance on port 8003. Then:
- confirm that its client span and its server span join the same trace;
- add a counter
ask.moderation.rejectionswith a singlereasonlabel limited to three values, and find it on the/metricspage; - add a span event (
span.add_event(...)) when the model's finish reason ismax_tokens, and decide whether that should also be a log line.
For your own project service, instrument every outbound call the same way and note which attributes you left off spans, and why.
11. Review prompt
Without looking back, list what setup_telemetry() must do before an instrumentation library is enabled, and why the order matters. Sketch the span tree of one /ask request with parent links, and mark which spans come from instrumentation libraries and which you wrote by hand. Then write out a traceparent header and name its four fields.
References
- OpenTelemetry documentation
- OpenTelemetry: Python
- OpenTelemetry: Python instrumentation
- OpenTelemetry FastAPI instrumentation
- OpenTelemetry HTTPX instrumentation
- OpenTelemetry: HTTP metrics conventions
- OpenTelemetry GenAI conventions: client inference spans
- OpenTelemetry GenAI conventions: Anthropic
- OpenTelemetry: Context propagation
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.