Observability for AI Agents at Scale: From Event Streams to Distributed Traces
This article explains how to build observability for coding agents once deployments scale beyond a single machine and a handful of concurrent tasks. It covers the limits of built-in session views and local JSONL event logs, a four-layer trace model (turn, step, model call, tool call) that restores call structure from flat event streams, zero-intrusion collection through native framework plugins, three-tier storage and query templates, methods for attributing latency and token cost, alerting and dashboard design, and a four-step rollout with common pitfalls.
1. What Changes at Scale
Coding agents are now part of everyday development workflows for many teams. Once usage scales up, the people relying on them stop caring only about whether a single result is correct. Three more questions come up:
- Where is the time actually going — model inference or tool execution?
- Which sessions and which models concentrate token consumption?
- At which step do failures and interruptions happen, and can the process be replayed?
None of these are questions about result correctness. They are questions about process explainability. For a single run, a person can watch the terminal output. When concurrent tasks grow from single digits to hundreds or thousands, and execution machines grow from one to a group, watching by eye no longer holds up. Structured data becomes mandatory.
2. The Limits of Built-in Observability in Open-Source Coding Frameworks
Take a common open-source coding agent framework (CLI form, able to read and write files autonomously in a controlled environment, execute commands, and call external services). Its organization is typically “microkernel plus full plugin architecture”: the kernel only assembles plugins by profile and manages their lifecycle, while model adapters, tool sets, sandbox policies, and session persistence are all pluggable. The CLI, terminal-interactive, and headless forms share the same kernel. Observability is mounted at this layer too, which is the key premise.
Its execution model is a ReAct loop: one user task is a turn, and each round of “reason — call tool — observe result” inside a turn is a step. The number of rounds and which tools get called are decided by the model at runtime, so the execution structure cannot be known before the run — this is exactly why every metric definition must collect first and model afterward.
Based on the event stream and on-disk data, such frameworks usually ship three out-of-the-box capabilities:
- Session trajectory view: a browser-based table of execution records organized by round, showing token usage and duration for individual records;
- Session event stream persistence: the complete event stream saved locally in the session directory as compressed JSONL, with no data loss;
- Tool call search: tool call arguments and return results recorded in the event stream, with full-text search across sessions.
The problem is that this data is a time-ordered sequence of session events stored on the local machine. It answers “what happened in this one run,” but not “how did this batch of tasks perform overall.” Three specific gaps:
- No statistics on call relationships or the time each one consumes, so latency cannot be attributed;
- Scope is local, single-session, and real-time; cross-machine aggregation and historical replay require manually moving files around;
- The event stream is a “flat time series” without trace/span semantics, making aggregation, analysis, and alerting difficult.
3. Target Data Model: Reconstructing Call Chains from Event Streams
The core fix is mapping the flat event stream onto a layered call-chain model. At least four layers are recommended:
| Layer | Semantics | Key attributes |
|---|---|---|
| Task (turn) | Full lifecycle of one user request | Task ID, status, total duration, total tokens, failing stage |
| Reasoning round (step) | One round of model reasoning and decision | Round index, input/output tokens, model name, duration |
| Model call | A single model request | Time to first token, generation rate, retry count, error code |
| Tool call | A single tool execution | Tool name, argument summary, return code, execution duration, sandbox interception |
With these four layers, all three question types can be answered structurally: latency attribution looks at the ratio of model call time to tool call time within a step; cost distribution aggregates tokens by task, model, and session; failure replay locates which round failed, which tool was called, and what it returned.
Illustrative structure (pseudocode, expressing field semantics only):
span = {"trace_id": task_id, # one task"span_id": step_id, # one reasoning round"parent_id": task_id,"kind": "llm" | "tool","attrs": {"model": "...", "tokens_in": 0, "tokens_out": 0},"duration_ms": 0,"status": "ok" | "error","error": {"code": "", "stage": "model|tool|sandbox"}}
4. Collection Side: Native Plugin Mounting, Zero Intrusion
The recommended approach is to mount collection as a native plugin at the framework kernel layer, rather than bolting on an external log-parsing script. Three reasons: the kernel owns plugin assembly and lifecycle, so it has complete turn/step boundaries; the event stream itself is lossless, so a plugin can subscribe directly without rewriting business logic; and all three runtime forms share the kernel, so one integration covers all of them.
Implementation points for collection:
- Asynchronous batch reporting: collection must not block the ReAct loop; use a local queue plus batch sends, with a forced flush when the process exits;
- Sensitive data redaction: tool arguments and returns may contain credentials or internal addresses, so field-level redaction and length truncation are needed on the collection side;
- Offloading large fields: full arguments and outputs go to object storage, with only a reference ID kept in the trace, avoiding trace data bloat;
- Failures must leave a trace: exceptions, timeouts, and sandbox interceptions must be reported as spans, otherwise the most critical segment is exactly what is missing during replay.
5. Storage and Query: Cross-Session, Cross-Machine, Long-Term Retention
Collected data needs three storage layers working together: trace data goes to a trace retrieval service supporting filters by trace_id, tool name, status, and time window; structured metrics go to a logging service for aggregation and dashboards; large raw payloads go to object storage for retrieval on demand. This upgrades “local, single-session, real-time viewing” into “historically queryable across sessions and machines.”
The query layer should offer three query templates: slow-task TopN (sorted by total duration), high-consumption sessions (aggregated by tokens), and failure clustering (grouped by failing stage and error code). These three cover most day-to-day troubleshooting entry points.
6. Attributing Cost and Latency
Latency attribution cannot look at total duration alone; it has to look at the ratio structure. Within the same task, if model calls dominate, the optimization directions are model selection, context trimming, and prompt compression; if tool calls dominate, the directions are parallelization, caching, and reducing sandbox startup overhead.
Cost attribution must separate “tokens that produced effective output” from “tokens spent on retries and wasted rounds.” In a ReAct loop the model may probe repeatedly; without round markers, cost looks inflated and the waste cannot be located. A two-dimensional aggregation by model and by task is recommended, keeping the round index so you can drill down.
7. Alerting and Dashboards: From Passive Lookup to Active Discovery
Configuring alerts on aggregated data is more sustainable than manual inspection. Example rules: task failure rate exceeding a threshold over a 5-minute window; step count for a single task exceeding the baseline mean by some multiple (usually a sign of a loop); tool error codes appearing in clusters (usually an environment or permission problem); an abnormal spike in token consumption rate.
Dashboards should have three sections: overall health (success rate, P50/P95 duration), cost distribution (by model, task, and time period), and a failure leaderboard (clustered by stage and error code).
8. Rollout Steps and Common Pitfalls
A four-step rollout is recommended: first define span semantics and field conventions; second implement the collection plugin and run a canary on a single runtime form; third connect storage and the three query templates; fourth configure alerts and review.
Common pitfalls include: collecting only the success path, which breaks the chain during replay; stuffing large fields into the trace, which degrades both storage and query; synchronous reporting that blocks and slows tasks; a missing unified trace_id, which breaks cross-layer correlation; and ignoring the compliance risk of skipping redaction.
9. Conclusion
The bottleneck for scaling agents is often not model capability but whether the process is observable. Abstracting the runtime event stream into a layered call chain, combined with the general-purpose capabilities of logging services, trace retrieval, object storage, and monitoring alerts, lets teams turn the three questions of latency, cost, and failure from experience-based judgment into data-backed conclusions. Baidu AI Cloud has accumulated relevant general capabilities in observability and log analysis, which can serve as a practical reference for this kind of solution.
