Debugging Multi-Step LLM Agent Tool Execution at Scale
System DesignModel answerLast updated
Build an observability system to capture, diagnose, and query failures in LLM agent tool calls across retries and execution phases.
Context
Production LLM agents orchestrate sequences of tool executions—database queries, API calls, sandboxed code runs, web searches—to complete user requests. These tools fail often: the model generates malformed arguments, services time out, rate limits trigger, schemas drift, or downstream dependencies return errors. When an agent retries a failed tool or switches strategies across multiple conversation turns, isolating the root cause without comprehensive telemetry becomes nearly impossible.
Your task is to design an observability platform that captures and organizes telemetry for agent tool execution, enabling engineers to debug failures efficiently while operating at high scale.
Requirements
Core Functionality
Structured trace hierarchy: Organize events in a four-level hierarchy where each agent session contains turns, each turn contains tool calls, and each tool call contains one or more execution attempts. Retries must appear as separate child attempts under the same tool call, preserving the full attempt history.
Lifecycle error classification: Tag each failure with its lifecycle phase:
- Argument generation: Model output invalid, schema validation rejected the arguments
- Transport and execution: Network failures, HTTP errors (4xx/5xx), sandbox crashes, timeouts
- Response handling: Parse errors, output truncation, policy violations detected post-execution
Payload capture with safety controls: Store enough context to debug (input arguments, error details, partial responses) while protecting secrets and preventing storage cost explosion from oversized outputs.
Retry metadata: Record the retry strategy used (max attempts, backoff timing), the attempt sequence number, delays applied, and the terminal outcome (succeeded eventually, gave up after budget exhausted, hit unrecoverable error).
Query capabilities: Engineers should be able to filter traces by error type, tool name, session identifier, or latency threshold to investigate patterns.
Scale and Performance Constraints
- Handle 50,000 tool executions per second at peak
- Telemetry overhead must stay under 5ms at P99 for any single tool call
- The system must never block agent progress, even during telemetry pipeline outages
- Keep full debug context for 7 days; retain aggregated error metrics for 90 days
What You Should Address
Schema design: Define the structure of a trace span for a tool execution attempt. Show how context flows between levels and how errors are classified.
System architecture: Describe the components from instrumentation in the agent runtime through collection, processing, and storage. Justify technology choices for the pipeline and query layer.
Data safety: Explain your approach to redacting secrets, handling PII, and managing payload size (inline vs. external storage, truncation strategies).
Sampling strategy: Discuss how you balance capturing all failures for debugging against the cost of storing high-volume success telemetry.
Hints
Hint 1
Think about what absolutely must be on the critical path versus what can happen asynchronously in the background
Hint 2
Consider how context propagation standards like OpenTelemetry handle parent-child relationships across service boundaries
Hint 3
Small metadata can be stored at 100% while large payloads need selective sampling based on outcome
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Scale
Start by translating requirements into concrete numbers to guide design decisions.
At 50k tool calls per second with an average of 1.2 attempts per call (accounting for retries), we're producing roughly 60k attempt records per second. Adding session and turn context brings total span volume to around 120k spans/second.
If each span's metadata averages 1 KB, that's 120 MB/s or about 10 TB/day of raw telemetry. With columnar compression (10x typical for this workload), metadata storage needs about 1 TB/day.
For detailed payloads (arguments, responses, errors), assume 5% of calls fail or retry plus 1% sampled successes—roughly 3,000 calls/second need full context. Capping inline payload at 8 KB means around 25 MB/s or 15 TB over the 7-day retention window.
These numbers drive two key decisions: metadata is cheap enough to capture at 100%, and the 5ms P99 latency budget eliminates any synchronous processing on the agent's critical path.
Data Model
Model this as OpenTelemetry-compatible distributed traces with domain-specific attributes. The hierarchy is: AgentSession → Turn → ToolCall → Attempt.
Each retry creates a new Attempt span as a child of the ToolCall span—retries never mutate the parent. This preserves the complete execution history.
Attempt Span Schema:
trace_id: hash(agent_session_id) // one trace per session
span_id, parent_span_id: UUID // links attempts to tool call
agent_session_id, turn_id, tool_call_id, attempt_id: string
attempt_number: int // 1, 2, 3...
tool_name, tool_version, model_id: string
start_time, duration_ms: timestamp, int
status: enum(OK, ERROR)
error_phase: enum(ARG_GEN, TRANSPORT, EXEC, RESPONSE, NONE)
error_code: enum(
SCHEMA_FAIL, ARG_INVALID, TIMEOUT, HTTP_4XX, HTTP_5XX,
RATE_LIMIT, SANDBOX_CRASH, PARSE_FAIL, TRUNCATED, POLICY_BLOCK
)
http_status: int (if applicable)
is_retryable: bool
retry_config: {max_attempts, backoff_strategy, base_delay_ms}
backoff_applied_ms: int
payload_location: {inline_json | s3_uri, sha256, size_bytes, is_truncated}
redacted_fields: array[{field_path, redaction_type}]
sampling_reason: enum(FAILED, RETRIED, HEAD_SAMPLE, DEBUG_SESSION)
ToolCall Span (parent): Aggregates outcome across attempts:
final_outcome: enum(
SUCCESS_FIRST_TRY, SUCCESS_AFTER_RETRY,
EXHAUSTED_BUDGET, UNRECOVERABLE, CANCELLED
)
total_attempts, total_duration_ms, argument_fingerprint
The argument_fingerprint is a normalized hash of inputs, useful for detecting retry loops with identical arguments.
Context propagates in-process via OpenTelemetry context API and across network boundaries using W3C traceparent headers plus baggage for session/turn/tool identifiers.
Architecture
┌─────────────────────────────────────────┐
│ Agent Runtime (per instance) │
│ ├─ Tool Interceptor (wraps all calls) │
│ │ ├─ pre: validate args │
│ │ ├─ exec: invoke with timeout │
│ │ ├─ post: parse, check policy │
│ │ └─ emit span → lock-free buffer │
│ │ │
│ └─ Background Thread / Sidecar │
│ ├─ redact secrets │
│ ├─ size-check → offload large blobs│
│ └─ batch + compress → send │
└─────────────────────────────────────────┘
▼
┌─────────────────────────────────────────┐
│ Kafka (topics: spans-meta, spans-full) │
│ partition by session_id for ordering │
└─────────────────────────────────────────┘
▼
┌─────────────────────────────────────────┐
│ Stream Processor (Flink / OTel Collector)│
│ ├─ tail-sampling decision per session │
│ ├─ enrich with service metadata │
│ ├─ detect semantic failures, loops │
│ └─ compute real-time aggregates │
└─────────────────────────────────────────┘
▼
┌──────────────────────────┬──────────────┐
│ ClickHouse │ Object Store │
│ - spans (7d full) │ (S3/GCS) │
│ - metadata (90d) │ - payloads │
│ - rollups (90d+) │ (7d TTL) │
└──────────────────────────┴──────────────┘
▼
┌─────────────────────────────────────────┐
│ Query API + Dashboard + Alerts │
└─────────────────────────────────────────┘
Critical path guarantees: The tool interceptor only performs fast operations—timestamping, error classification, enqueuing to a bounded lock-free ring buffer. This takes microseconds. If the buffer is full, the span is dropped and a counter increments; the agent never blocks. The sidecar runs with separate CPU/memory limits so telemetry degradation cannot starve the agent.
Why ClickHouse over Elasticsearch: This workload is write-heavy with analytical queries (filter by error type, aggregate by tool, compute percentiles). Columnar storage with MergeTree tables compresses better and scans faster than inverted indexes. Elasticsearch makes sense only if free-text search over error messages dominates—even then, ClickHouse's token bloom filters handle most search needs. Cost and query performance favor ClickHouse.
Query patterns supported:
- Filter:
WHERE tool_name = 'web_search' AND error_phase = 'EXEC' AND duration_ms > 2000 - Session drill-down: Reconstruct full Turn→ToolCall→Attempt tree with payload links
- Aggregation: Error rates by code, P99 latency by tool, retry distribution
Data Protection
Sanitization runs in the sidecar, off the agent's critical path. It's layered:
-
Schema annotations: Tool definitions mark fields as
secret,pii, orsafe. Secrets are dropped entirely. PII is replaced with keyed HMAC (preserves equality for debugging "same user across attempts" without exposing values). -
Pattern detection: Regex patterns catch unannotated secrets—API keys (common prefixes), JWTs, bearer tokens, emails, phone numbers, credit cards (Luhn-validated). Matches become
<REDACTED:type>. -
Header filtering: Never log
Authorization,Cookie, orX-API-Keyheaders. Use an allowlist for safe headers likeContent-Type,User-Agent. -
Size management:
- Payloads ≤8 KB: stored inline after redaction
- Larger payloads: store head + tail excerpts inline (first/last 2 KB, since errors often appear at boundaries), upload full redacted blob to object storage, set
is_truncated=true - Content-address by SHA256 for deduplication
- Object storage uses encryption at rest with 7-day lifecycle expiration
-
Fail-closed default: If redaction fails, store only metadata, never raw payload.
Access control: metadata dashboards are broadly readable for on-call engineers. Full payload access requires RBAC authorization and generates audit logs.
Sampling Strategy
The approach: dual-path with local tail decisions
-
Metadata: 100% retention. It's small (1 KB per span) and compressed columnar storage makes it cheap. Exact error rates and distributions require complete data.
-
Payloads: outcome-based sampling. The SDK buffers attempt payloads in memory until the ToolCall completes (bounded by tool timeout). Then:
- Any failure or retry: 100% of payloads from all attempts for that tool call
- Clean success: ~1% sampled, plus elevated rates for debug sessions and new tool versions
- Forced capture: Sessions tagged for debugging always capture full context
Why not pure head-based sampling? Deciding at call start misses rare failures—the 0.1% edge case that breaks production.
Why not collector-side tail sampling? Buffering 120k spans/second in the collector requires session affinity (partition by session_id), significant memory, and a timeout window. For high cardinality sessions, this becomes expensive. Our hybrid approach makes the cheap decision (metadata: always keep) globally and the expensive decision (payload: selective) locally where context is fresh.
Trade-off: Slight SDK complexity to buffer payloads until the tool call resolves. Bounded by tool timeout (typically 30-60s), so memory impact is predictable.
Common Mistakes to Avoid
Blocking the agent on telemetry. Synchronous writes or retries on the critical path violate the 5ms budget. Use async buffering and fail-open.
Flat span model. Without hierarchy (ToolCall as parent, Attempts as children), retry context is lost and queries become brittle.
No error lifecycle. Tagging everything as "FAILED" makes debugging impossible. Distinguish argument problems from network issues from response parsing.
Logging secrets. Default to redaction. Require explicit opt-in for sensitive fields, never opt-out.
Over-sampling successes. At 50k calls/second, even 10% sampling of successes creates unnecessary cost. Metadata gives you aggregates; sample payloads only when needed for debugging.
Ignoring backpressure. If Kafka or collectors degrade, the agent must continue. Drop telemetry, increment counters, alert ops—but never block user requests.
Complexity Analysis
- Write throughput: 120k spans/s sustained, 150 MB/s to Kafka
- Storage: ~1 TB/day metadata (compressed), ~15 TB total for 7-day payload retention
- Query latency: Sub-second for filtered scans over hours of data with proper indexing (ORDER BY session_id, tool_name, start_time in ClickHouse)
- Cost: Roughly $0.10/GB/month for ClickHouse vs. $0.25/GB/month for Elasticsearch at this scale