Video in progress

Senior 🌱 Spring

The traceId and userId in the log disappear inside @Async methods and CompletableFuture. Why, and how do you fix it?

MDC and SecurityContext are stored in a ThreadLocal, and a new thread doesn't inherit them. You add a TaskDecorator to the executor and copy the context yourself, or wire in Micrometer context-propagation.

📖 Answer

SLF4J's MDC, SecurityContextHolder (the default strategy), Micrometer's current span: all of them are a ThreadLocal. An @Async method runs on another pool thread, where these values are empty (or, worse, stale values left over from the previous task).

Fix: a TaskDecorator:

class ContextCopyingDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable task) {
        Map<String, String> mdc = MDC.getCopyOfContextMap();
        SecurityContext sec = SecurityContextHolder.getContext();
        return () -> {
            Map<String, String> old = MDC.getCopyOfContextMap();
            try {
                if (mdc != null) MDC.setContextMap(mdc);
                SecurityContextHolder.setContext(sec);
                task.run();
            } finally {
                if (old != null) MDC.setContextMap(old); else MDC.clear();
                SecurityContextHolder.clearContext();
            }
        };
    }
}

In Boot 3, if there is a bean of type TaskDecorator, the auto-configured applicationTaskExecutor picks it up on its own. The cleanup in finally is mandatory: pool threads are reused, and work could end up running in another user's context.

Other ways:

  • With Micrometer Tracing, ContextSnapshotFactory / ContextPropagatingTaskDecorator copy the observability context (trace, baggage) correctly; in Boot, spans are written to the MDC automatically.
  • Spring Security has DelegatingSecurityContextExecutor.
  • If you don't pass an executor to CompletableFuture.supplyAsync(...), it runs on ForkJoinPool.commonPool(), and the decorator doesn't reach it. Always pass your own decorated executor.

Checking is easy: in one test, put a value in the MDC and assert it from inside the @Async method.