Agent Observability at Scale: How to Investigate Latency, Cost, and Failures

    As AI agents move from pilots to production workloads, local logs are no longer enough to explain slow tasks, rising token costs, or failures across machines. This article outlines how to model turns, steps, model requests, and tool calls as structured traces, then use them to analyze latency, attribute costs, and reconstruct failures through a runtime-level instrumentation plugin.

    What Changes When Agent Workloads Scale

    AI agents are moving from pilot projects into everyday software development. A single task can involve multiple rounds of reasoning, repeated tool calls, and an execution path that cannot be predicted in advance. When concurrent sessions grow from a handful to hundreds or thousands, tasks run across machines, and failures need to be investigated days later, the question is no longer simply, “Was this answer correct?”

    Three engineering questions become more important:

    1. Where did the time go? Was it spent on model inference, tool execution, sandbox setup, networking, or queueing? Without a breakdown, optimization becomes guesswork.
    2. Where are tokens being consumed? Which sessions, task categories, and model calls account for the usage? This is essential for attributing costs to business functions.
    3. Where did execution fail or stop? Was the cause malformed model output, a tool timeout, a permission denial, or an external cancellation? Can the full sequence be reconstructed through its call relationships?

    Answering these questions requires more than a chronological log. It requires structured execution data that can be correlated across sessions and machines and retained for later investigation.

    The Coding Agent Execution Model: Turns and Steps

    A common coding agent design lets a large language model complete a task autonomously within a controlled environment. The agent reads and writes files, executes commands, calls external services, and decides what to do next based on each observation.

    These systems often use a microkernel-and-plugin architecture. The core assembles model adapters, toolsets, sandbox policies, and session persistence from configuration. Terminal, graphical, and headless interfaces share the same lifecycle. Observability should attach at this shared runtime layer rather than depend on a particular interface.

    Execution typically follows a reasoning–action–observation loop:

    • A turn is one user task.
    • A step is one iteration of reasoning, tool invocation, and observation within that turn.

    The model decides at runtime how many iterations to run and which tools to call. The execution structure therefore cannot be determined statically before the task starts. Observability must reconstruct the actual call relationships rather than assume a fixed call graph.

    A turn typically produces at least two kinds of output:

    • A human-readable execution view showing token usage and latency by iteration.
    • A complete machine-readable event stream for later search and analysis.

    Storing that event stream as compressed JSON Lines in a local session directory preserves detailed records and supports full-text searches of tool inputs and outputs. This can be sufficient for real-time troubleshooting on a single machine within a single session.

    What Chronological Events Cannot Provide at Scale

    Local, time-ordered session events explain what happened in one execution. As workloads grow, three limitations become more significant.

    Missing explicit call relationships

    A flat event sequence does not necessarily encode parent-child or causal relationships among reasoning spans, model requests, tool spans, and subtasks. Without those relationships, it is difficult to determine how much of a step’s duration came from the model versus tools, or to locate a failure within a specific step.

    Missing shared identifiers across sessions and hosts

    Tasks may be scheduled on different machines, with session files stored separately. Investigating a failure several days later may require logging into the original host and searching compressed files. There is no unified way to filter by task ID, user, or error code.

    Missing aggregatable metrics

    Token usage, latency, and failure rates need to be broken down by model, tool name, task type, and time window. Without these dimensions, cost and reliability cannot become part of routine operations, dashboards, or alerting.

    The solution is an instrumentation plugin layered over the native event stream. Without changing application semantics, it reconstructs structured traces covering tasks, reasoning steps, model calls, tool calls, and session relationships.

    What a Structured Trace Should Capture

    At a minimum, model the following objects as queryable entities connected through consistent trace and span semantics.

    Task or Turn

    Represent the lifecycle of one user goal, including start time, end time, final status, and associated session. This is the primary aggregation dimension for cost and success rate.

    Step

    Represent one reasoning–action–observation iteration. Record the step number, sanitized summaries of its inputs and outputs, total token usage, and duration.

    Steps are essential for answering, “Which iteration did the task get stuck in?”

    Model Call

    Capture each request to and response from a language model, including:

    • Model identifier or category, without tying the schema to a specific vendor.
    • Input and output token counts.
    • Time to first response chunk.
    • Total latency.
    • Whether the response was streamed.
    • Finish reason.

    Most cost analysis happens at this level.

    Tool Call

    Record the tool name, a summary of its arguments, return code, duration, and whether it timed out or was blocked by policy.

    Tools are often a source of tail latency and a frequent point of failure.

    Session Relationships

    Use session IDs and parent task IDs to connect consecutive turns from the same user or repeated attempts on the same code repository. These relationships help prevent retries from being treated as unrelated new traffic.

    Instrumentation should attach to the core lifecycle as a plugin, independently of the interface. Headless batch workloads and interactive use should produce the same trace structure.

    Investigating Latency: Break It Down Before Drilling Down

    An end-to-end duration alone is not enough to diagnose latency. Use a consistent breakdown:

    • Queueing and scheduling: Time from the task entering the execution environment to the start of the first reasoning step.
    • Model inference: Latency across model calls, further separated into time to first response and generation time where available.
    • Tool execution: Durations of tool spans, with particular attention to P95 and P99 rather than averages.
    • Framework overhead: Serialization, sandbox preparation, event persistence, and plugin hooks.

    Start by examining P99 latency by task type to determine whether the bottleneck is the model or a category of tools. Then open traces for slow tasks and inspect flame-chart-style timelines organized by step.

    For an intermittently timing-out tool, span attributes should expose the timeout threshold, retry count, and error type. A session-level “execution interrupted” message is not enough.

    An illustrative query—not a product-specific interface—would aggregate sum(model_latency) and sum(tool_latency) over a time window, then group tool latency by tool_name to calculate P99. This makes it possible to direct optimization toward a specific tool implementation or model-selection strategy.

    Investigating Tokens and Cost: Sessions, Models, and Tasks

    Runaway costs often come from long-tail sessions with repeated retries, steadily expanding context, or task categories routed to higher-priced models. Analyze usage across at least three dimensions.

    By Session

    Identify sessions with unusually high token consumption. Check whether context is being trimmed and whether complete tool outputs are repeatedly fed back into the model.

    By Model Call Type

    If the application routes calls by purpose, distinguish planning, coding, review, and other call types. Examine both usage and the applicable unit cost.

    By Task

    Retries multiply the tokens consumed for the same business goal. Attribute that usage to the eventual successful task rather than evaluating cost only by the number of model calls.

    Persisted events often already contain usage fields. The key is attaching those fields to the trace so they can support operational questions, such as comparing a business function’s weekly token usage with the same period a year earlier.

    Alerts should cover the rate of anomalous sessions, per-task token limits, and the failure-to-retry ratio—not just total token consumption.

    Investigating Failures and Interruptions: Reconstruction Matters

    Agent failures take many forms: unparseable model output, tool permission denials, processes terminated by the sandbox, user cancellations, and upstream rate limits.

    A final error string cannot answer the questions that matter:

    • Which step failed?
    • What were the inputs at that point?
    • Had execution already produced side effects, such as modifying files?

    Each span should record its status—success, failure, or cancellation—along with an error category and a reference to the original event stream. This preserves detailed events for auditing while enabling platform-level aggregation by error code.

    Reconstructing a failure from several days earlier depends on long-term retention and cross-machine indexing, not on whether the original local directory still exists.

    Use a consistent investigation sequence:

    1. Check the task’s final status.
    2. Find the last failed span.
    3. Inspect whether earlier tool calls in the same turn succeeded.
    4. Examine whether that step’s model output led to the tool call that failed.

    This turns vague reports of intermittent interruptions into specific, actionable failure categories.

    Integrating with an Observability Platform

    Agent instrumentation should extend existing application observability—logs, metrics, and traces—rather than create an isolated system.

    Once the missing instrumentation is in place, task success rates, step failure rates, model latency, tool P99 latency, and token usage can feed unified search, aggregation, dashboards, and alerts.

    Different storage and analysis layers serve different purposes:

    • Object storage is suitable for long-term retention of compressed events.
    • Log services support event searches and full-text retrieval.
    • Monitoring and alerting support service-level objectives.

    The central requirement is semantic alignment. Agent turns and steps should map to standard traces so their execution can be correlated with the surrounding microservices.

    The instrumentation plugin should observe execution without modifying it. Sampling and redaction must be controlled, especially for secrets, source code, and user data, so observability does not become a performance bottleneck or a compliance risk.

    Practical Implementation Priorities

    Start with identifiers: task IDs, session IDs, and step numbers must remain consistent across logs and traces.

    Next, attach the plugin at the core runtime layer so terminal, graphical, and headless execution produce structurally consistent data.

    Then implement a minimal useful breakdown:

    • Latency: Model, tools, and other overhead.
    • Failures: Model, tool, policy, and cancellation.

    Add detailed cost allocation after those foundations are reliable. Do not let the pursuit of a perfect flame chart delay basic operational visibility.

    At scale, agent engineering quality depends on turning an unpredictable execution loop into a process that can be queried, aggregated, and monitored. Clear latency attribution, token usage linked to sessions and tasks, and failures pinned to specific steps enable teams to move beyond checking individual answers and start managing the reliability and cost of entire workloads.