Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Why does MDC-based logging lose the trace id in a Reactor pipeline, and what does Reactor Context offer instead?

MDC stores values in a ThreadLocal, one copy per thread, but a Reactor pipeline can run its operators on different threads, for example after publishOn or when a WebClient response arrives on a Netty thread, so a log line in a later operator finds an empty or someone else's MDC. Reactor Context is an immutable key-value map attached to the subscription itself; we write it with contextWrite, it flows upstream from the subscriber, and we read it with Mono.deferContextual or transformDeferredContextual. Spring Security uses exactly this to store the security context, through ReactiveSecurityContextHolder.

Why this question is asked

Trace ids in logs are what let us follow one request through a busy service. In Spring MVC they just work, because MDC fills them in on the request thread. Teams moving to WebFlux discover that half their log lines have no trace id, or worse, the trace id of a different request. Interviewers ask this to see whether a candidate understands thread-bound state and the reactive alternative. In this answer, we will recap what MDC is, reproduce the lost trace id, explain why it happens, see how Reactor Context works and which way it flows, and look at how Spring Security uses it.

1A Quick Recap: MDC Is a ThreadLocal

MDC, the Mapped Diagnostic Context in SLF4J and Logback, is a map of values that the logging framework adds to every log line, such as a traceId. Internally it is stored in a ThreadLocal, a variable that has a separate value for each thread. We put a value in at the start of a request and every log call on that thread can read it.

This fits the thread-per-request model perfectly: in Spring MVC one request runs on one thread from start to finish, so the MDC set by a filter is visible in the controller, the service and the repository. The hidden assumption is that the request never changes threads.

2Reproducing the Lost Trace Id

In Reactor that assumption breaks. Here we set the MDC, then the pipeline moves to another thread.

Java
MDC.put("traceId", "abc123");
Mono.just("order-42")
.doOnNext(id -> log.info("loading {}", id)) // [traceId=abc123] loading order-42 (main thread)
.publishOn(Schedulers.parallel())
.doOnNext(id -> log.info("loaded {}", id)) // [traceId=] loaded order-42 (parallel-1 thread)
.block();
Where each operator runs
OperatorThreadMDC traceId
MDC.put and first doOnNextmainabc123
publishOn(parallel)switches threadnot copied
second doOnNextparallel-1empty
after a WebClient callreactor-http-nio-3empty, or another request's

The second log line runs on a parallel scheduler thread whose MDC is empty. The same happens without any publishOn of ours: a WebClient call sends a request and its response arrives on a Netty event-loop thread, so everything after the call runs there. And because event-loop threads serve many requests, a value left in their MDC by one request can appear in another request's log line, which is worse than a missing value.

3Reactor Context: Data Attached to the Subscription

Reactor's answer is to attach the data to the subscription rather than to a thread. Every subscription carries a Context, an immutable key-value map. Immutable means that writing returns a new Context rather than changing the existing one, which makes it safe to share across threads. Because the Context belongs to the chain of subscribers, it is available whichever thread an operator happens to run on.

Java
Mono<String> greeting = Mono.deferContextual(ctx ->
Mono.just("trace=" + ctx.getOrDefault("traceId", "none")))
.publishOn(Schedulers.parallel()) // thread changes do not matter
.contextWrite(Context.of("traceId", "abc123")); // written at the bottom
System.out.println(greeting.block()); // trace=abc123

We write the Context with contextWrite and read it with Mono.deferContextual, which gives us a read-only ContextView when the Mono is subscribed. For a Flux or a reusable piece of a pipeline, transformDeferredContextual((flux, ctx) -> ...) gives access to both the publisher and the context.

4Which Way the Context Flows

There is one rule that surprises everyone the first time: the Context flows upstream, from the subscriber toward the source. When we subscribe, the subscription travels up the chain, and each contextWrite adds its entries for the operators above it. So contextWrite affects what comes before it in the code, not what comes after.

