Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
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.
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.
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.
- Official documentation
- Spring Framework reference, Core technologies
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/