Propagate a correlation id across HTTP calls, async work and Kafka. Compare manual logging, a filter with MDC, and Micrometer Tracing.
Problem
A request enters the API gateway, calls two services and publishes a Kafka event. Every log line along the way must share one id so support can trace a customer complaint end to end.
Approach 1: Pass an id manually to every log statement (feasible, error-prone)
Every method signature grows a requestId parameter and developers forget it in half the code paths. Do not do this.
Approach 2: A servlet filter + MDC + propagation helpers
The filter reads or creates the id, puts it in the SLF4J MDC (so a logging pattern like %X{correlationId} prints it on every line), returns it to the client, and cleans up. Interceptors copy it to outgoing HTTP requests; a TaskDecorator copies the MDC to @Async threads.
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskDecorator;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorrelationIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Correlation-Id";
static final String MDC_KEY = "correlationId";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String id = request.getHeader(HEADER);
if (id == null || id.isBlank() || id.length() > 64) id = UUID.randomUUID().toString(); // never trust unbounded input
MDC.put(MDC_KEY, id);
response.setHeader(HEADER, id);
try {
chain.doFilter(request, response);
} finally {
MDC.remove(MDC_KEY); // threads are pooled: always clean up
}
}
}
@Configuration
class CorrelationPropagationConfig {
@Bean
ClientHttpRequestInterceptor correlationIdInterceptor() {
return (request, body, execution) -> {
String id = MDC.get(CorrelationIdFilter.MDC_KEY);
if (id != null) request.getHeaders().set(CorrelationIdFilter.HEADER, id);
return execution.execute(request, body);
};
}
@Bean
TaskDecorator mdcTaskDecorator() { // apply to the @Async executor
return task -> {
Map<String, String> context = MDC.getCopyOfContextMap();
return () -> {
if (context != null) MDC.setContextMap(context);
try { task.run(); } finally { MDC.clear(); }
};
};
}
}For Kafka, add the id as a record header in the producer and restore it in the listener:
import java.nio.charset.StandardCharsets;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.MDC;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
@Component
class CorrelatedKafka {
private final KafkaTemplate<String, String> kafka;
CorrelatedKafka(KafkaTemplate<String, String> kafka) { this.kafka = kafka; }
void send(String topic, String key, String payload) {
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, payload);
String id = MDC.get(CorrelationIdFilter.MDC_KEY);
if (id != null) record.headers().add(CorrelationIdFilter.HEADER, id.getBytes(StandardCharsets.UTF_8));
kafka.send(record);
}
@KafkaListener(topics = "order-events", groupId = "notifications")
public void listen(@Payload String payload,
@org.springframework.messaging.handler.annotation.Header(name = CorrelationIdFilter.HEADER, required = false) byte[] correlationId) {
if (correlationId != null) MDC.put(CorrelationIdFilter.MDC_KEY, new String(correlationId, StandardCharsets.UTF_8));
try {
// handle payload; every log line now carries the original id
} finally {
MDC.remove(CorrelationIdFilter.MDC_KEY);
}
}
}Approach 3: Micrometer Tracing / OpenTelemetry (optimal)
Spring Boot 3 instruments incoming requests, RestClient/WebClient, Kafka and @Async through the Observation API. It propagates the W3C traceparent header, puts traceId and spanId into the MDC, and exports spans to Zipkin, Jaeger or Tempo, giving you correlated logs and timing for each hop. Add micrometer-tracing-bridge-otel plus an exporter, then enable observation where Spring does not do it by default:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.support.ContextPropagatingTaskDecorator;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
@Configuration
class TracingConfig {
@Bean
KafkaTemplate<String, String> tracedKafkaTemplate(ProducerFactory<String, String> producerFactory) {
KafkaTemplate<String, String> template = new KafkaTemplate<>(producerFactory);
template.setObservationEnabled(true); // adds traceparent to record headers
return template;
}
@Bean
ConcurrentKafkaListenerContainerFactory<String, String> tracedListenerFactory(ConsumerFactory<String, String> consumerFactory) {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
factory.getContainerProperties().setObservationEnabled(true); // continues the trace in the consumer
return factory;
}
@Bean
ContextPropagatingTaskDecorator contextPropagatingTaskDecorator() {
return new ContextPropagatingTaskDecorator(); // trace + MDC across @Async threads
}
}With logging.pattern.correlation=[${spring.application.name:},%X{traceId:-},%X{spanId:-}] (Boot 3.2+ adds it by default when tracing is present) every log line carries the trace id.
Feasible → optimal
Manual ids are fragile; a filter + MDC + interceptors works without extra infrastructure; Micrometer Tracing gives standard propagation, automatic instrumentation of clients and messaging, and latency per hop. Many teams use tracing ids as the correlation id and still echo a request id header to clients.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related: why must the MDC be cleared in a finally block?
MDC is backed by a ThreadLocal. Servlet containers and executors reuse threads, so a value left behind leaks into the next, unrelated request, producing misleading logs. Always remove what you set (or restore the previous value) in finally.
Related: how do you correlate logs in a reactive WebFlux service?
There is no fixed thread per request, so ThreadLocal MDC does not work directly. Use Micrometer's context propagation with Reactor (Hooks.enableAutomaticContextPropagation() in Reactor 3.5.3+), which restores trace context and MDC around operators, or store the id in the Reactor Context and read it explicitly.