java 41 lines · 7 steps

Correlation IDs in a Spring WebFlux filter

A reactive WebFilter tags every request with a correlation ID and threads it through the Reactor context and logs.

Explained by highlit
1@Component
2public class CorrelationIdWebFilter implements WebFilter, Ordered {
3 
4 public static final String CORRELATION_ID_HEADER = "X-Correlation-Id";
5 private static final String MDC_KEY = "correlationId";
6 private static final String CONTEXT_KEY = "CONTEXT_CORRELATION_ID";
7 
8 @Override
9 public int getOrder() {
10 return Ordered.HIGHEST_PRECEDENCE;
11 }
12 
13 @Override
14 public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
15 String correlationId = resolveCorrelationId(exchange.getRequest());
16 
17 exchange.getResponse().getHeaders().set(CORRELATION_ID_HEADER, correlationId);
18 
19 return chain.filter(exchange)
20 .contextWrite(Context.of(CONTEXT_KEY, correlationId))
21 .doOnEach(signal -> {
22 if (!signal.isOnComplete() && !signal.isOnError() && !signal.isOnNext()) {
23 return;
24 }
25 String id = signal.getContextView().getOrDefault(CONTEXT_KEY, correlationId);
26 try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
27 if (signal.isOnError()) {
28 log.error("Request failed", signal.getThrowable());
29 }
30 }
31 });
32 }
33 
34 private String resolveCorrelationId(ServerHttpRequest request) {
35 String header = request.getHeaders().getFirst(CORRELATION_ID_HEADER);
36 if (header != null && !header.isBlank()) {
37 return header;
38 }
39 return UUID.randomUUID().toString();
40 }
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1In reactive code, thread-local MDC won't survive across operators, so state must ride in the Reactor context instead.
  2. 2Running a filter at highest precedence guarantees the correlation ID exists before any downstream logic executes.
  3. 3Populating MDC only inside a try-with-resources at log time keeps thread-local state scoped and cleaned up correctly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Correlation IDs in a Spring WebFlux filter — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code