Video in progress
In a WebFlux app, `traceId` sometimes shows up in the logs and sometimes is empty. Why, and how do you fix it in Spring Boot 3?
In Reactor one request runs on several threads, while MDC is a ThreadLocal. The context travels in the Reactor Context and does not land on the logging thread by itself. In Boot 3, Hooks.enableAutomaticContextPropagation() or spring.reactor.context-propagation=auto restores it into the ThreadLocals automatically.
📖 Answer
In a servlet app one request is one thread, so MDC stays in place from start to finish. In WebFlux, the work after a flatMap may continue on a Netty event loop thread, and after publishOn on another scheduler. The tracing context is kept correctly in the Reactor Context, but Logback only looks at the MDC of the current thread. The result: some log lines have a traceId, some don't, and sometimes it is the ID of a different request.
On Boot 3.2 and later the easiest fix is:
spring:
reactor:
context-propagation: auto
This turns on Hooks.enableAutomaticContextPropagation(): at every operator boundary, Micrometer's context-propagation library writes the values from the Reactor Context into the ThreadLocals (tracing, MDC) and then clears them. On older versions you call it by hand in the main method.
For values you add yourself (for example tenantId), put them in the Reactor Context, not in MDC, and register a ThreadLocalAccessor:
return service.load(id)
.contextWrite(Context.of("tenantId", tenantId)); // visible to the operators above
One catch: automatic propagation is not free, since every operator does a bit of extra work. On very hot paths I turn it on and measure the difference with a load test. Also, if blocking code inside Mono.fromCallable is moved to boundedElastic, test separately that propagation works there too.
Sign up to mark studied questions and save your progress.