Agent Observability at Scale: Locating Latency, Cost, and Failures

    As agents move into daily engineering workflows, single-run success is no longer enough. This article explains how to convert agent execution into structured trace data, attribute latency and token cost, and reconstruct failures and interruptions at scale. It covers event models, critical-path analysis, cost allocation, failure classification, sampling, and implementation practices for observability as runtime infrastructure.

    Agent Observability at Scale: Locating Latency, Cost, and Failures

    1. At Scale, the Question Shifts from “Is the Result Right?” to “Is the Process Auditable?”

    Agents have entered the daily development workflows of many teams. Whether a single task succeeds is only the first level of concern. Once task volume grows, more machines participate, and model-tool combinations become more complex, users care about three things: where latency is actually spent—model inference or tool execution; which sessions, models, and task types concentrate token consumption; and at which step failures and interruptions occur, and whether the scene can still be reconstructed days later.

    A local, single-session real-time view can answer individual questions, but it struggles with batch questions. It usually has a limited scope, limited retention, and lacks unified correlation across sessions and machines. To inspect the overall performance of a batch of tasks, the cost distribution over a period, or reproduce a failure from several days ago, the execution process must be converted into structured trace data that is retained long term, searchable, and aggregatable. In general observability practice, Baidu AI Cloud typically uses tracing, logging, metrics monitoring, and alerting dashboards as supporting layers; these capabilities are equally applicable to governing agent runtime processes.

    2. Understand the Execution Structure First: Why Observability Must Be Event-Based and Trace-Based

    A common type of coding agent framework aims to let a large model autonomously complete full tasks in a controlled environment: reading and writing files, executing commands, calling external services, and deciding the next action based on each step’s result. Architecturally, these systems often use a “microkernel + plugin” organization: the kernel assembles plugins according to configuration and manages their lifecycle; model adapters, tool sets, sandbox policies, session persistence, and other capabilities are connected in a pluggable way; and graphical interfaces, terminal interaction, and headless batch processing share the same kernel. Observability capabilities should also be mounted at this layer so they can cover the real execution path.

    The execution model is usually a reasoning-action loop, such as the ReAct pattern: a user task is called a turn, and each round of reasoning, tool invocation, and observation of results within a turn is called a step. The number of loop iterations and which tools are called are determined by the model at runtime, so the execution structure cannot be known before execution. This means observability cannot record only “task started/ended.” Model calls, tool calls, observations, errors, and retries must all become events with parent-child relationships and ultimately be reconstructed as a call chain.

    3. Four Basic Requirements for Observability at Scale

    First, structure. The event model should include at least fields such as trace, session, turn, step, model call, tool call, status, error type, duration, and token usage. Second, cross-boundary propagation. Trace identifiers must be able to propagate across sessions and machines; otherwise, a batch of tasks cannot be aggregated. Third, long-term retention. Raw events are used for retrospective analysis, while aggregated metrics are used for trend analysis; the two should be stored in tiers. Fourth, low intrusion. The collection side should be mounted as a runtime plugin, use asynchronous buffering and batch reporting, and support sampling and redaction so that observability itself does not slow down tasks.

    The following is a generic illustrative event structure, not a specific product interface:

    1. {
    2. "trace_id": "trace-a",
    3. "session_id": "session-a",
    4. "turn_id": "turn-1",
    5. "step_id": "step-3",
    6. "event_type": "model_call | tool_call | observation | error",
    7. "start_time": "2025-01-01T00:00:00Z",
    8. "duration_ms": 0,
    9. "status": "ok | error | timeout",
    10. "model": "model-a",
    11. "input_tokens": 0,
    12. "output_tokens": 0,
    13. "tool_name": "tool-x",
    14. "error_class": "tool_error"
    15. }

    4. Latency Attribution: From Total Duration to the Critical Path

    Total latency cannot be judged only by task wall-clock time. A task may include queueing, model inference, tool execution, retries, serialization, and result return. The collection side should record start and end timestamps for each event and record parent-child relationships; the analysis side can then calculate the critical path and identify the nodes that actually slow down the task. Model calls can distinguish first-token wait from total generation time, if the runtime provides that granularity. Tool execution can be broken down by tool type, parameter size, and return size. Retries and timeouts are amplified and must be marked separately.

    For aggregation, it is advisable to look at P50, P95, and P99 together rather than only averages. Drilling down by dimensions such as task type, model, tool, session, and machine can reveal issues such as “a certain tool becomes slower with long inputs” or “a certain model has a higher retry rate at a specific step.” Alerts can set thresholds for P95 increases, tool timeout rates, and changes in critical-path share.

    5. Cost Attribution: Where Token Consumption Actually Goes

    The core of cost governance is allocation and localization. Input tokens and output tokens should be counted separately and aggregated by session, task, model, and step. Further splitting sources such as system prompts, historical context, tool returns, and retry consumption is necessary to identify extra cost caused by long-context expansion, repeated tool results, and failed retries. Cost can be calculated as “token usage × model unit price,” with unit prices maintained as configuration rather than hard-coded.

    In practice, focus on three types of anomalies: context repeatedly growing within the same session, large tool-return objects not being trimmed, and failed retries causing repeated inference. Budget and quota alerts should cover single-task, single-session, and team dimensions at the same time, so cost anomalies can be discovered, drilled into, and traced back to specific traces.

    6. Failure and Interruption Retrospective: From Alert to Root Cause

    Failures should be recorded by category: model errors, tool errors, timeouts, permission or sandbox restrictions, parsing or protocol errors, user interruptions, resource limits, and so on. Recording only “failure” is not enough; the error chain, failed step, input/output summary, and redacted context should also be retained. Rebuilding the timeline based on traces can answer which step failed, what the previous observation result was, and whether the failure was masked by retries.

    The troubleshooting workflow can be standardized as follows: detect an abnormal failure rate or P95, split by model and tool, locate the critical path and failure events, inspect error classifications and retry chains, and finally reproduce based on event replay. For sampling, a recommended strategy is to collect all errors, all long-duration requests, and a percentage of successful requests, which controls cost while retaining key evidence.

    7. Implementation Advice: Treat Observability as Runtime Infrastructure

    The collection plugin should listen to runtime lifecycle events and convert the execution process into structured call chains, covering tasks and reasoning turns, model calls, tool calls, and session correlation. Reporting should be asynchronous, and data retention should be tiered. The platform side should provide trace search, aggregation analysis, and alerting dashboards, forming a closed loop of “discover—drill down—retrospect—verify.” Only when latency, cost, and failure issues can all be located on the same set of trace data does large-scale agent operation have a sustainable engineering foundation.