AI Infrastructure & Observability8 min readUpdated: 2025-02-15

Distributed Tracing and Latency Waterfalls in Multi-Agent LLM DAGs

How to structure OpenTelemetry-compatible execution spans across recursive agent loops, vector lookups, and token-streaming nodes.

ObservabilityDistributed TracingOpenTelemetryLLM PipelinesRedis StreamsAgents

Core Takeaway

As applications transition from single-turn prompt completions into complex multi-agent LangGraph workflows, debugging moves from inspecting HTTP status codes to tracing directed acyclic graphs (DAGs). When a multi-step agent takes 8.4 seconds or produces unexpected output, engineers need immediate visibility into every intermediate step: vector searches, prompt formatting, tool calling, token streaming, and output validation. This note outlines how to implement distributed tracing for AI pipelines without introducing latency overhead.

Problem Statement & Context

Traditional APM spans treat generative AI calls as monolithic HTTP requests, measuring only total duration and response status. In an autonomous agent, a single user prompt may spawn 4 downstream tool calls, 2 vector retrievals, and 3 reasoning iterations. Without structured span propagation and node-level token accounting, diagnosing why a workflow stalled, looped, or exceeded token budgets requires painful manual reproduction.

Architectural Concepts & Implementation

1. OpenTelemetry-Compatible Span Hierarchies for Agent DAGs

Each step in an agent workflow wraps execution inside a lightweight trace context. Spans carry standardized attributes including traceId, spanId, parentSpanId, nodeType, inputTokens, outputTokens, and modelTier. This preserves hierarchical parent-child relationships across asynchronous message queues and worker threads.

Agent Span Data Interface
export interface AgentSpanContext {
  traceId: string;
  spanId: string;
  parentSpanId?: string;
  workflowId: string;
  nodeName: string;
  nodeType: 'retrieval' | 'llm' | 'tool' | 'guardrail';
  startTimeMs: number;
  durationMs?: number;
  inputTokens?: number;
  outputTokens?: number;
  metadata?: Record<string, unknown>;
}

2. Asynchronous Telemetry Ingestion via Redis Streams

Synchronous database logging on the critical AI execution path introduces 15–40ms of latency per node. By streaming spans asynchronously into Redis Streams (XADD) using fire-and-forget commands, telemetry ingestion overhead is reduced to under 0.8ms per step.

Redis Streams Non-Blocking Span Publisher
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');

export async function publishSpanAsync(span: AgentSpanContext): Promise<void> {
  try {
    await redis.xadd(
      'telemetry:spans',
      'MAXLEN',
      '~',
      '50000',
      '*',
      'traceId', span.traceId,
      'spanId', span.spanId,
      'parentSpanId', span.parentSpanId || '',
      'nodeName', span.nodeName,
      'nodeType', span.nodeType,
      'durationMs', String(span.durationMs || 0),
      'inputTokens', String(span.inputTokens || 0),
      'outputTokens', String(span.outputTokens || 0)
    );
  } catch (err) {
    // Non-blocking: Telemetry failure must never disrupt production user inference
    console.error('Failed to emit telemetry span:', err);
  }
}

3. Critical Path Calculation and Latency Waterfalls

Rendering Gantt-style waterfall charts helps engineers instantly distinguish between parallel operations (e.g., concurrent vector searches) and serial execution bottlenecks. Calculating the longest path through the span tree identifies the critical bottleneck limiting end-to-end user response time.

Common Pitfalls & Trade-offs

  • !Trade-off: Telemetry stream eventual consistency. Dashboard displays lag actual execution by 50–150ms. This is entirely acceptable for monitoring while keeping production inference zero-overhead.
  • !Pitfall: Unbounded memory consumption in Redis. High-throughput pipelines emit millions of spans daily. Always enforce MAXLEN capping on Redis Streams and export historical spans to S3 or BigQuery.
  • !Pitfall: Logging raw customer prompts containing PII or credentials. Implement strict regex masking at the tracer wrapper before serializing span metadata.

Production Verification Checklist

  • Propagate traceId and parentSpanId across all inter-service HTTP requests, queues, and background jobs.
  • Capture inputTokens, outputTokens, modelTier, and cacheHit attributes on every generative span.
  • Use non-blocking fire-and-forget span submission to ensure telemetry collectors never block user inference.
  • Establish automated alerts for agent loops exceeding maximum recursion depth (>5 iterations) or latency thresholds.
  • Mask sensitive PII and authentication tokens before persisting telemetry payloads.
Back to all engineering notes