Observability for AI Agents at Scale: Solving Tracing, Latency, Cost, and Failure Replay
This article explains how to close the observability gap that appears when AI agents move from local, single-session debugging to large-scale production operations. It defines a three-layer tracing model (trace, span, attributes and events), then shows how to use span-level data for latency analysis based on percentiles and critical path, cost attribution down to individual spans, and precise replay of failures from days earlier. It also outlines a lightweight architecture for collection, transport, storage, and alerting, along with a phased rollout plan and common pitfalls to avoid. Local real-time views and structured cross-session traces are complementary, and together they mark the boundary between a demo and a production agent system.
1. The Starting Problem: A Single-Machine Real-Time View Cannot Support Scaled Operations
Take an open-source agent framework as an example. It usually ships with a session trace view, persisted session event streams, and tool-call retrieval, all scoped to three dimensions: the local machine, a single session, and real time. These capabilities are genuinely useful during development and self-testing: a developer can replay a session frame by frame and inspect the inputs and outputs of a specific tool call.
But once the workload grows from “a few dozen runs a day” to “a few hundred thousand runs a day,” the nature of the problem changes. The questions a team needs to answer are no longer “why was this one run slow,” but rather:
- What are the overall success rate and latency distribution across a batch of tasks, and where is the long tail?
- What does the cost distribution look like over a period, and which stage or task category is consuming the budget?
- Can a failure from several days ago be reproduced precisely, including the context and tool outputs at that time?
All three questions point to the same gap: there is no structured trace data that spans sessions and machines and can be retained long term. This article discusses how to fill that layer, not how to replace the existing local debugging view.
2. Define the Tracing Model First: Without Unified Semantics, Everything Afterward Is Invalid Data
The first step toward scale is not choosing storage. It is agreeing on what a trace actually is. A three-layer semantic model commonly used in the industry is a good starting point:
- Trace: a complete, user-perceivable task, such as “generate a weekly report and send it.”
- Span: a unit of work within the trace, such as one model inference, one tool call, one retrieval, or one code execution.
- Attributes and events: structured key-value pairs and timestamped events attached to a span, used to carry latency attribution, cost, and failure details.
An illustrative data structure (pseudocode that expresses semantics only and is not bound to any specific interface):
span = {"trace_id": "t-8f21", # unique across the whole trace"span_id": "s-03","parent_id": "s-01","name": "tool.search_docs","kind": "TOOL", # MODEL / TOOL / RETRIEVAL / EXEC"start_ms": 1730000000123,"end_ms": 1730000001987,"status": "ERROR","attrs": {"model.tier": "large","prompt_tokens": 1820,"completion_tokens": 460,"tool.retry": 2,"tenant.id": "team-a"},"events": [{"ts": 1730000001500, "name": "timeout", "detail": "upstream 3s"}]}
There are three key constraints. The trace_id must be generated at the entry point and propagated to every downstream call. Every span must carry a type, otherwise it cannot be classified and aggregated later. Token counts and retry counts must be recorded as attributes, otherwise cost analysis is guesswork.
3. Latency Investigation: Move from Averages to Percentiles and the Critical Path
At scale, average latency is almost meaningless. What matters is P50/P95/P99 and the critical path.
A suggested investigation sequence:
- Break down latency share by span type. In practice, model inference and tool calls usually dominate, while orchestration and queueing are underestimated.
- Compute critical path latency, not the sum of all span durations. Parallel tool calls make summation significantly overstate real latency.
- Separate queueing time from execution time. If queueing dominates, the problem lies in concurrency and quotas, not in the code.
- Drill into long-tail sessions individually, comparing P99 and P50 sessions across context length, tool retry counts, and number of retrieval hits.
-- Example: find the span types that contribute most to the critical pathSELECT span.kind,approx_percentile(span.duration_ms, 0.95) AS p95FROM spansWHERE trace_date = '2026-08-20'GROUP BY span.kindORDER BY p95 DESC;
One easily overlooked point: tool retries are latency amplifiers. Recording the retry count as a first-class attribute often explains most of the long tail in one pass.
4. Cost Investigation: Break the Bill Down to Span Granularity
The root cause of untraceable cost is usually not a lack of accounting, but accounting at too coarse a granularity. A practical approach is to split cost into additive atomic items:
- Input and output token counts, accumulated separately per model tier;
- Number of retrievals and tool calls;
- Repeated consumption caused by retries;
- Extra overhead from intermediate steps such as embedding and reranking.
With span-level attributes, cost allocation becomes a single aggregation query: summarize by tenant, by task type, by model tier, and by time window to locate anomalous sessions where a single task consumes the budget. On the engineering side, budget guardrails are also needed: a per-session token cap, a per-tenant daily quota, and automatic downgrade to a smaller model tier when limits are exceeded. These are general governance measures; specific thresholds should be determined by each team through load testing against its own workload rather than copied from others.
5. Failure Investigation: Make a Failure from Days Ago Precisely Reproducible
Reproducing a failure requires three things to hold at the same time: the input can be restored, the context can be restored, and the external responses can be restored.
- Input and context: snapshot the session message sequence, the system prompt version, and the retrieved fragments together, and tag the configuration version.
- External responses: persist tool and retrieval results in a structured form, with masking and access control in place, so sensitive data is not dumped into logs verbatim.
- Environment identifiers: record runtime version, concurrency configuration, and quota state, because many failures occur only under specific concurrency conditions.
The replay process should be a fixed routine: pull the snapshot by trace_id, replay it in an isolated environment, compare the status and latency of each span, and determine whether the cause is the prompt, the tool, or capacity. If the replay result differs from production, suspect drift in the state of external dependencies first, rather than the model itself.
6. Connecting the Data: Collection, Transport, Storage, and Query
A reference architecture can stay lightweight:
- Collection: instrument the framework at session and tool-call boundaries, and keep the local debugging view as the “single-machine real-time” entry point.
- Transport: use a message queue to absorb peaks, so collection does not back-pressure the main request path during traffic spikes.
- Storage: send detailed spans to a logging service or object storage, and aggregated metrics to a time-series database, forming hot/cold tiering and long-term retention.
- Query and alerting: set thresholds on success rate, P95 latency, and cost per task in the monitoring and alerting system, and attach a list of trace_ids to anomalies so you can jump directly from an alert to the trace.
Instrumentation must follow three principles: low intrusion, switchable, and failure must not affect the main flow. A collection failure must never take down a business session.
7. Rollout Plan and Common Pitfalls
A three-step rollout is recommended: first unify trace semantics and entry-point propagation; then add cost and failure snapshots; finally build aggregated dashboards and a closed alerting loop. Common pitfalls include recording only averages and not percentiles; aggregating cost only at the session level; spans without types, which makes classification impossible; an inappropriate sampling rate that discards the long tail; and the compliance risk of persisting sensitive raw text in full.
If a team already uses Baidu AI Cloud or a similar cloud platform, the capabilities above can map directly onto general categories such as logging service, message queue, object storage, and monitoring and alerting, without building the entire infrastructure stack in-house.
8. Conclusion
Observability at scale is not about buying a dashboard. It is about first defining four things clearly: trace semantics, latency attribution, cost atomic items, and failure snapshots. The local real-time view solves “seeing one run”; structured trace data solves “inspecting a batch, measuring a period accurately, and replaying one failure.” The two are complementary, and together they mark the dividing line between an agent moving from demo to production.
