Scrivio Interview library
CodingIntermediate5 min read · updated 12 November 2026

An @Async method needs the caller's MDC trace id and security context. Show how you would carry them across the thread hop.

MDC and the SecurityContext live in ThreadLocals, so they stay on the caller thread when @Async moves work to a pool thread. We fix this with a TaskDecorator on the executor: it captures MDC.getCopyOfContextMap() and the SecurityContext when the task is submitted, restores them on the pool thread around run(), and clears them in a finally block. Boot applies a TaskDecorator bean to its auto-configured executor, Spring Security offers DelegatingSecurityContextAsyncTaskExecutor for the security part, and Micrometer's context propagation library can carry tracing context automatically.

Why this question is asked

Logs without a trace id and an async job that suddenly runs as anonymous are two sides of the same problem: context that was attached to a thread did not travel with the work. Interviewers ask for code here because the fix has a few details that are easy to get wrong, especially cleaning up, and getting them wrong leaks one user's identity into another user's task. In this answer, we will recap why the context is lost, reproduce it, write a TaskDecorator that carries MDC and security, register it with Boot, and look at the library options for security and tracing.

1Why the Context Is Lost on the Thread Hop

MDC, the Mapped Diagnostic Context of SLF4J and Logback, is a small map of values such as traceId that the logging pattern prints on every line. Spring Security's SecurityContextHolder holds the authenticated user. By default both store their data in a ThreadLocal, a variable that has a separate value for each thread.

@Async runs our method on a thread from a pool. That thread has its own ThreadLocals, which are empty or, worse, still hold values from a previous task. So the method logs without a trace id and sees no authenticated user.

Java
// on the request thread: MDC traceId=4bf92f35, user=alice
reportService.build(id); // @Async
// inside build(), on task-1:
log.info("building"); // [traceId=] building
SecurityContextHolder.getContext().getAuthentication(); // null

2Writing a TaskDecorator

A TaskDecorator is a Spring interface with one method, decorate(Runnable). The executor calls it on the submitting thread, before the task is queued, and runs whatever Runnable we return on the pool thread. That gives us exactly two moments: capture on the caller, restore on the worker.

Java
public class ContextCopyingDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable task) {
Map<String, String> mdc = MDC.getCopyOfContextMap(); // captured on the caller thread
SecurityContext security = SecurityContextHolder.getContext(); // captured on the caller thread
return () -> {
Map<String, String> previous = MDC.getCopyOfContextMap(); // normally null on a clean worker
if (mdc != null) MDC.setContextMap(mdc); else MDC.clear();
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(security.getAuthentication());
SecurityContextHolder.setContext(ctx);
try {
task.run(); // [traceId=4bf92f35] building, user=alice
} finally {
SecurityContextHolder.clearContext(); // nothing leaks into the next task
if (previous != null) MDC.setContextMap(previous); else MDC.clear();
}
};
}
}
Step throughCapture on submit, restore around run
Request threadDecoratorPool thread
submit task: copy MDC and SecurityContext
queued decorated Runnable
set MDC and SecurityContext
run @Async method body
finally: clear both

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

Notice three details. We take a copy of the MDC map, because the caller will keep changing its own map after submitting. We put the authentication into a new SecurityContext instead of sharing the caller's object, so a change on one thread cannot affect the other. And the finally block always clears, because pool threads are reused: without it, the next task on task-1 would run with alice's identity and trace id.

Restoring the previous values rather than only clearing also makes the decorator safe when the executor runs a task on the caller thread itself, for example under CallerRunsPolicy.

3Registering It With Spring Boot

Boot builds its auto-configured ThreadPoolTaskExecutor, the one @Async uses by default, with a builder that picks up a TaskDecorator bean from the context. So declaring the bean is enough.

Java
@Configuration
@EnableAsync
class AsyncConfig {
@Bean
TaskDecorator contextCopyingDecorator() {
return new ContextCopyingDecorator(); // applied to applicationTaskExecutor by Boot
}
}
// For our own executor bean we set it explicitly:
@Bean
ThreadPoolTaskExecutor reportExecutor() {
ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(4);
ex.setQueueCapacity(200);
ex.setTaskDecorator(new ContextCopyingDecorator());
return ex; // initialised by Spring as a bean
}

