Observability for AI Agents at Scale: Tracing, Cost, and Failure Analysis
As coding agents move from small pilots into daily production workflows, single-session logs are no longer enough to answer questions about latency, token spend, and failures across many runs. This article explains why agent observability must be rebuilt around structured traces, what execution model makes coding agents hard to observe, and how to design a four-layer data model (Session, Turn, Step, and leaf ModelCall or ToolCall nodes) that supports latency attribution, cost drill-down, and failure localization. It covers collecting traces through native framework plugins with asynchronous batching and field-level redaction, querying for latency, cost, and failure patterns, and moving from manual queries to proactive alerting with tiered data retention. A phased rollout path is included to help teams make latency, cost, and reliability measurable and preventable as agent usage scales.
1. Why Scaling Requires a New Observability Perspective
Coding agents are now part of many teams’ daily development workflows. During small-scale trials, users usually care only about whether a single task returns the correct result. But once call volume, concurrent sessions, and runtime duration all increase, the questions become much harder: Did a task spend its time on model inference, or on tool execution and waiting on external systems? Which sessions, models, and turns account for most token consumption? Did failures and interruptions happen during inference, tool calls, or result parsing, and can they be fully reconstructed after the fact?
These questions share one characteristic: none of them are single-session problems. They are statistical and correlation problems that span sessions and time windows. The observability features built into most open-source agent frameworks are scoped to a single machine, a single session, and real time—for example, an in-browser execution trace table, a locally persisted event stream, or full-text search for one session. Such capabilities are very effective for development and debugging, but they fall short when you need to answer “How did this batch of tasks perform overall?”, “Was last week’s cost distribution abnormal?”, or “How exactly did that failure three days ago happen?”
So the first step toward scale is not switching frameworks, but adding a layer of structured trace data: upgrading the execution process from “readable text logs” to “searchable, aggregatable, long-term structured call chains.” The general-purpose capabilities that Baidu AI Cloud provides for agent observability are built around exactly this layer: a plugin integrates with the execution kernel, reconstructs the process as a call chain, and combines chain search, aggregation, and monitoring alerts into a closed loop.
2. How the Coding Agent Execution Model Shapes Observability Challenges
Designing an observability solution requires understanding the execution model of the observed system. Current mainstream coding agent frameworks share three common characteristics.
First, a microkernel with full plugin architecture. The kernel only assembles plugins according to a configuration (profile) and manages their lifecycle. Model adapters, tool sets, sandbox policies, session persistence, and everything else are pluggable plugins. Multiple forms—command line, terminal UI, and headless batch processing—share the same kernel. This means observability should naturally attach at the kernel layer rather than being scattered across individual tool implementations.
Second, ReAct-style loop execution. One user task is called a turn, and each round of “reason—call tool—observe result” within a turn is called a step. The number of loop rounds, which tools are called, and whether to retry are all decided by the model at runtime.
Third, the execution structure cannot be determined before runtime. The same request can produce completely different call tree depths and tool combinations across two runs.
These three points directly lead to hard requirements for the observability solution: the data model must express both the “task—turn—step” hierarchy and the “model call—tool call” node types, and it must support parent-child relationships and latency attribution. Otherwise, it cannot answer “where did the time go?”
3. Target Data Model: Four Layers and Two Node Types
It is recommended to abstract the trace into a four-layer structure, from top to bottom: Session, Turn, Step (reasoning round), and leaf calls (model calls or tool calls).
Session└── Turn (a user task)└── Step (reasoning round N)├── ModelCall (model request: input/output tokens, first-token latency, total latency, status)└── ToolCall (tool call: tool name, argument digest, result digest, latency, status)
This model has three key design points. First, latency attribution is computable: Step latency minus the sum of all its leaf call latencies equals orchestration and scheduling overhead; model call and tool call latencies can be aggregated directly, which answers the “inference vs. execution” ratio question. Second, cost can be drilled down: token usage is attached to model call nodes and can be aggregated along four dimensions—Session, model, tool, and time. Third, failures can be localized: status fields and error codes are attached to leaf nodes, and combined with the parent-child chain, you can determine at which layer an interruption occurred.
4. Collection Side: Mounting as a Native Plugin
Collection should not depend on modifying business code, but should be implemented through the framework’s own plugin mechanism. Key practices are as follows.
- Attach at kernel lifecycle hooks rather than inside individual tools, to avoid missing or duplicate collection.
- Use asynchronous batch reporting with a bounded in-process queue buffer. When the queue is full, drop low-value details and increment a counter to prevent the observability path from dragging down the main flow.
- Apply field-level redaction and length truncation to sensitive information. Keep only digests and hashes for tool arguments and results, which meets troubleshooting needs while controlling storage costs.
- Inject a unified trace identifier into every chain, so that headless batch tasks can also be correlated with the session that triggered them and with code repository changes.
A sample plugin skeleton is shown below (pseudocode, expressing only the mounting and reporting timing):
class TracingPlugin:def on_turn_start(self, ctx, turn):ctx.span = tracer.start_span("turn", turn.id, attrs=turn.meta())def on_step_start(self, ctx, step):ctx.step_span = ctx.span.child("step", step.index)def on_model_call(self, ctx, call):ctx.step_span.child("model", attrs={"model": call.model, "in_tokens": call.in_tokens,"out_tokens": call.out_tokens, "latency_ms": call.latency,}).end()def on_tool_call(self, ctx, call):ctx.step_span.child("tool", attrs={"name": call.name, "args_digest": digest(call.args),"result_digest": digest(call.result), "status": call.status,"latency_ms": call.latency,}).end()def on_turn_end(self, ctx, turn):ctx.span.end()
5. Query Side: Analysis Paths for Three High-Frequency Questions
Once structured data is in place, query capabilities should be organized around three high-frequency questions.
Latency troubleshooting. First aggregate total latency and step count distribution by Turn, then drill into each Step to compare the latency share of model calls versus tool calls. If tool calls dominate, it is usually because external dependencies are slow or timeout and retry limits are missing. If model calls dominate and output tokens are high, start with redundant prompts and context bloat.
Cost troubleshooting. Use the model call node as the smallest granularity, aggregate tokens and call counts across three dimensions—Session, model, and time window—and identify long-tail sessions. A practical approach is to track both “average turns per task” and the “turn–token correlation coefficient.” Turn inflation is often the root cause of cost overruns, not unit price.
Failure troubleshooting. Index by status and error code, count which node types failures concentrate in, and reconstruct the scene along the parent-child chain: full tool arguments, result digests, and a snapshot of the context for that round. Because the event stream itself is retained losslessly, reproducing a failure from days ago only requires locating it by trace identifier.
6. From Passive Queries to Proactive Alerts
At scale, manual queries are not enough to cover risks. Key metrics need to be connected to a monitoring and alerting system: outlier detection for per-task latency and turn counts, day-over-day spikes in token consumption, thresholds for tool call failure and timeout rates, and non-zero queue drop counts. Alerts should carry the trace identifier and link directly to the corresponding chain, so on-call engineers do not have to jump between multiple systems. It is also recommended to set a tiered retention policy for trace data: short-term hot storage for details and long-term cold storage for aggregated metrics, balancing traceability against storage cost.
7. Recommended Rollout Path
In the first phase, focus only on “queryable”: integrate the plugin and ensure complete data for the four types—tasks, turns, model calls, and tool calls. In the second phase, make it “aggregatable”: build dashboards for latency and cost and establish a baseline. In the third phase, make it “alertable”: connect outliers and spikes to alerts, and feed the conclusions back into tuning prompts, tool timeouts, and concurrency policies. By proceeding in this order, teams can make latency, cost, and failures truly measurable, attributable, and preventable engineering problems as agents scale.
