Observability for AI Agents at Scale: Building Structured Tracing
As AI agents move into daily development workflows, observability requirements change once usage scales. This article explains why agent execution data is naturally tree-structured rather than linear, where built-in observability in common open-source coding agent frameworks falls short, and how to add a collection plugin that turns event streams into structured traces across collection, transport, storage, and analysis layers. It also covers how to investigate latency attribution, token cost distribution, and failure reproduction, along with practical notes on sampling, clock synchronization, and alerting.
1. Why Observability Requirements Change at Scale
AI agents are now part of many teams’ daily development workflows. When call volume is low, developers only need to check whether a single execution result matches expectations. But as task volume, machine count, and concurrent sessions all grow, users naturally start focusing on three things:
- Whether time is spent on model inference or on tool execution;
- Which sessions, models, and task types account for most token consumption;
- Where failures and interruptions occur, and whether the process can be fully traced and reproduced.
All three share a prerequisite: structured, correlatable process data that can be retained over the long term. However, the observability built into most open-source agent frameworks is designed for “local, single-session, real-time troubleshooting,” which does not match the requirements at scale.
2. Execution Structure of General-Purpose Coding Agents: Why Process Data Is a Tree, Not a Line
Taking a common open-source coding agent framework as a sample (a CLI form that lets the model read and write files, execute commands, and call external services in a controlled environment, deciding the next step based on each result), its organization is typically a microkernel with 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 components. The CLI, terminal interaction, and headless forms share the same kernel. Observability naturally attaches at the plugin layer, making it the most straightforward integration point.
The execution model is a ReAct loop: one user task is called a turn, and each round of “reasoning—calling a tool—observing the result” within a turn is called a step. The key conclusion is that the number of loop iterations and which tools get called are decided by the model at runtime, so the execution structure cannot be determined before the run.
This leads to two engineering facts:
- Process data is essentially a dynamically generated call tree, not a fixed pipeline, so it cannot be modeled with static instrumentation or fixed stage divisions;
- The event sequence of a single session is complete, but it lacks cross-session call relationships and latency attribution, so it cannot answer “how is the overall performance?”
3. Three Built-In Capabilities and Three Gaps
These frameworks typically provide three capabilities out of the box: a session trace view organized by iteration in the browser (showing tokens and latency for individual records); a complete event stream persisted losslessly as compressed JSONL in the local session directory; and tool call inputs and returns recorded in the event stream, with full-text session search supported.
The capabilities are not weak, but the boundaries are clear, and there are three gaps:
- The scope is the local machine. In multi-machine deployments, data is scattered and cannot be compared horizontally.
- The scope is a single session. There are no explicit parent-child relationships between turns, steps, model calls, and tool calls, so latency cannot be attributed bottom-up.
- The lifecycle is real-time. A failure from a few days ago has often already been cleaned up locally or sits on someone’s machine.
4. Overall Approach: Filling the Structured Trace Gap as a Native Plugin
The recommended approach is not to replace the framework’s built-in capabilities, but to add a collection plugin at the plugin layer that converts the event stream into structured traces and reports them, forming four layers:
- Collection layer: subscribe to session lifecycle and event streams, generating spans at four granularities—turn, step, model call, and tool call;
- Transport layer: local batch buffering, retry on failure, rate limiting, and sampling to prevent observability from impacting the main flow;
- Storage layer: trace data goes into a log/storage service built for long-term retention, while raw event streams are archived to object storage;
- Analysis layer: trace search, aggregate analysis, and monitoring/alerting dashboards.
Illustrative attribute design (pseudocode, only expressing the modeling idea):
span(name="step", id=..., parent=turn_id,attrs={"step.index": 3, "model": "...", "tool": "shell"})span(name="model_call", parent=step_id,attrs={"in_tokens": ..., "out_tokens": ..., "latency_ms": ...})span(name="tool_call", parent=step_id,attrs={"tool.name": ..., "exit_code": ..., "latency_ms": ...})
5. How to Investigate Three Common Questions
Latency attribution: attaching two types of child spans—model calls and tool calls—under each step allows bottom-up aggregation to get the “inference share vs. tool share,” and to further pinpoint slow tools and slow models.
Cost distribution: tokens are reported only at the model-call granularity; combined with session tags, model names, and task types for multi-dimensional aggregation, this can produce consumption distributions by session, by model, and by time window, providing a basis for quotas and optimization.
Failure tracing: record a termination reason for each execution (normal completion, unparseable model output, tool timeout, or interruption), with failed spans carrying error codes and key context; because data is centrally retained, a trace ID or time window can be used to search and reproduce a problem from several days ago.
6. Implementation Notes
Prioritize sampling and redaction to avoid the overhead of full reporting and the leakage of sensitive information; unify clocks, since cross-machine attribution depends on a consistent time baseline; retain the raw event stream as a fallback, so structured traces and raw data validate each other; alert thresholds should be based on percentiles rather than averages, as long-tail tasks more easily expose real problems. Building the collection and retention pipeline on cloud log services, monitoring/alerting, and object storage provides elasticity and durability while remaining compatible with local development workflows.
