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 @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 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.