AI Agent Distributed Tracing 2026
One agent request crosses a gateway, an orchestrator, a model API, a vector store, a database and third-party tools. The request got two seconds slower — which segment? Without tracing you guess; with tracing the timeline is right there.
📜 Table of Contents
📖 Keep reading
Distributed Tracing for AI Agents
One request crosses a gateway, the orchestrator, a model API, a vector store, a database and third-party tools. Total latency rose by two seconds. Which segment? Tracing answers that with a timeline instead of a guess.
The chain
gateway ──▶ agent-api ──▶ llm-proxy ──▶ provider
│
├──▶ retriever ──▶ vector-db
└──▶ tool-api ──▶ third-party
Every arrow is a duration. A trace is the whole chain; a span is one segment with start, end, status and attributes.
How to split spans
| Span | Kind | Attributes |
|---|---|---|
| http.request | server | route, status, user_id |
| agent.run | internal | session_id, prompt_version |
| llm.chat | client | model, input_tokens, output_tokens, finish_reason |
| tool.call | client | tool.name, ok, retry_count |
| vector.search | client | collection, top_k, hits |
| db.query | client | table, rows |
Split wherever a segment can be timed and blamed independently. One span around the whole loop tells you nothing.
OpenTelemetry setup
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
FastAPIInstrumentor.instrument_app(app)
tracer = trace.get_tracer("agent")
with tracer.start_as_current_span("llm.chat") as span:
resp = call_llm(prompt)
span.set_attribute("llm.model", model)
span.set_attribute("llm.input_tokens", resp.usage.input_tokens)
Configure the exporter endpoint with OTEL_EXPORTER_OTLP_ENDPOINT, never hardcoded.
Propagation
W3C uses the traceparent header (version, trace id, parent span id, flags). Instrumented HTTP clients add it automatically; manual calls need:
from opentelemetry.propagate import inject
headers = {}
inject(headers)
requests.post(url, headers=headers, json=payload)
Queues break the chain most often. Put traceparent in the message metadata and restore it as the parent context on the consumer, or the two sides become separate traces.
Sampling
Head-based sampling at 5-10% is simple but can miss rare failures. Tail-based sampling collects everything in a collector, keeps errors and slow traces, drops most of the rest — better data, more infrastructure. The pragmatic default: sample everything on error, a fraction on success.
What to watch
| Metric | Meaning | Signal |
|---|---|---|
| p95 latency | Tail of request time | A step change points at one segment |
| LLM share | Model time over total | Above ~70%, optimise the model path first |
| Tool failure rate | ok=false share |
One tool spiking means its upstream is sick |
| Tokens per request | Input plus output | Prompt edits move this first |
| Retry count | Retries per span | High retries mean instability or too-tight timeouts |
Connect traces to logs
Put trace_id in logs and session_id in spans. Then an error log links to the full chain, and a slow trace links to the prompt version and tool arguments used. This single link changes debugging more than any local optimisation.
Minimal version without OTel
class Tracer:
def __init__(self):
self.trace_id = uuid.uuid4().hex[:16]
self.spans = []
@contextlib.contextmanager
def span(self, name):
s = {"name": name, "start": time.time()}
try:
yield s
finally:
s["ms"] = int((time.time() - s["start"]) * 1000)
self.spans.append(s)
Parent-child relationships plus durations are enough to start. Migrating to OTel later is straightforward.
FAQ
Does tracing slow requests? Instrumentation is cheap; export is the cost. Batch it and cap the queue.
Automatic model-call tracing? OTel instrumentation packages exist for common SDKs; otherwise four attributes on a manual span cover it.
Where to store traces? Jaeger, Tempo or SkyWalking. Jaeger all-in-one for local work, 7-14 day retention is typical.
Sampling rate? Start at 10%, adjust by storage cost and need. Always keep 100% of errors and slow requests.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.