Middleware tracing produces duplicate traces requiring careful instrumentation changes
The issue reports that Next.js middleware generates two separate traces per request when it should produce one unified trace. This affects monitoring systems like Datadog by doubling perceived traffic metrics. The fix requires modifying how middleware tracing is handled to properly connect to parent spans.
https://github.com/blairmcalpine/double-trace-repro
docker run --rm -it \
-p 16686:16686 \
-p 4317:4317 \
jaegertracing/jaeger:latest
I expect that for one server request, there is one associated opentelemetry trace. This is however not the case, because middleware tracing emits its own, entirely separate trace that is not at all connected to the base one.
I can see this making sense previously when middleware ran in edge runtimes (so the work was done by an entirely separate machine), but now that we have proxy and the node runtime, it's always going to be handled by the same process. This currently happens because of how we invoke middleware, where we run an entirely new BaseServer.handleRequest span that gets its propagation info from the incoming requests' headers (ie not the propagation info from the already started parent span). Instead, tracing middleware should be tied to the parent GET /[template]/some-route span (that is also BaseServer.handleRequest).
This current behaviour is especially problematic if you want to use datadog for Next.js apps - this is because of datadog's trace metrics, which are computed from every single common trace emitted by a service. Because these two traces are both BaseServer.handleRequest, this means datadog things they are two separate requests. This means 2x the perceived traffic for a service, as well as incorrect averages for latency, etc.
To work around thi
Claim this issue to let others know you're working on it. You'll earn 20 points when you complete it!