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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1In reactive code, thread-local MDC won't survive across operators, so state must ride in the Reactor context instead.
- 2Running a filter at highest precedence guarantees the correlation ID exists before any downstream logic executes.
- 3Populating MDC only inside a try-with-resources at log time keeps thread-local state scoped and cleaned up correctly.
Related explainers
java
@Component public class OrderRecoveryHandler { private final RabbitTemplate rabbitTemplate;
Dead-letter recovery with Spring AMQP
dead-letter-queue
retry
exponential-backoff
Advanced
9 steps
java
public final class DeepCopier { private static final ObjectMapper MAPPER = new ObjectMapper() .registerModule(new JavaTimeModule())
Deep-copying objects via Jackson serialization
serialization
deep-copy
generics
Intermediate
7 steps
java
package com.example.time; import java.time.Duration; import java.time.Instant;
Adding ISO-8601 durations across time zones in Java
date-time
iso-8601
parsing
Intermediate
7 steps
java
@Component public class InventoryReconciliationJob { private static final Logger log = LoggerFactory.getLogger(InventoryReconciliationJob.class);
Distributed scheduled jobs with Spring locks
distributed-locking
scheduling
concurrency
Advanced
8 steps
java
import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern;
Ranking the most frequent words in Java
streams
regex
grouping
Intermediate
7 steps
java
public final class HttpHeaders { private final NavigableMap<String, List<String>> values = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
A case-insensitive HTTP headers map in Java
case-insensitivity
multimap
immutability
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/correlation-ids-in-a-spring-webflux-filter-explained-java-3afa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.