Scaling AI Agents: How to Troubleshoot Latency, Cost, and Failures

    This article explains how to build observability for coding agents once they move from individual trials into daily team workflows. It covers the common runtime architecture of agent frameworks, why fixed instrumentation and static APM approaches fall short, and the limits of built-in single-session tooling. The core of the article is a three-part troubleshooting method: decomposing latency into model inference and tool execution, attributing token consumption by session, model, and task type, and making every interruption reproducible through unified error classification, context capture, and replay. It closes with a practical adoption checklist for teams building cross-session, long-term trace data.

    1. Introduction: What Changes at Scale

    When coding agents move from isolated trials into everyday team development workflows, the concerns of the people using them shift noticeably. At small scale, the only question is “was this particular output correct?” Once usage scales up, three operational problems become the real headaches:

    • Latency breakdown: Where does the time in a single task actually go — model inference, or tool execution (compilation, tests, command invocation)?
    • Cost distribution: Which sessions, models, and task types concentrate token consumption, and is there any abnormal amplification?
    • Failure traceability: At which step did a failure or interruption occur, what was the input context, and can it be fully reproduced days later?

    All three share one prerequisite: structured trace data that spans sessions and machines and can be retained long term. The observability built into most open-source agent frameworks is scoped to a single machine, a single session, and real time — it can answer “what just happened,” but it struggles to answer “how did things perform over the past week.”

    This article takes the general form of an “intelligent coding tool,” abstracts its runtime structure, and lays out a product-agnostic approach to building observability. If a team uses general-purpose capabilities such as the monitoring and alerting, log service, and container platform offered by Baidu AI Cloud to carry collection and visualization, the approach can be implemented directly on that foundation.

    2. General Principles of Agent Runtime: Why Model Before You Observe

    To investigate latency, cost, and failures, you first have to understand the execution structure. Mainstream coding agents (in command-line form) typically share these characteristics: they autonomously complete a full task inside a controlled sandbox — reading and writing files, executing commands, calling external services — and decide the next action based on the result of each step.

    Architecturally, a common industry approach is a “microkernel with full plugin architecture”: the kernel only assembles plugins according to a configuration profile and manages their lifecycle, while model adapters, tool sets, sandbox policies, and session persistence are all pluggable plugins. The command-line, terminal UI, and headless forms share the same kernel. Observability should be mounted at this same layer, which is what makes it form-agnostic.

    In terms of the execution model, a ReAct loop is the norm:

    • One user task is called a turn;
    • Within a turn, each round of “reason → call tool → observe result” is called a step;
    • The number of loop iterations and which tools get called are decided by the model at runtime.

    This leads to one key conclusion: the execution structure cannot be determined before the run. So the traditional APM approach based on fixed instrumentation or a static topology does not apply. You must first reconstruct the runtime process into a tree- or chain-shaped structured call trace, and only then aggregate on top of it.

    A single turn typically produces two outputs: a human-facing “session trajectory view,” and a complete machine-facing event stream (a common practice is to write it to disk as compressed JSONL, losslessly). The former suits single-case troubleshooting; the latter is the data source for building cross-session analysis.

    3. The Limits of Built-In Capabilities: From “Single-Session Real Time” to “Globally Operable”

    Open-source frameworks usually ship three out-of-the-box capabilities:

    1. Session trajectory: Execution records organized by turn inside the browser, where you can inspect token usage and latency for an individual record;
    2. Event stream persistence: The complete event stream stored compressed in a local session directory, with no loss of information;
    3. Tool call search: Tool inputs and returned results recorded in the event stream, with full-text search within a session.

    These three capabilities solve “instant troubleshooting on a single machine and session,” but scaled scenarios immediately expose four gaps:

    • Data silos: Files are scattered across individual developer machines and cannot be queried centrally;
    • No cross-session aggregation: You cannot compute “average latency of a given model over the past seven days” or “failure rate of a given tool”;
    • Limited retention: Local files are subject to disk capacity and cleanup policies, so a failure from a few days ago may already be gone;
    • No proactive detection: You can only wait passively for users to report problems, with no threshold-based alerting.

    The way to close these gaps is to introduce a collector in native plugin form: mount it as a plugin at the kernel layer, subscribe to the event stream, convert the execution process into a structured call trace covering four levels — task and reasoning turns, model calls, tool calls, and session correlation — and then report it to a centralized backend.

    An illustrative level model (fields are generic examples, not a specific interface):

    1. {
    2. "trace_id": "t-20260812-001",
    3. "session_id": "s-77",
    4. "turns": [{
    5. "turn_id": 1,
    6. "steps": [{
    7. "step": 2,
    8. "llm_call": { "model": "chat-model", "in_tokens": 8120, "out_tokens": 431, "latency_ms": 6820 },
    9. "tool_call": { "name": "run_command", "args_hash": "a1b2", "latency_ms": 24500, "status": "error" }
    10. }]
    11. }]
    12. }

    With a unified model in place, latency, cost, and failure questions become different query dimensions over the same table.

    4. Troubleshooting Latency: Splitting Time into Inference and Execution

    The core of latency troubleshooting is not looking at total duration but performing attribution decomposition:

    • Split by layer: Total turn latency = Σ(step inference latency) + Σ(tool execution latency) + scheduling and queueing overhead. If tool execution consistently accounts for a larger share than inference, optimization should focus on command timeouts, dependency installation, caching, and parallelization; otherwise, focus on context length, prompt redundancy, and model selection.
    • Look by percentile: Averages hide the long tail, so observe P50/P90/P99. Latency distributions for coding agents are usually extremely long-tailed, with P99 often several times P50.
    • Drill down by tool: Aggregate with tool name as a dimension to quickly identify the “five slowest tools” and the “five slowest models.”
    • Separate queueing from execution: When queueing exists on the container platform or gateway side, queueing time must be listed separately, or you will misdiagnose it as the model getting slower.

    One practical rule: when the median step count for a class of tasks rises while per-step latency stays flat, the model is “taking more detours” — that is a prompt or tool-description problem, not a performance problem.

    5. Troubleshooting Cost: A Consistent Basis for Token Attribution

    Cost analysis starts with a unified basis. It is advisable to build dashboards along at least these dimensions:

    • Session dimension: Identify the top N sessions by consumption and judge whether they are legitimate long tasks or loops spinning idle;
    • Model dimension: Compare per-task token cost across models to spot mismatches where “an expensive model is used for simple tasks”;
    • Task type dimension: Refactoring tasks are naturally multi-turn and need a separate baseline from Q&A tasks;
    • Input-to-output ratio: An abnormally high share of input tokens usually means context is accumulating or historical trajectories are being carried repeatedly, which can be improved by trimming history and summary compression.

    It is worth stressing that billing rules differ substantially across vendors. This article gives no specific unit prices; teams should rely on their own contracts and bills, and treat “token volume” as a technical metric to optimize first, independent of billing, before mapping it to cost.

    6. Troubleshooting Failures: Making Every Interruption Reproducible

    The difficulty of failure troubleshooting lies in the “process nature” of agents — the same prompt takes different paths under different contexts. Four steps make it actionable:

    1. Unified error classification: Distinguish model-layer errors (rate limiting, timeouts, content refusal), tool-layer errors (non-zero exit codes, missing dependencies), framework-layer errors (plugin exceptions, context overflow), and manual interruptions;
    2. Preserve the scene: Record tool input digests, return codes, and key stdout fragments in the trace, with sensitive information hashed or redacted;
    3. One-click replay: Use the trace_id to look up the complete event stream and replay it in an isolated sandbox following the same step sequence, to verify whether the issue is intermittent or consistently reproducible;
    4. Failure-rate dashboard plus alerting: Compute failure rates by tool, model, and task type, and set threshold alerts for sudden spikes — moving from passive reporting to proactive detection.

    On Baidu AI Cloud, trace data can be written to the log service for long-term retention and search, threshold policies can be configured with monitoring and alerting, and “a failure from a few days ago” becomes a record that can be queried and replayed.

    7. Adoption Checklist

    • Collection must be plugin-based, avoiding intrusion into the kernel and business code;
    • The event stream is the source of truth and views are only projections — do not conflate the two;
    • Unify the three-level trace/turn/step model first, then build dashboards, otherwise metric definitions will require repeated rework;
    • Redact sensitive information at the collection end; trace data also needs access control and auditing;
    • Start with a small pilot, covering just two metrics — failure rate and P99 latency — before extending to cost analysis.

    At scale, agent observability is essentially a data engineering problem: turning a non-deterministic execution process into structured facts that can be queried, aggregated, and replayed. Once that is done, latency, cost, and failures no longer have to be guessed at.