AI Agent Observability at Scale: Tracing Latency, Token Costs, and Failures
Scaling an AI agent means answering questions that a local session view cannot: where latency accumulates, which workloads drive token costs, and what happened before a task failed. This article explains how to model agent execution as structured traces, analyze self time and critical paths, track token usage consistently, and collect enough detail to diagnose failures without blocking the main workflow.
1. What Changes When AI Agents Scale?
Early in an AI agent project, the main question is whether the current run produced the right result. As request volume, concurrent sessions, and the number of users grow, three operational questions take over:
- Where does the time go? Is the bottleneck model inference, tool execution, sandbox startup, or time spent in a queue?
- What drives token consumption? Which sessions, models, or task types consistently drive up costs? Are some runs using more tokens than expected or repeating work?
- Where do runs fail or stop? Was the cause an invalid model response, a tool timeout, a context limit, or rate limiting by an external dependency? Can you reconstruct what happened afterward?
All three questions require structured trace data that spans sessions and machines and can be retained over time. The trace views built into many open-source agent frameworks are local, live, and limited to one session. That works for development, but it cannot answer questions like “How did the system perform over the past seven days?” This article covers how to fill that gap.
2. Why You Cannot Predict an Agent’s Execution Path
A typical open-source agent framework lets a large language model complete a task in a controlled environment. The agent can read and write files, run commands, and call external services, using each result to decide what to do next.
Architecture: a microkernel with plugins. A small kernel loads plugins according to a profile and manages their lifecycle. Model adapters, toolsets, sandbox policies, and session persistence are all pluggable. Command-line, interactive terminal, and headless batch modes share the same kernel. Observability belongs at this layer rather than scattered across individual plugins.
Execution model: a reasoning–action loop. A user task is a turn. Each cycle of reasoning, tool use, and observation within that turn is a step. The model decides at runtime how many steps to take and which tools to call, so the execution tree is not known in advance.
That has three implications for observability:
- A fixed list of instrumentation points is not enough. The collector must build call trees dynamically and support arbitrary nesting.
- A single latency threshold cannot distinguish slow runs from normal ones across different tasks. Compare latency percentiles against baselines for similar workloads.
- A final status is not enough to explain a failure. Preserve the ordered event stream that led to it.
3. Trace Data Model: Four Entities and One Chain of IDs
Start by modeling execution as records that can be joined and aggregated:
| Entity | What it represents | Key fields |
|---|---|---|
| Task trace | One end-to-end request within a session | trace_id, session_id, tenant or user, start and end times, status |
| Step | One cycle within a turn | step_id, parent_id, sequence number, decision summary, token delta |
| Model call span | One inference request | Model ID, input and output tokens, cache hits, time to first token, total latency, error code |
| Tool call span | One external action | Tool name, argument summary, execution time, exit code, retry count |
Use trace_id → turn_id → step_id → span_id to correlate records, and parent_span_id to represent nesting. These relationships let you roll up latency and token usage or drill down to individual calls.
An illustrative event record:
{"trace_id": "t-8f21c","session_id": "s-1042","turn_id": 3,"step_id": 7,"span_id": "m-77","parent_span_id": "s-7","kind": "model_call","start_ts": 1730000000123,"duration_ms": 4820,"status": "ok","attrs": {"model": "chat-model-a","input_tokens": 12043,"output_tokens": 386,"cached_tokens": 8000,"first_token_ms": 910}}
4. Latency Attribution: Calculate Self Time, Then Find the Critical Path
A parent span’s elapsed time already includes the time spent in its children. Summing raw span durations therefore double-counts nested work. Start with self time: the portion of a span’s duration not covered by its child spans.
def self_time(span, children):child = sum(c.duration_ms for c in children)return max(span.duration_ms - child, 0)# Bucket step-level self time into model, tool, and framework time.buckets = {"model": 0, "tool": 0, "framework": 0}for step in trace.steps:for span in step.spans:buckets[span.kind] += self_time(span, span.children)
This simplified example assumes that child spans do not overlap and that span kinds have been normalized to the three bucket names. When children run concurrently, subtract the time covered by their combined intervals rather than summing their durations.
Next, find the critical path: the longest chain of dependent operations that determines when the request can finish. Self time tells you where work happens; the critical path tells you which work delays completion.
- Model inference dominates: Review prompt length, trim context, reconsider model selection, or evaluate concurrent streaming where applicable.
- Tool execution dominates: Check external dependencies and timeout settings, and look for calls that can run in parallel.
- Framework or sandbox overhead dominates: Inspect environment warm-up, image and dependency setup, and cold-start behavior.
Also track time to first token, which reflects delays such as queueing and prompt prefill, and tool concurrency, which shows whether tool calls actually overlap.
5. Token Cost Attribution: Use Consistent Metrics and Drill Down
Token analysis often breaks down because different parts of the system count usage differently. Standardize three dimensions before building reports:
- Usage: Track input, output, cached, and reasoning tokens separately rather than collapsing them into one total.
- Grouping: Break down usage by session, user or tenant, model, task type, and tool.
- Time: Pre-aggregate by hour or day while retaining detailed records for drill-down.
-- Break down token usage by model and task type to spot unusual growth.SELECT model, task_type,SUM(input_tokens) AS in_tok,SUM(output_tokens) AS out_tok,SUM(cached_tokens) AS cache_tok,COUNT(DISTINCT trace_id) AS tracesFROM span_modelWHERE ts BETWEEN :from AND :toGROUP BY model, task_typeORDER BY out_tok DESC;
Track token usage per successful task and average tokens per step alongside overall usage. A sudden increase can point to a loop running too many steps or context that is not being trimmed. Unlike a change in the bill, an increase in tokens per task cannot be explained by pricing alone. Budget alerts can surface these problems before the bill arrives.
6. Failure Investigation: Classify First, Then Reconstruct the Run
Avoid labeling every unsuccessful run simply as error. Classify failures and interruptions by where they occur:
- Model: Invalid output format, a response blocked by a safety policy, or a context limit exceeded.
- Tool: Timeout, nonzero exit code, argument validation failure, or dependency rate limiting.
- Environment: Sandbox startup failure, insufficient resources, or an image pull failure.
- Workflow: Manual interruption, session timeout, or upstream cancellation.
For each event, record a structured error code, a sanitized summary of the original error, and the step number at which it occurred. Retain the full sequence of structured events, including sanitized tool results. An ordered record lets you replay the relevant sequence in a test environment and makes intermittent failures easier to reproduce. Retain failed traces at a higher rate than routine successes: rare failures are often the samples you most need to investigate.
7. Trace Collection: Non-Intrusive, Asynchronous, and Resilient
A collector plugin should follow four principles:
- Non-intrusive: Hook into the kernel lifecycle without requiring changes to application plugins.
- Asynchronous and batched: Use an in-memory queue and batch exports. Limit retries and keep export work off the main execution path.
- Able to degrade gracefully: If collection fails, disable it and emit a diagnostic signal without affecting task execution.
- Sanitized before storage: Do not persist secrets, access tokens, complete code, or file contents. Keep only summaries and lengths for tool arguments.
class TraceCollector:def on_span_end(self, span):if not self.enabled:returnself.queue.put(self.sanitize(span)) # Sanitize before enqueueing.if len(self.queue) > self.batch:self.flush()
The example shows where collection hooks into span completion. In an asynchronous implementation, enqueueing must not wait, and flush() must schedule a background export rather than perform it inline.
8. Common Pitfalls
| Pitfall | What to do |
|---|---|
| Clock skew across machines produces inconsistent span timings. | Synchronize clocks across hosts and use a monotonic clock to measure elapsed time. |
| A process exits before queued events are exported. | Use graceful shutdown and a disk-backed buffer. |
| Context truncation leaves spans open. | Use a timeout to close spans that never receive an end event. |
| Concurrent tool calls are attached to the wrong parent. | Pass span_id explicitly through the execution context. |
| Token metrics do not match billing records. | Agree on counting conventions before reporting usage. |
| Sampling drops the failures you need to investigate. | Retain all failed and slow traces. |
| Aggregate metrics leave nothing to drill into. | Set separate retention policies for detailed records and aggregates. |
| Sensitive information is persisted. | Apply consistent sanitization before export. |
| Unbounded loops drive up cost. | Enforce both a step limit and a budget limit. |
| Averages hide slow runs. | Track P95 and P99 latency against baselines for comparable tasks. |
| Repeated alerts bury useful signals. | Group related alerts by trace. |
| Missing task labels prevent meaningful comparisons. | Apply task-type labels consistently at the request entry point. |
9. A Three-Stage Rollout
- Make runs traceable. Capture the four core entities and their correlation IDs across the full execution path.
- Make metrics explainable. Add pre-aggregations and let users drill down by model, task type, session, or other relevant dimensions.
- Detect regressions early. Build dashboards and alerts for latency, cost, and failure rate.
At scale, the bottleneck is often not what the model can do, but what the team can see about how it runs. Structured traces turn latency, token costs, and failures from matters of guesswork into problems you can measure, attribute, and investigate through replay.
