Scaling AI Agents in Production: Latency, Cost, and Failure Troubleshooting in Practice
This article presents a framework-independent methodology for observability in coding agents at scale. It explains why built-in, single-session tooling falls short once concurrency and machine count grow, then shows how to reconstruct execution as a structured call chain (Task, Turn, Step, ModelCall, ToolCall). It covers layered latency attribution, token cost allocation, failure classification with reproducible evidence, and a minimal observability loop built on log services, monitoring alerts, and object storage. A deployment checklist is included.
Scaling AI Agents in Production: Latency, Cost, and Failure Troubleshooting in Practice
1. Introduction: What Changes Once You Scale
Coding agents are now part of the daily development workflow for many teams. During the pilot phase, teams care about one thing only: whether the result of a given task is correct. But once call volume, concurrent sessions, and the number of connected machines all rise together, the concerns of the people operating these agents converge on three questions:
- Latency attribution: Where does the time of a single task actually go — model inference, or tool execution (compilation, testing, retrieval, external API calls)?
- Cost attribution: Which sessions, models, and task types concentrate token consumption, and can it be allocated per team or per project?
- Failure replay: At which step did a failure or interruption occur — invalid model output, a tool timeout, or a context overflow? Can the process be fully reconstructed?
These three classes of problems share a defining trait: none of them is a “single-session correctness” problem. They are structured data analysis problems that span sessions, machines, and time windows. The observability that ships with most open-source agent frameworks is scoped to the local machine, a single session, and real time, so it structurally cannot cover scaled deployments. This article is not tied to any specific framework. Instead, it abstracts a general methodology for end-to-end observability of coding agent pipelines, and explains how to implement it with general-purpose capabilities on Baidu AI Cloud (log services, monitoring and alerting, object storage, and related offerings).
2. How Coding Agents Run: Why Observability Is Hard
Designing an observability scheme requires understanding the execution structure of the observed object. The mainstream coding agent frameworks in the industry are architecturally very similar and can be abstracted into three layers:
- Microkernel with full plugin architecture: The kernel only assembles plugins according to a profile and manages their lifecycle; model adapters, tool sets, sandbox policies, and session persistence are all pluggable. The three modes — command line, terminal interaction, and headless batch processing — share the same kernel, and observability hooks into this layer.
- ReAct-style loop: One user task is called a turn, and each round of “reason — call tool — observe result” inside a turn is called a step. The number of loop iterations and which tools get called are decided dynamically by the model at runtime.
- Event-stream driven: Every step emits structured events (user input, model request/response, tool call arguments and returns, errors), appended in chronological order.
This is where the root cause of observability difficulty is buried: the execution structure is not knowable before the run. The same request might complete in 3 steps, or retry across 20 steps. You therefore cannot describe a task with a fixed template; you can only preserve the event stream losslessly first, then reconstruct the call relationships after the fact.
2.1 What Frameworks Typically Provide Out of the Box
Most frameworks ship three capabilities by default: an in-browser session trace view organized by turn (showing tokens and latency for individual records), full local compressed persistence of the event stream (JSONL + zstd, lossless), and full-text tool call search across a session.
2.2 Why Call Relationships Still Need to Be Built on Top
The built-in data has three limitations, which map exactly onto the three pain points of scale:
- Time series only, no call tree: Events are flat, and the parent-child relationships (turn → step → model call / tool call) must be inferred separately, so you cannot directly obtain “time spent per stage” statistics.
- Data lives on the local machine: With many machines, troubleshooting means logging into each one; once a machine is reclaimed or its disk is cleaned, the scene of a failure from a few days ago simply disappears.
- No aggregation, no alerting: You cannot answer “which model was most expensive over the past 7 days” or “which tool type has the highest timeout rate”, nor can you be notified proactively when the failure rate spikes.
3. Overall Approach: Reconstructing Execution as a Structured Call Chain
The target artifact is a searchable, aggregatable call chain data model. It should contain at least the following entities and fields:
Task: task_id, tenant/team, project, profile, start_time, end_time, status└─ Turn: turn_id, user_input_hash, token_in/out, duration└─ Step: step_index, model_name, latency, token_in/out, cache_hit├─ ModelCall: request_id, prompt_tokens, completion_tokens, finish_reason, error_code└─ ToolCall: tool_name, args_digest, result_status, exec_ms, retry_count
Key design principles:
- One execution = one trace, one step = one span, with model calls and tool calls as child nodes of the span. Latency attribution then becomes an aggregation over spans rather than manual log reading.
- Redact sensitive information: Tool arguments and returns keep only a digest and a status, never the raw text, so code and secrets are not written into the trace store.
- Layered sampling and full capture: Keep 100% of failed traces and sample successful traces at a ratio, balancing cost against replayability.
4. Investigating Latency: Layered Attribution, Not Total Duration
Looking only at “total task latency” has no actionable value; it must be broken down by layer:
- Model inference latency = Σ ModelCall.latency, further split into time-to-first-token and overall generation time;
- Tool execution latency = Σ ToolCall.exec_ms, aggregated by tool_name, to quickly find “which command or API is the long-tail culprit”;
- Queueing and scheduling latency = Turn.duration − the sum of the above, used to identify concurrency throttling and sandbox cold starts;
- Retry amplification factor = actual step count / theoretical minimum step count, measuring the time wasted by the model repeatedly trial-and-erroring.
Practical recommendation: set a latency baseline per task type (for example P50/P95 grouped by profile), and trigger an alert when P95 drifts beyond a threshold, instead of waiting for users to complain that things “got slower”.
5. Investigating Cost: Token Ownership and Allocation
The core of cost troubleshooting is allocatability. Implementation points:
- Tag Tasks with business labels (team, project, environment, profile); all tokens are inherited along the trace, enabling aggregation by dimension;
- Distinguish input, output, and cache-hit tokens; output tokens are usually the bulk of the cost, and the cache hit rate is the most direct optimization lever;
- Establish a “cost per task” metric, which reflects efficiency changes better than total consumption;
- Automatically flag anomalous sessions (a single session consuming several times the baseline tokens), commonly caused by repeatedly inflating context or oversized tool returns that were not truncated.
Illustrative aggregation query (pseudo-SQL; exact syntax depends on the chosen log/analytics service):
SELECT team, model_name,SUM(prompt_tokens) AS in_tok,SUM(completion_tokens) AS out_tok,COUNT(DISTINCT task_id) AS tasksFROM agent_traceWHERE dt BETWEEN '2024-05-01' AND '2024-05-07'GROUP BY team, model_nameORDER BY out_tok DESC;
6. Investigating Failures: From Error Codes to Reproducible Scenarios
Failure troubleshooting must distinguish four categories, each bound to different evidence:
| Failure type | Typical signal | Evidence needed |
|---|---|---|
| Invalid model output | Parse failure, tool argument validation failure | Redacted raw response fragment, step index |
| Tool execution failure | Non-zero exit code, timeout, missing dependency | Command digest, exec_ms, retry count |
| Context overflow | Request rejected, history truncated | Token curve, truncation policy marker |
| External dependency error | Rate limiting, 5xx, network jitter | Status code, retry chain |
Since failed traces are kept 100%, the replay path is: alert → pull the full call tree by task_id → locate the first anomalous span → replay with the profile and tool versions from that time. The event stream should also be archived to object storage for long-term retention and low-cost replay.
7. The Observability Loop: Collection, Aggregation, Alerting
The recommended minimal loop:
- Collection: Mount as a native plugin inside the agent kernel, with zero changes to business code, emitting the structured trace described above;
- Transport and storage: Trace data flows into a log service / analytics store, while raw events are archived to object storage;
- Aggregation dashboards: Three core views — layered latency, token allocation, and tool failure rate;
- Alerting: Three threshold rules — failure rate, P95 latency, and cost per task — routed to the on-call channel.
8. Deployment Checklist
- Can you answer within one minute “which layer was the slowest task yesterday slow in”?
- Can you produce last week’s token bill broken down by team?
- Can a failure from three days ago still be reconstructed into a full call tree?
- Are failed traces kept in full and successful traces sampled in a controlled way?
- Is the trace fully redacted, with no risk of leaking code or credentials?
9. Conclusion
Observability at scale is essentially upgrading process data from “local machine, single session, real time” to “cross-session, cross-machine, long-term retained” structured traces. Preserve the event stream losslessly first, then reconstruct the call relationships, and finally drive optimization with three tables: layered latency, token allocation, and failure classification. This methodology is independent of any specific framework and can be applied directly on top of general-purpose capabilities on Baidu AI Cloud, such as log services, monitoring and alerting, and object storage.
