Video in progress
In an @Async method or a CompletableFuture, the traceId and MDC values disappear from the logs. What is the cause and how do you fix it?
The MDC and the tracing context live in a ThreadLocal, while the task runs on another thread in a pool, and the context doesn't pass on its own. The executor needs a TaskDecorator that copies the context over, or Micrometer context-propagation.
📖 Answer
The sign is familiar: the controller logs have a traceId, but the logs in the @Async method have an empty one. In the trace UI the asynchronous work also shows up as a separate, "orphan" trace.
Starting with Spring Framework 6.1 / Boot 3.2 there is a ready solution:
@Configuration
public class AsyncConfig {
@Bean
public TaskDecorator contextPropagatingTaskDecorator() {
// copies MDC, tracing and other ThreadLocals to the new thread
return new ContextPropagatingTaskDecorator();
}
}
Boot's auto-configured ThreadPoolTaskExecutor picks up a TaskDecorator bean by itself. If you create the executor yourself, don't forget executor.setTaskDecorator(...).
In older versions, or for the MDC only, a hand-written decorator:
public Runnable decorate(Runnable task) {
Map<String, String> ctx = MDC.getCopyOfContextMap();
return () -> {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (ctx != null) MDC.setContextMap(ctx); else MDC.clear();
try {
task.run();
} finally {
if (previous != null) MDC.setContextMap(previous); else MDC.clear();
}
};
}
If you don't pass an executor, CompletableFuture.supplyAsync(...) runs on ForkJoinPool.commonPool(), which the decorator never reaches. Always pass your own executor with the decorator, or wrap the task with a ContextSnapshot.
In Reactor the problem is different: threads change between operators. In Boot 3 it is solved with Hooks.enableAutomaticContextPropagation() (or spring.reactor.context-propagation=auto).
With virtual threads, a ThreadLocal also starts empty for every new thread, so this rule applies to them too.
Sign up to mark studied questions and save your progress.