Observability for AI Agents at Scale: A Practical Guide to Structured Tracing, Cost Attribution, and Failure Replay
As coding agents move into daily development workflows, scaling shifts the hard questions from "was the answer correct" to "where did the time go, where did the cost go, and where did the failure happen." This article takes a neutral look at why the common "microkernel plus fully pluggable" architecture and the ReAct execution loop make these agents hard to observe, then lays out a complete approach: reconstructing each task as a structured call chain of Task, Turn, Step, ModelCall, and ToolCall; designing an event model and a collection plugin; retaining data across sessions and machines over the long term; and using trace lookup, aggregate analysis, and monitoring alerts to attribute latency, roll up cost, and replay failures. Illustrative data structures and code are included so you can build a reusable agent observability system on your own stack.
As coding agents become part of everyday development workflows, the questions that matter change once you scale. Correctness of a single answer is no longer the hard part. Once dozens or hundreds of tasks run concurrently and keep running for weeks, three questions become genuinely difficult to answer:
- Latency attribution: within a task’s total duration, how much goes to model inference, how much to tool execution (reading and writing files, running commands, calling external services), and how much to queuing and network waits.
- Cost allocation: which sessions, models, and task types concentrate token consumption, and whether any session shows abnormal amplification.
- Failure replay: at which step a failure or interruption occurred, what the context, tool inputs, and returns looked like at that moment, and whether a failure from several days ago can be fully reproduced.
These three questions share one trait: none of them can be answered from a single session, a single machine, or a real-time view. They require structured trace data that spans sessions and machines and is retained over the long term.
1. Why These Agents Are Hard to Observe by Design
1.1 Microkernel plus fully pluggable architecture
Mainstream coding agent frameworks are generally organized as a microkernel with fully pluggable components. The kernel only assembles plugins according to a configuration (profile) and manages their lifecycle; model adapters, tool sets, sandbox policies, and session persistence are all pluggable plugins. Multiple form factors, including command line, terminal UI, and headless, share the same kernel. This design has two consequences for observability:
- Upside: observability can be mounted at the kernel layer as a plugin too, without intruding on business logic, and it naturally covers every form factor.
- Challenge: the execution path is determined by the plugin combination, and the tool set differs across profiles, so collection points must sit uniformly at the kernel boundary rather than being scattered across individual plugins.
1.2 The ReAct loop: structure is undetermined until runtime
The execution model is a reason-act loop. One user task is a turn, and within a turn each round of reasoning, tool invocation, and observation 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 starts.
This means the traditional approach of instrumenting a fixed span tree does not apply. You need an event stream plus post-hoc reconstruction approach: first persist every atomic event, then rebuild the call chain on the analysis side using turn and step relationships.
2. Observability Data Model
A four-layer structure works well, narrowing scope layer by layer:
Task└── Turn (one user request)└── Step (one round of reasoning + tool call + observation)├── ModelCall (model call, with token metering)└── ToolCall (tool call, with input/return summary)
Illustrative event structure (pseudocode):
{"trace_id": "t-9f2c","task_id": "task-118","turn_id": "turn-3","step_index": 2,"event_type": "tool_call","span_kind": "TOOL","name": "shell.exec","start_ms": 1730000000123,"duration_ms": 842,"attributes": {"tool": "shell","exit_code": 0,"io_bytes": 4096},"cost": { "input_tokens": 0, "output_tokens": 0 }}
Key design principles:
- One trace_id across the whole chain, with task, turn, and step as hierarchy attributes, so you can aggregate at any level.
- Meter model calls and tool calls separately: the former records tokens, the latter records duration and I/O, which avoids charging all latency to the model.
- Write both events and spans: the event stream supports complete replay, while spans support aggregate analysis and flame-graph style latency breakdowns.
3. Collection: A Plugin at the Kernel Boundary
The collection plugin should attach at the kernel’s plugin assembly layer and subscribe to lifecycle hooks such as turn start and end, step iteration, before and after model calls, and before and after tool calls. It reports events asynchronously in batches to a backend (buffered through a message queue or logging service, for example) so the main execution path is never blocked.
Kernel lifecycle hookson_turn_start -> generate turn_id, initialize step counteron_step_begin -> step_index++, record reasoning starton_model_end -> collect token usage, model identifier, time to first tokenon_tool_begin -> record tool name, input summary (redacted)on_tool_end -> record duration, exit code, output summaryon_turn_end -> aggregate turn-level duration and cost, persist
Engineering notes:
- Async and sampling: under high concurrency, sample the I/O details of tool calls, but keep model calls and error events at full volume.
- Redaction: secrets, paths, and user data in inputs are hashed or masked on the collection side.
- Resume after interruption: persist locally first and report afterwards, so a process crash does not lose events.
4. From Data to Answers: Three Query Patterns
4.1 Latency attribution
Aggregate model_call.duration and tool_call.duration by step to get the latency breakdown of a single task, then aggregate by tool name to find the slowest tool. Example:
turn-3 total duration 12.4s├─ model inference 7.1s (57%)├─ tool shell.exec 3.8s (31%) ← slowest tool└─ queue/network 1.5s (12%)
4.2 Cost allocation
Aggregate tokens by model + session + task_type to produce the top-N sessions and detect abnormal amplification (for instance, a session whose token usage grows several times over the previous period).
4.3 Failure replay
Pull the complete event stream by trace_id and replay reasoning and tool calls in step order. This pinpoints the failing step and its context, making a failure from several days ago reproducible.
5. Platform Capabilities
Once the collected data lands in a unified backend, you can compose a full capability set: trace lookup (filter by trace, task, or tool), aggregate analysis (latency and cost dashboards), and monitoring alerts (failure rate, plus alerts when a single task’s duration or token usage exceeds a threshold). On the cloud, you can reuse general-purpose building blocks: a message queue for buffering, object storage for long-term retention, a logging service for search, and monitoring and alerting for threshold notifications. That yields cross-session, cross-machine observability at a relatively low integration cost.
6. Conclusion
Observability for agents at scale comes down to turning an execution structure that is uncertain at runtime into a structured trace that can be rebuilt after the fact. Collect uniformly at the kernel boundary as a plugin, let an event stream support post-hoc reconstruction, answer latency and cost questions with aggregate analysis, and rely on the full event set for failure replay. That is enough to build an agent observability system on your own stack that stays neutral, reusable, and able to evolve over time.
