Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service uses virtual threads, CompletableFuture pipelines and Reactor in different places. How do you make sure the security context and tracing context reach every piece of work?

The security context and the tracing context are both ThreadLocal values, and a ThreadLocal never crosses to another thread or task by itself, so every place where work moves needs explicit propagation. Executors and CompletableFuture get wrapped executors or task decorators that capture the context at submit time and restore it in the task; virtual threads are still threads with their own ThreadLocals, so they need the same wrapping; and Reactor carries values in its own Context, bridged with ReactiveSecurityContextHolder and Micrometer context propagation. Then we test that each kind of work sees the expected user and trace.

Why this question is asked

A service that mixes virtual threads, CompletableFuture chains and Reactor calls has at least three different ways of moving work between threads, and each one drops the security context and the trace id in its own way. The symptoms are confusing: authorization checks that fail only in the async branch, audit records with no user, and traces that break into pieces. Interviewers ask this to see whether we can name the one underlying rule and apply it consistently. In this answer, we will recap the rule, then handle executors and CompletableFuture, virtual threads and Reactor in turn, and finish with how to test that it all works.

1A Quick Recap: Contexts Live on Threads

Spring Security stores the current user in SecurityContextHolder, and Micrometer stores the current observation (and through it the trace and span ids) in its own ThreadLocal. The logging MDC, the map of values printed with each log line, is a ThreadLocal too. A ThreadLocal is a variable with a separate value per thread.

So the rule is simple: whenever work is handed from one thread to another, whoever hands it over must capture the values and whoever runs it must restore them, and clear them afterwards. There is no magic inheritance. Each mechanism in our service needs a hook where we can do the capture and restore.

Where propagation is needed and what does it
MechanismWhy the context is lostWhat propagates it
@Async and thread poolsPool threads were created earlierDelegatingSecurityContextExecutor or a TaskDecorator
CompletableFuture.*AsyncRuns on commonPool by defaultPass a wrapped executor to every async stage
Virtual threadsEach one is a new thread with empty ThreadLocalsWrap the virtual-thread executor the same way
Reactor (Mono, Flux)Operators hop between scheduler threadsReactor Context plus context propagation
One rule, four hooks: capture at hand-over, restore while running, clear afterwards.

2Executors and CompletableFuture

For thread pools, Spring Security gives us DelegatingSecurityContextExecutor and DelegatingSecurityContextExecutorService, which wrap each task so that the caller's SecurityContext is set while it runs. For the other ThreadLocals, Micrometer's context-propagation library offers ContextExecutorService.wrap(), which captures a ContextSnapshot of every registered ThreadLocalAccessor, including the current observation, and restores it in the task.

CompletableFuture needs special care because its async methods silently use ForkJoinPool.commonPool() when no executor is given. Every supplyAsync, thenApplyAsync and runAsync must receive our wrapped executor.

Java
ExecutorService pool = Executors.newFixedThreadPool(16);
// ContextExecutorService comes from io.micrometer:context-propagation; check your version for the wrap() overloads
ExecutorService propagating = ContextExecutorService.wrap( // observation and other registered ThreadLocals
new DelegatingSecurityContextExecutorService(pool)); // security context
CompletableFuture<Report> f = CompletableFuture
.supplyAsync(() -> loadOrders(), propagating) // user=alice, traceId=4bf9
.thenApplyAsync(orders -> summarise(orders), propagating); // user=alice, traceId=4bf9
CompletableFuture.supplyAsync(() -> loadOrders()); // user=null, no traceId: commonPool

Notice that the last line, with no executor, loses everything. A good habit is a code review rule or an ArchUnit test that forbids the async methods without an executor argument. In Spring Boot, a TaskDecorator bean is applied to the auto-configured executor, so a decorator that composes both wrappers covers every @Async method in one place.

3Virtual Threads Are Still Threads

Virtual threads, final since Java 21, are cheap threads scheduled by the JDK on a small set of carrier threads. They make blocking code scale, but they do not change ThreadLocal semantics: each virtual thread has its own ThreadLocal values, and a new virtual thread starts with none of the caller's values. Since we usually create one virtual thread per task, every task starts empty.

So we wrap the virtual-thread executor exactly as we wrap a pool. With spring.threads.virtual.enabled=true, Boot switches its auto-configured task executor to virtual threads, and a TaskDecorator bean is still applied, so the same decorator keeps working. Because virtual threads are not reused, the stale-context risk of pools is smaller, but the capture and restore are still needed. Java 25 also finalised ScopedValue, a safer alternative to ThreadLocal for passing values down a call tree, but Spring Security still uses ThreadLocal-based holders, so check your version before relying on it.

Java
ExecutorService virtual = ContextExecutorService.wrap(
new DelegatingSecurityContextExecutorService(Executors.newVirtualThreadPerTaskExecutor()));
virtual.submit(() -> log.info("user={}", currentUser())); // user=alice
Thread.ofVirtual().start(() -> log.info("user={}", currentUser())); // user=null: started by hand, not wrapped

4Reactor Uses Its Own Context

Reactor is different. A single Mono or Flux pipeline can run its operators on several threads, switching whenever a publishOn or a non-blocking I/O callback happens, so a ThreadLocal set at the start means nothing a few operators later. Reactor therefore carries request-scoped values in its own Context, an immutable map attached to the subscription that travels with the pipeline.

