Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

Your service puts a trace id and user id into SLF4J MDC, which is ThreadLocal-based. After moving work to @Async methods and CompletableFuture chains, logs from background work lack the ids or show wrong ones. Explain and fix, including why InheritableThreadLocal does not solve it.

MDC values live in a ThreadLocal of the thread that set them, so tasks running on @Async or CompletableFuture pool threads see nothing, or see values left behind by an earlier task on that thread. InheritableThreadLocal does not help, because it copies values only when a thread is created, and pool threads are created once, long before our request, so they keep whatever their creator had. The fix is to capture the context when the task is submitted and restore it around the task, for example with a Spring TaskDecorator on ThreadPoolTaskExecutor, or with Micrometer's context-propagation library and tracing integrations, and always to clear the restored values afterwards.

Why this question is asked

Logs without trace ids are almost useless during an incident, and logs with the wrong trace id are worse, because they send us chasing the wrong request. This problem appears the day a team moves work to background threads, and the first idea people try, InheritableThreadLocal, seems to work in a quick test and fails in production. Interviewers ask it to see whether we understand how context is attached to threads and how pools reuse them. In this answer, we will recap how MDC stores its values, reproduce the missing and wrong ids, explain why InheritableThreadLocal fails, and then fix it with a TaskDecorator and with Micrometer context propagation.

1A Quick Recap of MDC

MDC, the mapped diagnostic context in SLF4J, is a map of key-value pairs that the logging framework adds to every log line, for example traceId and userId. With Logback, the MDC is stored per thread, in a ThreadLocal. MDC.put("traceId", "abc") puts the value into the current thread's map, and every later log statement on the same thread can print it with a pattern such as %X{traceId}.

So the MDC belongs to a thread, not to a request. As long as the whole request runs on one thread, the two are the same. Once work moves to other threads, they separate.

2Reproducing the Missing and Wrong Ids

A filter puts the trace id into the MDC on the Tomcat request thread. The controller then calls an @Async method and a CompletableFuture chain.

Java
MDC.put("traceId", "t-1001"); // request thread http-nio-8080-exec-3
log.info("received order"); // traceId=t-1001
reportService.generateAsync(order); // @Async, runs on task-2
CompletableFuture.supplyAsync(() -> price(order), pricingPool)
.thenAccept(p -> log.info("priced {}", p)); // runs on pricing-1
// task-2: "generating report" traceId= (empty: nothing was set on this thread)
// pricing-1: "priced 42.50" traceId=t-0977 (left over from an earlier task on this thread)

Notice the two different failures. task-2 never had an MDC value, so its log lines have none. pricing-1 once ran a task that set or restored an id and did not clear it, so it now prints an id that belongs to another request. The wrong id is the more dangerous of the two.

3Why InheritableThreadLocal Does Not Solve It

InheritableThreadLocal is a ThreadLocal whose values are copied from the parent thread to a child thread at the moment the child thread is created. That sounds like what we need, and in a quick test with new Thread() it works. But pools do not create a thread per task. A ThreadPoolTaskExecutor creates its threads once, the first time they are needed, from whatever thread happened to trigger the creation, and then reuses them for thousands of tasks.

So a pool thread inherits the MDC of the request that happened to cause its creation, perhaps the first request after startup, and keeps that copy forever. Every later task on it prints that first request's trace id unless something overwrites it. InheritableThreadLocal turns missing ids into wrong ids. Logback also stopped making its MDC inheritable years ago (around version 1.1.5) for this reason.

Step throughCopy at creation versus capture at submission
Request A threadPool threadRequest B thread
first task: pool creates thread, inherits traceId A
logs traceId A (correct by luck)
later task from request B
logs traceId A (wrong: inherited copy kept)
with a TaskDecorator: capture B, restore B
logs traceId B, then clears MDC

6 messages in order. Play them, or step through them one at a time.

Inheritance copies once per thread; propagation must happen once per task.

4Fix 1: Capture and Restore With a TaskDecorator

The correct model is to copy the context once per task: capture it on the submitting thread when the task is submitted, set it on the worker thread when the task starts, and clear it when the task ends. Spring's ThreadPoolTaskExecutor accepts a TaskDecorator, which wraps every Runnable it is given, so we can do this in one place.

