AI Pipeline Observability: Distributed DAG Tracing & Latency Waterfalls for Agent Workflows
Building an end-to-end telemetry system capturing multi-agent reasoning spans, node-level token expenditure, and retrieval drift diagnostics.
Executive Summary
Debugging multi-step AI agents and LangGraph state machines is notoriously difficult when systems fail silently, loop indefinitely, or experience unexplained latency spikes. The AI Pipeline Observability Platform provides real-time distributed tracing specifically designed for LLM execution DAGs. It ingests node-level spans over asynchronous Redis Streams, reconstructs dependency graphs in real time, and renders interactive latency waterfalls with token consumption attribution, cache hit markers, and automated error diagnostics.
The Engineering Challenge & Context
When an AI agent takes 7.4 seconds to generate an answer or produces a malformed output, standard application monitoring tools (APMs) treat the LLM call as an opaque HTTP span. They cannot differentiate between vector database retrieval delay, prompt template construction, iterative tool-call loops, token streaming latency, or post-generation validation failures. Without granular node-level telemetry, engineering teams waste hours attempting to reproduce non-deterministic agent states.
System Architecture & Data Flow
Every node in an agent workflow wraps execution within a lightweight SpanContext. When an operation starts (e.g., Qdrant vector retrieval, OpenAI tool execution, schema validator), the worker generates a span containing traceId, parentSpanId, startTime, nodeType, inputTokens, and outputTokens. Spans are published asynchronously to Redis Streams via non-blocking fire-and-forget commands, adding zero detectable overhead to user requests. A background consumer worker ingests the stream, reconciles parent-child spans into an immutable execution DAG, calculates the critical path latency, and broadcasts updates over WebSockets/SSE to the Next.js telemetry dashboard.
+-----------------------------------------------------------------------------------+
| AI AGENT RUNTIME (LangGraph) |
| |
| [ User Request ] |
| | |
| v |
| [ Node 1: Retrieval ] ---- Span: { traceId, id: 'n1', latency: 420ms } ------+ |
| | | |
| v | |
| [ Node 2: Reasoning ] --- Span: { traceId, parentId: 'n1', latency: 1200ms } -+ |
| | | |
| v | |
| [ Node 3: Tool Call ] --- Span: { traceId, parentId: 'n2', latency: 310ms } --+ |
+-------------------------------------------------------------------------------|---+
| Async XADD
v
+-----------------------------------------------------------------------------------+
| REDIS STREAMS TELEMETRY INGESTION |
| Stream: 'telemetry:agent_spans' (Non-blocking fire-and-forget, <1ms overhead) |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| DAG RECONSTRUCTION & WATERFALL ENGINE |
| |
| 1. Reconstruct Parent-Child Tree via traceId & parentSpanId |
| 2. Calculate Critical Path Duration vs Parallel Branches |
| 3. Compute Per-Node Token Cost & Latency Percentiles (p50, p95, p99) |
| 4. Anomaly Alerting: Detect recursive loops (>4 iterations) or 429 backoffs |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| NEXT.JS OBSERVABILITY DASHBOARD (WEB/SSE) |
| - Interactive Gantt Waterfall Chart |
| - Node Inspection Modal (Prompts, Token Counts, Vector Similarity Scores) |
| - Real-Time Execution Playback |
+-----------------------------------------------------------------------------------+Key Engineering Decisions & Trade-offs
Asynchronous Redis Streams vs. Direct Synchronous Database Writes
Rationale: Synchronous database logging on every intermediate agent node adds 15–40ms of latency per step, compounding to hundreds of milliseconds in a 10-step agent loop. Redis Streams (XADD) completes in under 0.8ms without blocking the critical execution thread.
Trade-offs & Constraints: Telemetry data is eventually consistent by 50–150ms on the dashboard, which is completely acceptable for real-time monitoring.
OpenTelemetry-Aligned Span Hierarchy
Rationale: Structuring spans with standard traceId, spanId, parentSpanId, and semantic attributes ensures immediate compatibility with enterprise APMs (Jaeger, Datadog) while maintaining custom AI-specific metadata like gen_ai.prompt.tokens and gen_ai.completion.tokens.
Trade-offs & Constraints: Requires strict schema validation at the ingestion boundary to prevent malformed spans from breaking DAG tree reconstruction.
Custom Lightweight SVG/DOM Waterfall Visualizer
Rationale: External charting packages (e.g., heavy D3 or Chart.js plugins) add 250–400KB of client JavaScript. Building an SVG-based waterfall component specifically tailored for DAG spans keeps the page bundle lean and interactive.
Trade-offs & Constraints: Requires building custom zooming, panning, and tooltip mechanics in React Vanilla CSS.
Span Context & Execution Telemetry Interface
The span collector exposes a high-order tracing wrapper that intercepts execution, measures start and end timestamps, and captures token consumption attributes.
export interface TelemetrySpan {
traceId: string;
spanId: string;
parentSpanId?: string;
nodeName: string;
nodeType: 'retrieval' | 'llm_generation' | 'tool_execution' | 'validation';
startTimeMs: number;
durationMs: number;
inputTokens?: number;
outputTokens?: number;
status: 'ok' | 'error';
errorMessage?: string;
metadata?: Record<string, unknown>;
}
export async function traceAgentNode<T>(
context: { traceId: string; parentSpanId?: string; nodeName: string; nodeType: TelemetrySpan['nodeType'] },
fn: () => Promise<{ result: T; inputTokens?: number; outputTokens?: number }>
): Promise<T> {
const spanId = 'span_' + Math.random().toString(36).substring(2, 9);
const startTime = Date.now();
try {
const { result, inputTokens, outputTokens } = await fn();
const durationMs = Date.now() - startTime;
await recordSpanAsync({
traceId: context.traceId,
spanId,
parentSpanId: context.parentSpanId,
nodeName: context.nodeName,
nodeType: context.nodeType,
startTimeMs: startTime,
durationMs,
inputTokens,
outputTokens,
status: 'ok',
});
return result;
} catch (error: any) {
await recordSpanAsync({
traceId: context.traceId,
spanId,
parentSpanId: context.parentSpanId,
nodeName: context.nodeName,
nodeType: context.nodeType,
startTimeMs: startTime,
durationMs: Date.now() - startTime,
status: 'error',
errorMessage: error.message,
});
throw error;
}
}Critical Path Calculation Algorithm
To identify whether high latency is driven by parallel branch waits or a single slow node, the engine computes the critical path of the directed acyclic graph.
export function calculateCriticalPath(spans: TelemetrySpan[]): {
totalDurationMs: number;
criticalNodes: string[];
} {
const spanMap = new Map(spans.map((s) => [s.spanId, s]));
const childrenMap = new Map<string, string[]>();
for (const span of spans) {
if (span.parentSpanId) {
const existing = childrenMap.get(span.parentSpanId) || [];
childrenMap.set(span.parentSpanId, [...existing, span.spanId]);
}
}
const roots = spans.filter((s) => !s.parentSpanId);
let maxPathDuration = 0;
let criticalPath: string[] = [];
function dfs(currentId: string, currentDuration: number, path: string[]) {
const span = spanMap.get(currentId);
if (!span) return;
const nextDuration = currentDuration + span.durationMs;
const children = childrenMap.get(currentId) || [];
if (children.length === 0) {
if (nextDuration > maxPathDuration) {
maxPathDuration = nextDuration;
criticalPath = [...path, span.nodeName];
}
return;
}
for (const childId of children) {
dfs(childId, nextDuration, [...path, span.nodeName]);
}
}
for (const root of roots) {
dfs(root.spanId, 0, []);
}
return { totalDurationMs: maxPathDuration, criticalNodes: criticalPath };
}Reliability, Security & Operational Considerations
- •Automatic payload redaction: sensitive prompt text and authorization headers are masked before persistence.
- •Redis Streams capped using MAXLEN ~ 50,000 to prevent unbounded memory growth on high-volume clusters.
- •Non-blocking telemetry: worker execution never stalls or throws exceptions if the telemetry collector drops connections.
- •CORS-restricted WebSocket endpoints requiring valid JWT tokens for real-time dashboard inspection.
Lessons Learned
- ✓Visualizing step-level token consumption immediately uncovers runaway context duplication in multi-turn agent tool loops.
- ✓Critical path analysis distinguishes between parallelized operations (e.g., dual vector searches) and serial bottlenecks.
- ✓Lightweight custom DOM waterfalls deliver significantly faster load times than large monolithic third-party charting suites.
Known Limitations & Future Architecture Roadmap
- →Spans are retained in hot Redis storage for 30 days; an archival pipeline to Parquet files on S3 is planned.
- →Automated alerting integrations with Slack and PagerDuty for SLA degradation are scheduled for the next release.