How to propagate Correlation ID from ThreadLocal to Kafka Headers in a Spring Boot 3 distributed system?

23 hours ago 1
ARTICLE AD BOX

I am implementing an observability layer in a Spring Boot 3.2.0 ecosystem to ensure distributed tracing across multiple microservices.

I have a ContextInterceptor that captures a correlation-id from incoming HTTP requests and stores it in a ThreadLocal via a RequestContext wrapper. This works perfectly for the synchronous flow.

However, I'm struggling with the best practice to propagate this context when sending messages to Apache Kafka asynchronously. I want to ensure the correlation-id is injected into the Kafka Headers without polluting my business logic with infrastructure code.

What is the standard approach to 'wrap' the Kafka Producer to automatically include these headers from the current ThreadLocal context?

public void sendWithContext(String payload) { ProducerRecord<String, String> record = new ProducerRecord<>("topic", payload); String correlationId = MyContextHolder.get(); record.headers().add("correlation-id", correlationId.getBytes()); kafkaTemplate.send(record); }
Read Entire Article