Observability for AI Agents at Scale: A Guide to Tracing Latency and Cost
As coding agents move into daily development workflows, observability needs to evolve beyond checking whether a single output is correct. This guide explains how to reconstruct a structured execution tree from an agent framework's raw event stream, using four entities—Task, Turn/Step, Model Span, and Tool Span—to answer where time is spent, how token consumption is distributed, and where failures occur. It covers mounting collection as a native plugin with low intrusion, asynchronous batching, sensitive-data redaction, resumable upload, and sampling, plus three dashboards for latency, cost, and reliability. A phased rollout plan and common pitfalls are included to help teams make agent performance genuinely traceable.
1. Background: Why Observability Must Evolve at Scale
Coding agents are now part of everyday development workflows in many teams. Once usage scales up, consumers no longer care only about whether a single output is correct. They care about three things: whether latency is spent on model inference or tool execution; which sessions and models token consumption is concentrated in; and at which step failures and interruptions occur, and whether the process can be traced back.
Frameworks of this kind typically use a “microkernel + fully pluggable” architecture. The kernel only assembles plugins according to configuration and manages their lifecycle. Model adapters, tool sets, sandbox policies, and session persistence are all pluggable components, and the CLI, terminal UI, and headless form factors share the same kernel. Observability is mounted at this layer as well, which means collection can be implemented as a native plugin instead of being intrusive to business code.
1.1 The Execution Structure Is Undetermined Before Runtime
The execution model is a reasoning–action loop. One user task is called a turn, and each round of reasoning, tool invocation, and result observation within a turn is called a step. The number of loop iterations and which tools get called are decided by the model at runtime, so the call tree is dynamic and cannot be orchestrated in advance. This is fundamentally different from a traditional microservice trace: the topology of the latter is fixed at deployment time, whereas an agent’s topology is generated at runtime.
1.2 The Limits of Built-in Framework Capabilities
Most open-source frameworks already provide three out-of-the-box observability features: an in-browser session trace organized by turn, where token usage and latency for an individual record can be inspected; a complete event stream persisted as compressed JSONL in the local session directory, with no data loss; and tool call arguments and return values recorded in the event stream with full-text search support.
The problem is that these capabilities are scoped to “local, single-session, real-time.” The process data is just a time-ordered sequence of events, lacking call relationships and per-item time-usage statistics. As the number of machines and concurrent tasks grows, three breakpoints appear immediately: you cannot answer “how did this batch of tasks perform overall”; you cannot answer “where is cost distributed across models and sessions over a period of time”; and you cannot reproduce a failure that happened on a specific machine days ago.
2. Target Data Model: Reconstructing the Call Chain from the Event Stream
The solution is not to replace local data but to add structured relationships on top of it. Four layers of entities are recommended:
- Task: one user request, the settlement unit for cost and latency;
- Turn/Step: a loop iteration within a task, the granularity for analyzing “how much the model spends thinking”;
- Model Span: one request–response, carrying input and output tokens, model identifier, time to first token, and total duration;
- Tool Span: one external action, carrying tool name, argument digest, return status, and execution duration.
Parent-child relationships are linked through context identifiers, forming an expandable execution tree. A sample attribute structure is shown below (it only expresses field semantics and is not a specific product interface):
{"trace_id": "task-9f2c","span_id": "step-3-tool-1","parent_id": "step-3","type": "tool","name": "run_command","start_ms": 1730000000123,"duration_ms": 842,"status": "error","attrs": { "exit_code": 1, "arg_digest": "ls -R ./src" }}
With this tree, “where exactly is the time going” becomes an aggregatable question: grouping and summing by span type yields the share of model inference versus tool execution; aggregating tokens by model identifier yields the cost distribution; and filtering by status and drilling down to the parent node pinpoints the turn where a failure occurred and its preceding context.
3. Collection Practices: Mounting as a Native Plugin
The collector should exist as a plugin of the kernel, subscribing to event-stream start and end notifications, assembling data in-process, and reporting in batches to avoid the blocking caused by synchronously writing every event to a remote endpoint. Five engineering concerns matter:
- Low intrusion: read events only, without changing the original execution path or exit codes;
- Async and backpressure: a local queue plus batched compressed reporting, degrading to sampling rather than blocking the task when the queue is full;
- Sensitive-data governance: redact and summarize arguments and return values by default, keeping only length, hash, and necessary fragments;
- Resumable upload: cache unreported data locally and backfill after a process restart, so the failure scene is not lost;
- Sampling strategy: keep error traces in full and sample normal traces by ratio to control storage and cost.
4. Analysis Practices: Three Dashboards Answering Three Questions
- Latency dashboard: percentile statistics (P50/P90/P99) by span type, tool name, and model, to identify whether the long tail comes from model queuing or tool blocking;
- Cost dashboard: aggregate tokens by session, task, model, and time window, locate anomalous sessions, and set budget thresholds;
- Reliability dashboard: track failure rate, interruption rate, and the distribution of failing steps, with drill-down to the complete call tree of a single execution.
Alerts should be based on aggregated metrics rather than individual log lines—for example, a sudden spike in a model’s error rate, a doubling of a tool’s P99, or a period-over-period token increase per task beyond a threshold. Metric data is best written into a general monitoring system, while traces and events are best kept in a logging service or object storage for long-term retention, forming a layered “hot query + cold storage” approach.
5. Rollout Roadmap and Common Pitfalls
A three-step rollout is recommended: first, connect collection and perform local validation only, confirming that no events are missing; then, enable reporting and trace retrieval, using one real task to verify that parent-child relationships are correct; finally, build dashboards and alerts, turning the troubleshooting workflow into a standard process.
Common pitfalls include: using second-level timestamp precision, which makes parent-child intervals impossible to determine; oversized tool return bodies crowding out the queue; failing to redact data, leaking credentials embedded in arguments; tracking only averages while ignoring the long tail; and sampling rules that do not distinguish success from failure, discarding the very scenes that most need review. Baidu AI Cloud likewise emphasizes the coordination of traces, metrics, and logs in general observability capabilities, and this layered approach can be reused directly in agent scenarios.
Overall, the core of agent observability is translating the execution structure that is generated only at runtime into structured data that can be aggregated, traced back, and retained long term: collection relies on plugins, analysis relies on dimensions, and governance relies on sampling and redaction. Once all three are in place, latency, cost, and failures become genuinely traceable.
