Agent Observability at Scale: Diagnosing Latency, Token Cost, and Failures

    As agents move from demos into daily engineering, teams need structured, aggregable, and searchable trace data across batches of tasks, time windows, machines, and long retention periods. This article presents a unified execution model, latency and token-cost attribution methods, failure classification, a collection architecture, practical metrics, common pitfalls, and a phased rollout plan for large-scale agent observability.

    When agents move from demos into daily development work, whether a single run produces the right result is only the minimum requirement. At scale, teams need to answer three engineering questions: Where does time actually go—model inference, tool execution, queue waiting, or retries? Where are tokens consumed—which sessions, model calls, and steps? Where do failures and interruptions occur in the chain, and can the scene still be reconstructed days later? Local, single-session, real-time trace views solve the problem of “this one run in front of me.” For batches of tasks, time ranges, cross-machine deployments, and long-term retention, teams must add structured, aggregable, and searchable trace data.

    Three Typical Blind Spots at Scale

    The first blind spot is unclear performance attribution. An increase in total task latency may come from longer model inputs, more output turns, slower tool calls, concurrent queue congestion, timeout retries, or context compression. If only task start and end times are recorded, the result is wall-clock duration, but it is impossible to tell which segment is on the critical path. With parallel tool calls in particular, sub-step durations cannot simply be summed; the call tree must be reconstructed and exclusive durations calculated.

    The second blind spot is unclear cost attribution. Total token count is an outcome, not an explanation. A task may repeatedly carry historical context at every step, and large tool results may be fed back into later inference. Failed retries generate new model calls. Tasks of the same type may produce completely different context lengths because they choose different tools. Only by splitting tokens by session, task, step, model, and retry can teams determine whether cost growth is “normal business growth” or “context inflation, looped calls, and repeated inference.”

    The third blind spot is that failures cannot be traced back. Failures may occur in model planning, protocol parsing, tool authorization, sandbox execution, external dependencies, budget limits, or cancellation operations. Recording only an error code makes it impossible to determine the last successful step, which retries were triggered, or which plugin version and tool argument digest were in use. Retrospectability requires saving configuration, versions, input/output digests, error types, retry chains, and key timestamps together, with support for retrieval by session or task.

    Traditional local session views usually cover a single machine, a single session, and real-time observation, which is suitable for development debugging. Scale troubleshooting requires cross-session, cross-machine, long-retention structured trace data. The two are not replacements for each other; they are capabilities at different granularities that should be combined.

    Define a Unified Data Model Before Instrumentation

    The most common mistake in observability programs is to connect logs first and add fields later, ending up with a pile of text that cannot be correlated. Define a unified execution model first, then instrument around that model.

    • Session: A container for one continuous interaction or a group of related tasks, used to connect user intent, artifacts, and follow-up questions.
    • Task: A user goal that can be independently judged as successful or failed. This is the primary granularity for latency and cost statistics.
    • Turn: A reasoning–action–observation loop inside a task.
    • Step: A model call, tool call, result observation, or control action within a turn.
    • Model call: Records model identifier, input/output tokens, latency, retries, status, context digest, and similar fields.
    • Tool call: Records tool name, argument digest, result size, latency, status, timeouts, retries, and similar fields.
    • Artifacts and events: File changes, command output digests, error events, cancellation events, budget alerts, and similar items.

    Every trace must have stable correlation fields: trace_id, span_id, parent_span_id, session_id, task_id, step_no, span_type, start and end times, duration, status, retry count, error type, host or instance identifier, plugin version, and configuration digest. Model calls additionally record token counts. Tool calls additionally record tool category, argument digest, and result size.

    A simplified event structure can look like this:

    1. {
    2. "trace_id": "task-7f2c...",
    3. "session_id": "session-19a...",
    4. "task_id": "task-7f2c...",
    5. "span_id": "step-3-tool-1",
    6. "parent_span_id": "step-3",
    7. "span_type": "tool_call",
    8. "step_no": 3,
    9. "start_time": "2025-01-01T10:00:00.120Z",
    10. "duration_ms": 1840,
    11. "status": "error",
    12. "retry_count": 1,
    13. "attributes": {
    14. "tool_category": "file_search",
    15. "arg_digest": "sha256:...",
    16. "result_bytes": 12034,
    17. "error_class": "timeout"
    18. }
    19. }

    Two principles must hold during collection: traces must not break, and sensitive information must not be stored raw. At the trace level, all sub-steps must inherit parent context, and trace_id and parent_span_id must be passed across processes or threads. At the security level, large tool results and user inputs should not be indiscriminately persisted. Store length, digest, hash, and controlled raw text enabled on demand, and prevent secrets, personal information, or business data from entering the observability system.

    Latency Diagnosis: Drill Down from Total Time to the Critical Path

    Total latency optimization cannot rely on averages alone. Observe at least P50, P95, and P99, grouped by task type, model, tool, instance, and plugin version. During troubleshooting, first determine which category the latency belongs to:

    1. High model inference share: Check input tokens, output tokens, number of turns, context compression strategy, retries, and rate limiting. If input keeps growing, first investigate whether historical messages and tool results are being repeatedly injected.
    2. High tool execution share: Check P95, timeout rate, and retry rate for specific tool operations. Common causes include oversized search scope, external service jitter, long command execution time, oversized results, and too many serial tool calls.
    3. High queue and wait share: Check concurrency quotas, lock contention, task queues, rate limits, and backoff strategies. This type of latency is often hidden before the model call starts; without a separate wait span, it will be misattributed to model latency.
    4. High retry and backoff share: Retries should be recorded as an independent attribute or step. Otherwise, the average latency of successful calls will be inflated, and failure costs will be underestimated.
    5. Collection overhead: Oversized log payloads, synchronous disk writes, and frequent remote reporting can slow execution. Collection should use asynchronous batching, ring buffers, and backpressure protection.

    A diagnostic query can aggregate percentile latency and retry rate by step type:

    1. SELECT span_type,
    2. percentile(duration_ms, 0.50) AS p50,
    3. percentile(duration_ms, 0.95) AS p95,
    4. avg(CASE WHEN retry_count > 0 THEN 1.0 ELSE 0.0 END) AS retry_rate,
    5. avg(duration_ms) AS avg_ms
    6. FROM trace_spans
    7. WHERE start_time >= :start_time
    8. AND start_time < :end_time
    9. GROUP BY span_type;

    The next step is to find the critical path within a single trace. The correct method is to reconstruct the call tree based on parent_span_id, calculate the exclusive duration of each step, and then identify the longest branch from the root node to a leaf. With parallel tool calls, total duration is determined by the slowest critical branch, not by the sum of all sub-steps. Reports should also distinguish wall-clock duration from CPU and wait durations, so that time spent waiting for external responses is not mistaken for computation overhead.

    Cost Analysis: Token Attribution Must Be Multi-Dimensional

    Total token count cannot directly guide optimization. Establish attribution dimensions such as session, task type, model, step number, tool category, user or team, instance and version, whether a retry occurred, and whether a cache hit occurred if the model interface provides that information. Core metrics include:

    • Average tokens per successful task;
    • P95 tokens per task;
    • Average tokens and context length per step;
    • Additional tokens generated by retries;
    • Context growth rate after tool results are fed back;
    • Cost weight per unit of successful output.

    Cost increases commonly fall into four patterns: context inflation turn by turn; oversized tool results that are not trimmed; failed retries that re-run full inference; and changes in model selection or turn strategy that cause more multi-step calls. Analysis should avoid asking only “which model is expensive” and instead ask “which type of task repeatedly consumes tokens at which step.” For example, if tokens rise for a task type but the model unit price has not changed, the cause may be that a tool returned full content instead of a summary. If the single-run cost of a task type is not high but its failure rate has risen, total cost will be amplified by retries.

    Cost alerts should be based on baselines and percentiles, not a single absolute threshold. Set budgets by team or task type, and trigger alerts for conditions such as “a single task exceeds the historical P99 token count,” “tool result size grows abnormally,” or “retry cost share spikes.” For high-cost traces, retain the full call tree. For regular traces, sampling can be used, but sampling must be applied to the entire trace, not just intermediate steps; otherwise the critical path cannot be reconstructed.

    Failure Diagnosis: Split “Failure” into Diagnosable Categories

    The first step in failure troubleshooting is not to read the error message, but to classify the failure. At minimum, distinguish:

    • Model and scheduling: Rate limiting, timeouts, context limit exceeded, truncated output, content validation failure.
    • Protocol and parsing: Unknown tool name, invalid arguments, structured output parsing failure, argument type mismatch.
    • Tool and environment: Insufficient permissions, unreachable network, sandbox restrictions, abnormal command exit code, oversized result.
    • Orchestration and budget: Step limit exceeded, looped calls, task cancellation, budget exhaustion, manual interruption.
    • Collection and platform: Buffer overflow, upload failure, sampling misjudgment, missing fields.

    Every failure event should be associated with error type, error code, redacted error summary, last successful step, retry count, current turn, input digest, configuration version, plugin version, and container or host identifier. For external dependency failures, also record timeout configuration and dependency availability metrics. For reentrant operations, use idempotency keys to avoid side effects during replay; when replaying, prefer recorded argument digests, tool result digests, and a simulated environment rather than unconditionally re-executing real write operations.

    Troubleshooting can follow a four-step method: first narrow the scope by time, task type, model, and instance; then check whether failure rates and error categories are concentrated; next drill into a specific trace and inspect the critical path and last successful step along the timeline; finally correlate version changes, configuration changes, capacity changes, and dependency alerts to determine whether the issue is intermittent, a regression, or systemic.

    Collection Architecture: Plugin Instrumentation, Buffering, Governance, and Tiered Storage

    A scale-ready design can be divided into six layers:

    1. Collection layer: Mount plugins or SDKs into the execution kernel and instrument the start and end of tasks, model calls, tool calls, errors, and retries. Cover command-line, interactive interface, and unattended entry points.
    2. Buffer layer: Use bounded queues for asynchronous batch sending on the local machine to avoid blocking the main workflow. When queues are full, prioritize retaining failed, slow, and high-cost traces.
    3. Governance layer: Perform field validation, sensitive-information redaction, sampling, quotas, and routing. Sampling should use a trace-consistent strategy. By default, sample a small fraction; force retention for failures, timeouts, high-cost traces, and manually flagged traces.
    4. Storage layer: Use a trace index for parent-child retrieval, time-series metrics for aggregation and alerting, object storage for long-term retention of redacted payloads, and a log warehouse for event investigation.
    5. Analysis layer: Provide trace search, aggregation analysis, dashboards, alerts, and root-cause assistance views.
    6. Operations layer: Set retention periods, access permissions, audit records, data quality checks, and cost budgets.

    Pay special attention to backpressure and data integrity. The collection side should expose drop counters, upload success rate, and latency metrics. The analysis side should detect quality issues such as missing parent-child relationships, empty token fields, and inverted timestamps. Otherwise, the observability system itself will become a new source of failure.

    Practical Metrics and Daily Troubleshooting Workflow

    Start with a small set of high-value metrics: task completion rate, interruption rate, P95 latency, model latency share, tool latency share, average step count, retry rate, tokens per successful task, Top N error categories, and Top N slow tools. Split dashboards by task type, model, tool, and version, and avoid mixing all metrics into one global view.

    Daily troubleshooting can follow a fixed workflow:

    • Performance issues: Check percentile curves first, then find the critical path, and finally determine whether the cause is model, tool, waiting, or retries.
    • Cost issues: Attribute cost by session and task first, then inspect step-level tokens and retry cost, and finally compare recent changes in configuration and tool result size.
    • Failure issues: Check the error category distribution first, then drill into a single trace to confirm the last successful step and environment snapshot, and finally validate hypotheses through controlled replay or comparison with successful traces.
    • Regression issues: Associate versions and configuration digests with traces, and compare P95 latency, error rate, and cost per successful unit before and after changes.

    Common Pitfalls and Governance Recommendations

    1. Recording only final results: Without intermediate steps, failures cannot be located. Record tasks, turns, model calls, tool calls, and error events.
    2. Inconsistent IDs: Multi-process, multi-threaded, and asynchronous tools easily break traces. Generate a root trace at the entry point, and have all sub-calls inherit context.
    3. Unreliable timestamps: Clock skew across machines causes timeline confusion. Correct clocks and also record durations calculated from monotonic clocks.
    4. Token statistics that omit retries: Counting only successful calls underestimates cost. Retries should be an independent dimension.
    5. Storing large payloads raw: Tool outputs and user inputs may contain sensitive information. Prefer storing digests, lengths, and hashes, and collect raw text on demand under controls.
    6. Incorrect sampling granularity: Sampling only some steps makes traces impossible to reconstruct. Sample by task or session, and force retention for anomalous traces.
    7. Abusing high-cardinality labels: Do not use raw inputs, file paths, or full argument sets as aggregation labels. Use hashes, categories, and controlled dimensions.
    8. Ignoring collection overhead: Synchronous reporting slows tasks. Use asynchronous batching, rate limiting, and backpressure, and establish metrics for the observability pipeline itself.

    Phased Rollout Roadmap

    Phase 1 completes “correlatable”: unify IDs, define core steps, and record status, tokens, tool categories, and error classifications. Phase 2 completes “queryable”: build trace search, aggregation by task and session, and performance and cost dashboards. Phase 3 completes “retrospectable”: add forced sampling for anomalies, redaction, configuration snapshots, long-term retention, and controlled replay. Phase 4 completes “governable”: set budgets and percentile alerts, and establish version regression comparison, slow-tool governance, and a high-cost task optimization loop.

    The goal of large-scale agent observability is not to pile up logs, but to turn an unpredictable execution process into queryable, aggregable, and retrospectable engineering assets. Only when latency, cost, and failures all land on the same structured call chain can teams move from guessing by experience to locating with data, and continuously improve the efficiency, cost, and reliability of agent systems.