Video in progress

How do you correctly propagate MDC, the trace ID and the security context through CompletableFuture and thread pools?

These contexts live in ThreadLocal and don't cross to another thread on their own. The fix is a wrapper that captures the context when the task is submitted, restores it when it runs, and cleans up at the end: TaskDecorator in Spring, ContextSnapshot/context-propagation in Micrometer, Context.wrap in OpenTelemetry.

📖 Answer

The symptom is familiar: the async part shows up in the log without a trace ID, or SecurityContextHolder.getContext() is empty in an @Async method. Even worse, a pool thread shows the MDC of a previous request, and log lines get tied to the wrong user.

The basic pattern is capture/restore:

public final class ContextAwareExecutor implements Executor {
    private final Executor delegate;
    public ContextAwareExecutor(Executor delegate) { this.delegate = delegate; }

    @Override
    public void execute(Runnable task) {
        Map<String, String> mdc = MDC.getCopyOfContextMap();   // at submit time
        SecurityContext sec = SecurityContextHolder.getContext();
        delegate.execute(() -> {
            Map<String, String> previous = MDC.getCopyOfContextMap();
            try {
                if (mdc != null) MDC.setContextMap(mdc); else MDC.clear();
                SecurityContextHolder.setContext(sec);
                task.run();
            } finally {
                if (previous != null) MDC.setContextMap(previous); else MDC.clear();
                SecurityContextHolder.clearContext();
            }
        });
    }
}

Then use supplyAsync(fn, contextAwareExecutor) everywhere. Async calls without an executor go to commonPool and lose the context. It helps to forbid those with an ArchUnit rule or static analysis.

Ready-made tools:

  • Spring: ThreadPoolTaskExecutor.setTaskDecorator(...); in Spring Security, DelegatingSecurityContextExecutor;
  • Micrometer Tracing plus the context-propagation library: ContextExecutorService.wrap(...) passes along all registered ThreadLocalAccessors together, and the same mechanism works with Reactor;
  • the OpenTelemetry Java agent instruments many executors automatically.

The architecture-level decision: register the context types in one place and create all executors through a single factory. If every team writes its own wrapper, sooner or later cleanup gets forgotten in some pool. With virtual threads and JDK 25+, ScopedValue closes this problem structurally for new code.