Spring Security uses that Context for reactive code: ReactiveSecurityContextHolder.getContext() reads the SecurityContext from the Reactor Context, and in WebFlux the security filters put it there. For ThreadLocal-based code that runs inside a pipeline, such as logging with MDC or a library that reads SecurityContextHolder, Micrometer context propagation bridges the two worlds. With Hooks.enableAutomaticContextPropagation(), or in Boot spring.reactor.context-propagation=auto, Reactor restores registered ThreadLocal values from the Context around each operator.

Java
Mono<String> name = ReactiveSecurityContextHolder.getContext()
.map(ctx -> ctx.getAuthentication().getName()); // alice, read from the Reactor Context
webClient.get().uri("/stock").retrieve().bodyToMono(Stock.class)
.doOnNext(s -> log.info("stock for {}", MDC.get("userId"))); // alice only with automatic propagation
Step throughChoosing the propagation hook
  1. Does the work run in a Mono or Flux?
    YesUse the Reactor Context and automatic propagationNoContinue
  2. Is it submitted to an executor or CompletableFuture?
    YesWrap the executor: security and context snapshotNoContinue
  3. Is it a thread started by hand?
    YesReplace with a wrapped executorNoSame thread: nothing to do

3 steps in order. Play them, or step through them one at a time.

Every branch ends in capture at hand-over and restore while running.

Notice that the two worlds need a bridge in both directions. In a servlet application that calls WebClient, Spring Security can copy the servlet context into the Reactor Context for the client's filters, and for the ThreadLocal side we register a ThreadLocalAccessor for each value we need. Recent Spring Security versions ship an accessor for the security context; check your version, and register one yourself if it is missing.

5Testing That the Context Arrives

Propagation code is easy to break silently, so we test it the way it fails: run work on each mechanism and assert what it sees. @WithMockUser sets the user only on the test thread, which makes it a perfect probe.

Java
@Test
@WithMockUser("alice")
void everyAsyncPathSeesTheUser() throws Exception {
assertThat(service.viaAsync().get()).isEqualTo("alice"); // @Async
assertThat(service.viaCompletableFuture().get()).isEqualTo("alice"); // wrapped executor
assertThat(service.viaVirtualThread().get()).isEqualTo("alice"); // virtual thread executor
StepVerifier.create(service.viaReactor()).expectNext("alice").verifyComplete();
}

We add the same checks for the trace id, for example by asserting that a test observation registry sees one trace with all spans, and we run the pool test twice with different users to catch stale contexts left on reused threads.

6Follow-up questions

Why not set MODE_INHERITABLETHREADLOCAL and skip all of this?

It only copies at thread creation. Pools reuse threads, so a thread keeps the user of the request that created it, and later tasks run as the wrong person. It also does nothing for Reactor, whose operators run on scheduler threads created long before the request.

Does Micrometer context propagation also handle the security context?

Only if a ThreadLocalAccessor for it is registered. The library propagates whatever accessors are registered; Micrometer Tracing registers the observation, and recent Spring Security versions provide an accessor for SecurityContextHolder. Without one, we keep the DelegatingSecurityContext wrappers.

What about the MDC?

MDC is a ThreadLocal map, so it has the same problem. Micrometer Tracing copies trace and span ids into the MDC from the current observation, so they follow automatically once the observation propagates. Our own MDC keys, such as a user id, need their own accessor or a decorator that copies the MDC map.

7Conclusion

In this answer, we saw that the security context, the current observation and the MDC are all ThreadLocal values, so none of them crosses a thread boundary by itself. Executors, @Async and CompletableFuture need wrapped executors or task decorators, with an executor passed to every async stage. Virtual threads are still threads with empty ThreadLocals, so their executor is wrapped the same way. Reactor carries values in its own Context, read through ReactiveSecurityContextHolder and bridged to ThreadLocals by Micrometer context propagation. Finally, tests running each mechanism under @WithMockUser prove the user and the trace arrive.

What to say in the interviewAbout 90 seconds aloud

Open with

I start from one rule: the security context, the observation that carries the trace, and the MDC are all ThreadLocals, and a ThreadLocal never moves to another thread on its own.

Then, if they want more

So every place where work changes thread needs a hook that captures the values at hand-over, restores them while the task runs, and clears them afterwards. For executors and @Async, I wrap the executor with DelegatingSecurityContextExecutorService for the user and Micrometer's ContextExecutorService for the observation, or in Boot I register one TaskDecorator that does both.

For CompletableFuture, the trap is that the async methods default to the common pool, so every async stage must get the wrapped executor, and I'd enforce that with a review or ArchUnit rule.

Virtual threads don't change anything: each one is a new thread with empty ThreadLocals, so I wrap the virtual-thread executor the same way, and Boot's decorator still applies when virtual threads are enabled. Reactor is the odd one out, because a pipeline hops between threads, so values live in the Reactor Context.

Reactive code reads the user from ReactiveSecurityContextHolder, and for ThreadLocal-based code I turn on automatic context propagation so registered accessors are restored around operators. Finally I write tests with @WithMockUser that run work through each path and assert the user and trace id, including twice with different users to catch stale pool threads.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 25
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 Security reference
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 "A service uses virtual threads, CompletableFuture pipelines and Reactor in different...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/5c76628c40/