If several decorators are needed, Spring Framework 6.1 added CompositeTaskDecorator, and recent Boot versions compose several TaskDecorator beans; check your version before relying on more than one bean.

4Library Options for Security and Tracing

For the security part alone, Spring Security already provides wrappers. DelegatingSecurityContextAsyncTaskExecutor wraps an executor so that every task runs with the SecurityContext that was current when it was submitted, and clears it afterwards. It is a good choice when we do not want to maintain our own code, though it handles only security, not MDC.

For tracing, Micrometer's context-propagation library is the general answer. Micrometer Tracing stores the current span in ThreadLocals and registers accessors with the library, so a ContextSnapshot can capture all registered ThreadLocals at once and restore them elsewhere. Spring Framework 6.1 ships ContextPropagatingTaskDecorator, which does exactly that. With Micrometer Tracing on the classpath, the trace id in the MDC is set from the current span, so propagating the span also fixes the logs.

Java
@Bean
TaskDecorator tracingDecorator() {
return new ContextPropagatingTaskDecorator(); // captures every registered ThreadLocal accessor
}
// Security only, wrapping an existing executor:
@Bean
AsyncTaskExecutor securedExecutor(ThreadPoolTaskExecutor reportExecutor) {
return new DelegatingSecurityContextAsyncTaskExecutor(reportExecutor);
}

Whichever option we pick, we should not switch SecurityContextHolder to MODE_INHERITABLETHREADLOCAL as a shortcut. Inheritable ThreadLocals copy values only when a thread is created, and pool threads are created once and reused, so tasks would see whichever user happened to be active when the thread was born.

5Follow-up questions

Does this work with virtual threads?

Yes. With spring.threads.virtual.enabled=true Boot uses a SimpleAsyncTaskExecutor on virtual threads, which also applies the TaskDecorator. Virtual threads still have their own ThreadLocals, so the context must still be copied; each task starts with an empty context, which removes the leak risk but not the need to propagate.

How would you test the decorator?

Write a test that puts a value in MDC and an authentication in SecurityContextHolder, calls an @Async method that records MDC.get("traceId") and the user name, waits on its CompletableFuture, and asserts both values. Then submit a second task with an empty context and assert it sees nothing, which proves the cleanup.

Why capture in decorate() rather than inside the Runnable?

decorate() runs on the submitting thread, which is the only moment the caller's ThreadLocals are visible. Code inside the returned Runnable runs later on the pool thread, where reading MDC would only return the worker's own values.

6Conclusion

In this answer, we saw that MDC and the SecurityContext stay behind because they are ThreadLocals. A TaskDecorator captures them on submit, restores them around run, and clears them in finally; Boot applies a TaskDecorator bean to its executor; DelegatingSecurityContextAsyncTaskExecutor covers security alone; and ContextPropagatingTaskDecorator with Micrometer's library propagates tracing.

What to say in the interviewAbout 80 seconds aloud

Open with

Both the MDC and the SecurityContext are stored in ThreadLocals, so when @Async hands work to a pool thread, they stay behind and the task logs without a trace id and runs as anonymous.

Then, if they want more

I fix it at the executor with a TaskDecorator. Its decorate method runs on the submitting thread, so there I take MDC.getCopyOfContextMap() and the current authentication.

It returns a Runnable that, on the pool thread, calls MDC.setContextMap with the copy and sets a new SecurityContext holding that authentication, runs the task, and in a finally block clears the security context and restores or clears the MDC.

The finally matters most, because pool threads are reused and otherwise the next task would run with the previous user's identity. In Boot I just declare the decorator as a bean, and Boot applies it to the auto-configured applicationTaskExecutor; for my own executors I call setTaskDecorator. If I only need security, Spring Security's DelegatingSecurityContextAsyncTaskExecutor does the copy for me.

For tracing I prefer Micrometer's context-propagation library through Spring's ContextPropagatingTaskDecorator, which captures every registered ThreadLocal, including the current span, so the trace id follows automatically. I would not use an inheritable ThreadLocal mode, because pool threads are created once and reused.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
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 "An @Async method needs the caller's MDC trace id and security context. Show how you...": https://scrivio-interview-library.netlify.app/spring-boot/spring-utilities/ad7c195e8b/