Java
class MdcTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable task) {
Map<String, String> captured = MDC.getCopyOfContextMap(); // on the submitting thread
return () -> {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (captured != null) MDC.setContextMap(captured); else MDC.clear();
try {
task.run(); // on the pool thread
} finally {
if (previous != null) MDC.setContextMap(previous); else MDC.clear(); // never leak
}
};
}
}
@Bean
ThreadPoolTaskExecutor applicationTaskExecutor() {
ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
ex.setTaskDecorator(new MdcTaskDecorator());
ex.setThreadNamePrefix("async-");
return ex;
}

The finally block is what prevents the wrong-id failure: after each task, the pool thread goes back to what it had before, normally nothing. Spring Boot applies a TaskDecorator bean to its auto-configured executor, so @Async methods get the decorator automatically. CompletableFuture chains only benefit when they use that executor, so we pass it explicitly instead of letting them use the common pool.

5Fix 2: Micrometer Context Propagation and Tracing

Writing decorators for each kind of context (MDC, security, tenant, locale) does not scale. Micrometer's context-propagation library generalises the idea: each kind of context registers a ThreadLocalAccessor, and the library can capture a snapshot of all of them and restore it on another thread. It bridges ThreadLocals with Reactor's Context too, which matters for reactive code. Spring Framework provides a ContextPropagatingTaskDecorator built on it, and Micrometer Tracing puts the trace and span ids into the MDC and keeps them correct across instrumented executors (check your versions for the exact classes and properties).

Java
@Bean
TaskDecorator contextPropagatingTaskDecorator() {
return new ContextPropagatingTaskDecorator(); // captures every registered ThreadLocal context
}
// Or wrap any ExecutorService, including ones used by CompletableFuture
ExecutorService pricingPool = ContextExecutorService.wrap(Executors.newFixedThreadPool(8));

So for trace ids specifically, using Micrometer Tracing or OpenTelemetry instrumentation is usually the least effort, and the decorator approach covers our own custom keys such as userId.

6Follow-up questions

Why restore the previous MDC instead of just clearing it?

Usually the previous map is empty, so the two are the same. But if the task runs on the caller's thread, for example when CallerRunsPolicy rejects into the submitting thread, clearing would erase the caller's own context. Restoring what was there is correct in both cases.

Does this work with virtual threads?

Yes, but with one new virtual thread per task, there is no stale value left from earlier tasks, so the wrong-id failure goes away while the missing-id failure stays. Context still has to be captured and restored at submission. Scoped values give a cleaner model for new code, while MDC itself remains ThreadLocal-based.

How do we test that propagation works?

Submit a task that logs from inside an @Async method with a known trace id, capture log output with a test appender, and assert the id appears. Then run a second task with no id on the same single-threaded executor and assert the id does not appear, which proves clearing.

7Conclusion

In this answer, we saw that MDC stores values per thread, so pool threads used by @Async and CompletableFuture either have no ids or keep ids from earlier tasks. InheritableThreadLocal copies values only when a thread is created, so pool threads keep the context of whoever created them, which makes the ids wrong rather than missing. We fixed it by capturing the context at submission and restoring it around each task with a TaskDecorator, or with Micrometer context propagation and tracing, always clearing the restored values afterwards.

What to say in the interviewAbout 90 seconds aloud

Open with

MDC in Logback is stored in a ThreadLocal, so the trace id and user id belong to the request thread that set them. When work moves to an @Async method or a CompletableFuture stage, it runs on a pool thread with its own MDC.

Then, if they want more

If nothing was ever set there, the logs have no ids. If an earlier task left values behind, the logs show another request's ids, which is worse. InheritableThreadLocal looks like the answer, but it copies values only when a thread is created.

Pool threads are created once and reused, so each one keeps the context of whatever request happened to create it, and every later task prints that id. That's why Logback stopped making MDC inheritable.

The right model is to propagate per task: capture the context on the submitting thread and restore it on the worker for the duration of the task.

In Spring I'd do that with a TaskDecorator on ThreadPoolTaskExecutor that takes MDC.getCopyOfContextMap at submit time, sets it before running the task, and in a finally restores the previous map or clears it, so nothing leaks into the next task. Spring Boot applies a TaskDecorator bean to its async executor, and I'd pass that executor to CompletableFuture explicitly.

For a broader solution, Micrometer context propagation captures all registered ThreadLocal contexts, bridges to Reactor, and Micrometer Tracing keeps trace ids in the MDC across instrumented executors.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your service puts a trace id and user id into SLF4J MDC, which is ThreadLocal-based....": https://scrivio-interview-library.netlify.app/java/threads/82a29d2545/