Tracing an AI Agent Like a Distributed System
An agent run is a distributed trace: model calls, retrieval, tools, retries, queue waits, approvals, and token usage all need one correlation model. A practical OpenTelemetry design for debugging latency, failures, and AI spend without logging sensitive prompts by default.
On this page
A normal API request is already hard to debug when it crosses several services. An agent request adds another layer of uncertainty: one user action can trigger retrieval, a reranker, multiple model calls, several tools, retries, a queue hop, and perhaps a human approval before anything reaches the screen.
If those steps live in separate dashboards, the final symptom is easy to see and the cause is not.
A user says the assistant took twelve seconds. The LLM dashboard says generation took three. The search service looks healthy. The CRM tool returned 200. Nothing appears obviously broken.
The missing eight seconds may have been a queue wait, a retry after a rate limit, a slow vector query, or the planner making a second model call because the first tool result failed validation.
I prefer to treat the whole agent run as one distributed trace. Model calls are important spans, but they are not the trace. They sit beside retrieval, tools, application decisions, approvals, and ordinary infrastructure work.
OpenTelemetry is useful here because it gives the AI path the same correlation model as the rest of the service instead of creating a second observability universe just for LLMs.
Start with a durable run ID and a trace ID
A trace describes one execution attempt through a set of services. A long-running agent may survive across multiple workers or resume hours later, so I also keep an application-level run ID.
type AgentRunContext = { runId: string; tenantId: string; workflow: string; workflowVersion: number;};The run ID is intentionally high-cardinality. I use it as a trace/span correlation attribute only where the telemetry backend and retention model can handle that cardinality; I do not use it as a metric label. If the workflow pauses and later resumes under another trace, the run ID still connects the lifecycle.
I do not put user email addresses, raw prompts, document text, or arbitrary tool arguments into span attributes just because tracing makes it convenient. Observability data is still data with retention and access-control consequences.
Model the trace around operations, not framework callbacks
A framework may emit dozens of internal events. That does not mean every callback deserves a span.
I want spans that answer engineering questions:
- how long did retrieval take?
- which model call consumed the tokens?
- which tool retried?
- where did the run wait?
- which step failed?
- what version of the workflow produced this path?
A useful trace might look conceptually like this:
agent.run retrieval.search postgres.full_text vector.search reranker.score model.plan tool.crm.get_customer model.answer output.policy_checkIf the tool call itself makes an HTTP request, normal HTTP instrumentation can appear below that tool span. If retrieval hits PostgreSQL, database instrumentation can appear below the retrieval span.
That hierarchy is valuable because it connects AI-specific decisions to ordinary infrastructure latency.
Create one run span and attach stable dimensions
OpenTelemetry's GenAI semantic conventions are useful as a shared vocabulary, but I still need application-specific attributes for workflow identity and product behavior.
The important rule is to keep dimensions used for aggregation bounded. A span attribute such as workflow=customer-support groups well. prompt=<35KB user conversation> does not.
import { trace, SpanStatusCode } from "@opentelemetry/api";const tracer = trace.getTracer("agent-runtime");async function traceAgentRun<T>( context: AgentRunContext, execute: () => Promise<T>,): Promise<T> { return tracer.startActiveSpan("agent.run", async (span) => { span.setAttributes({ "app.ai.run_id": context.runId, "app.ai.workflow": context.workflow, "app.ai.workflow_version": context.workflowVersion, }); try { const result = await execute(); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.recordException(error as Error); span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : "agent run failed", }); throw error; } finally { span.end(); } });}I generally do not add tenantId as a trace attribute automatically. Whether that is appropriate depends on the telemetry backend, retention policy, access model, and cardinality. In a multi-tenant product, tenant-level cost reporting is useful, but the identifier can often be represented as an internal opaque ID in a separate metering pipeline rather than copied to every exported span.
Trace model calls as operations with usage, not transcripts
For a model span I care about the operational contract:
- provider and model identifier;
- operation type;
- latency;
- input/output token counts;
- cached input tokens where available;
- retry/attempt number;
- response status;
- structured-output validation result.
I do not need the raw prompt to answer most latency and cost questions.
type ModelUsage = { inputTokens: number; outputTokens: number; cachedInputTokens?: number;};async function tracedModelCall<T>(input: { model: string; operation: "plan" | "answer" | "judge" | "rerank"; attempt: number; call: () => Promise<{ value: T; usage: ModelUsage }>;}): Promise<T> { return tracer.startActiveSpan(`model.${input.operation}`, async (span) => { span.setAttributes({ "gen_ai.operation.name": input.operation, "gen_ai.request.model": input.model, "app.ai.attempt": input.attempt, }); try { const result = await input.call(); span.setAttributes({ "app.ai.input_tokens": result.usage.inputTokens, "app.ai.output_tokens": result.usage.outputTokens, "app.ai.cached_input_tokens": result.usage.cachedInputTokens ?? 0, }); return result.value; } finally { span.end(); } });}If the provider SDK already emits compatible OpenTelemetry spans, I would avoid wrapping the same physical request twice unless the outer span represents a distinct application operation. Duplicate spans make latency analysis worse, not better.
Keep pricing out of the request path
Token counts are durable facts about a call. Price is a business rule that changes.
I avoid hard-coding a dollar amount into the runtime span from a table someone copied months ago. Instead I record usage and the model identifier, then calculate cost in a metering/reporting layer with a versioned price catalog.
type UsageRecord = { runId: string; model: string; inputTokens: number; cachedInputTokens: number; outputTokens: number; occurredAt: string;};That lets historical reports say which pricing table they used. It also handles providers whose billing dimensions are not only text tokens.
If I need real-time budget enforcement, the runtime can use a current internal price snapshot, but I still keep the raw usage. Recomputing cost later should be possible.
Tool spans need retry and side-effect semantics
A tool span should tell me more than tool=refund and duration=842ms.
For production debugging I want to know whether this was the first attempt, whether the tool is read-only or side-effectful, and whether the final outcome was known.
type ToolTraceAttributes = { toolName: string; attempt: number; sideEffect: "none" | "idempotent-write" | "non-idempotent-write"; outcome: "success" | "failure" | "unknown";};That becomes especially important after timeouts. A write whose outcome is unknown should look different from a request that definitely failed before the dependency accepted it.
This connects directly to the retry and idempotency boundaries covered earlier in the series. A trace should preserve those semantics instead of flattening every exception into tool_error=true.
Retrieval deserves its own trace tree
A RAG request can spend more time retrieving evidence than generating the answer.
For hybrid retrieval I want separate child spans for lexical search, vector search, fusion, and reranking. Useful attributes include bounded counts rather than entire documents:
retrieval.lexical.candidates = 30retrieval.semantic.candidates = 30retrieval.fused.candidates = 44retrieval.reranked.candidates = 20retrieval.final_context_chunks = 6For quality debugging, stable chunk IDs can be recorded in a restricted evaluation trace or run artifact when appropriate. I would not place a large array of document IDs into every production metric label.
Metrics and traces have different cardinality budgets. That distinction matters.
Metrics answer fleet questions; traces answer run questions
A trace is good for:
Why did run R-183 take 14 seconds?
A metric is good for:
Did p95 model latency increase after version 42?
I derive operational metrics such as:
- run duration;
- model-call duration by operation/model;
- tool failure rate;
- retries per run;
- input/output/cached tokens;
- queue wait time;
- cancellation count;
- approval wait time;
- retrieval candidate counts.
I keep high-cardinality values such as run IDs out of metric labels. Otherwise a monitoring system can become both expensive and slow while trying to observe an expensive and slow agent.
Queue wait time should not disappear
Agent systems often push work through queues, especially for long-running jobs.
A common tracing mistake starts the worker span only after the message is received. The trace then shows a 600 ms task that the user actually waited eight seconds for.
Record enqueue time and link producer/consumer context so the trace can distinguish:
queue wait: 7.4sworker execution: 0.6sThis is ordinary messaging observability, but it becomes more important when an agent fans out many asynchronous steps.
Sampling needs a product-aware strategy
Keeping every full trace forever can be expensive, especially if one run creates dozens of spans.
I usually want higher retention for:
- failed runs;
- unusually slow runs;
- runs with unknown side-effect outcomes;
- security-policy blocks;
- evaluation traffic;
- a small representative sample of normal runs.
Tail-based sampling can help retain traces after their outcome is known. If that infrastructure is not available, application-level trace promotion or a separate run-event store can cover the critical cases.
The important part is that “sample 1% randomly” should not accidentally discard 99% of the failures you need to investigate.
Prompt and completion capture should be opt-in
There are legitimate debugging cases where seeing the model input or output is useful.
That does not make universal prompt logging a good default.
Model context can contain customer data, private documents, source code, secrets accidentally returned by tools, or information with stricter retention requirements than ordinary telemetry.
I prefer metadata by default and controlled content capture for explicitly approved environments or diagnostic sessions. When content capture is enabled, it needs redaction, access controls, retention, and auditability just like any other sensitive data pipeline.
A tracing backend should not become the easiest place in the company to search every prompt a customer ever sent.
Version everything that can change behavior
A useful agent trace usually carries versions for:
workflow.versionprompt.versionretrieval.versiontool_schema.versionpolicy.versionmodelThat turns a vague production report into a comparison.
If failures started when retrieval.version=18 shipped, I can slice traces before and after it. If only prompt.version=42 shows a rise in unnecessary tool calls, the investigation gets much smaller.
This also connects observability to evaluation: the same versions used in CI should appear in production telemetry.
Make the final trace tell a story without hidden reasoning
I do not need private chain-of-thought to debug an agent.
I need observable state transitions:
plan selected tool=search_ordersretrieval returned 4 evidence chunkstool validation failed: missing customer_idplanner repaired argumentssecond tool call succeededoutput policy allowed responseThose are application events and decisions that can be stored explicitly.
The trace should explain what the system *did*, what it observed, how long each operation took, and which boundary failed. That is enough to debug a surprising amount of agent behavior without storing hidden reasoning or giant transcripts.
When full tracing is unnecessary
A one-call text generator can often live with ordinary HTTP metrics plus provider usage logs.
The richer trace becomes valuable once one user request fans out into multiple probabilistic and deterministic operations. At that point, the LLM is only one service in a distributed workflow.
That is the mental model I find most useful: agent observability is distributed tracing with a few new dimensions—model identity, token usage, retrieval quality, tool semantics, and workflow state.
The infrastructure does not need to become exotic just because an LLM is involved. It needs to make the entire execution path visible enough that a slow, expensive, or incorrect run can be explained from evidence rather than reconstructed from five unrelated dashboards.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article