AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Next.Js Middleware Tracing Emits Duplicate BaseServer.HandleRequest Spans Per Request

Middleware tracing creates a second, disconnected trace instead of inheriting the parent request span, causing duplicate request traces and incorrect observability metrics (e.g., Datadog trace metrics double traffic).

mediumConfidence 75%Next.jsRoute HandlersHydrationApp RouterAffected V16.1.6

Origin Analysis

In Next.js BaseServer, the startSpan method always extracts the parent context from incoming request headers via propagation.extract, ignoring any active OpenTelemetry context. When middleware is invoked in the same process, a second BaseServer.handleRequest span is created as a new root span rather than as a child of the outer request span.
1. Clone reproduction repo and install dependencies. 2. Run `npm run dev`. 3. Start a local OTel collector (e.g., Jaeger via Docker). 4. Send a single request with `curl http://localhost:3000/`. 5. Open Jaeger UI and query the service; observe two entirely separate traces for the single request.

Fixing Code Block

import { context, propagation, trace, SpanOptions } from '@opentelemetry/api' protected startSpan( name: string, options: SpanOptions = {} ) { const activeContext = context.active() const existingSpan = trace.getSpan(activeContext) // If a parent span is already active (e.g., the outer request span), // use it as parent instead of extracting from request headers. const parentContext = existingSpan ? activeContext : propagation.extract(activeContext, this.request?.headers || {}) return tracer.startSpan(name, options, parentContext) }
Modifies the startSpan method in base-server.ts to check for an existing active span. If present (as during middleware invocation within the same request), it uses that span as the parent context, linking the middleware span to the outer request span. Only when no active span exists does it fall back to extracting propagation context from request headers, preserving behaviour for root request spans.

Edge Case Audit

Applying this change globally may inadvertently create parent-child relationships for any nested span started from unrelated code that already has an active context. Ensure the active context is correctly scoped to the incoming request (e.g., via context.with) to avoid cross-request contamination in concurrent handling. Test thoroughly with async operations and different APM providers. Rollback: replace the modified startSpan method with the original implementation that always extracts from headers.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state