Java
Mono.deferContextual(ctx -> Mono.just(ctx.getOrDefault("k", "missing")))
.contextWrite(Context.of("k", "set below")) // visible to deferContextual above
.block(); // set below
Mono.just("x")
.contextWrite(Context.of("k", "set above"))
.flatMap(v -> Mono.deferContextual(ctx -> Mono.just(ctx.getOrDefault("k", "missing"))))
.block(); // missing: the write is upstream of the read
Step throughSubscription carries the Context upstream
SubscribercontextWritepublishOndeferContextual
subscribe(), empty Context
subscribe(), Context{traceId=abc123}
subscribe(), same Context
onNext(trace=abc123) on parallel-1
onNext passes down

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

Data flows down, the Context flows up with the subscription.

That is why frameworks put contextWrite at the very end of a pipeline, close to the subscriber. In WebFlux the framework subscribes to the Mono our controller returns, and filters can add entries with contextWrite on the chain they return, so the values are visible to everything our controller built.

5How Spring Security Uses It

Spring Security is a good example of the pattern. In MVC it keeps the authenticated user in SecurityContextHolder, a ThreadLocal. In WebFlux it cannot, for the reasons above, so ReactorContextWebFilter writes the security context into the Reactor Context of each request, and ReactiveSecurityContextHolder.getContext() reads it back as a Mono.

Java
@GetMapping("/me")
Mono<String> me() {
return ReactiveSecurityContextHolder.getContext()
.map(ctx -> ctx.getAuthentication().getName()); // "ana", whichever thread runs this
}

For trace ids in logs, we do not have to read the Context by hand in every operator. Micrometer's context-propagation library and Reactor's automatic context propagation can copy Context values back into ThreadLocals such as MDC around each operator. That feature is built on the same Reactor Context we saw here, so understanding contextWrite and its upstream direction is still what explains when a trace id appears and when it does not.

6Follow-up questions

Why not just copy MDC to the new thread in each operator?

We could, with a doOnEach that reads the Context and sets MDC, and older code did exactly this. It is easy to get wrong: values must also be cleared afterwards, or they leak into the next task on that thread. Libraries that do it systematically, like Micrometer's context propagation, are safer than hand-written copies.

Can we modify a value in the Context?

No, the Context is immutable. contextWrite returns a new Context with the entry added or replaced, visible to operators upstream of it. If a value must change during processing, it is usually a sign it should be part of the data flowing through the pipeline instead.

Is Reactor Context the same as the subscriber's state?

It is attached to the subscriber chain, so each subscription has its own Context. Two requests subscribing to the same Mono definition each get their own values, which is exactly what makes it safe for per-request data like trace ids and users.

7Conclusion

In this answer, we saw that MDC loses the trace id in Reactor because it is a ThreadLocal and pipelines change threads, after publishOn, subscribeOn or a WebClient call, so log lines find an empty or a stale MDC. Reactor Context instead attaches an immutable key-value map to the subscription; we write it with contextWrite, which affects the operators upstream of it, and read it with Mono.deferContextual or transformDeferredContextual. Spring Security relies on the same mechanism through ReactiveSecurityContextHolder.

What to say in the interviewAbout 80 seconds aloud

Open with

MDC is backed by a ThreadLocal, so it only works while one request stays on one thread, which is true in Spring MVC but not in Reactor. A reactive pipeline can switch threads between operators, after a publishOn, a subscribeOn, or simply when a WebClient response arrives on a Netty event-loop thread.

Then, if they want more

A log line after that switch reads the MDC of the new thread, which is empty, or even has a value left by a different request, since event loops serve many requests. Reactor Context solves this by attaching data to the subscription instead of the thread.

It is an immutable key-value map; I write to it with contextWrite and read it with Mono.deferContextual, or transformDeferredContextual for a reusable piece of a Flux.

The important detail is direction: the Context travels upstream with the subscription, so contextWrite is visible to operators above it, which is why it goes at the end of the chain, near the subscriber, and why WebFlux filters can add values that the controller's pipeline sees.

Spring Security uses exactly this: in WebFlux the security context lives in the Reactor Context and you read it with ReactiveSecurityContextHolder.getContext. For logging, newer Reactor and Micrometer versions can restore MDC from the Context automatically around operators.

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 "Why does MDC-based logging lose the trace id in a Reactor pipeline, and what does...": https://scrivio-interview-library.netlify.app/spring-boot/webflux/9942c140e3/