Video in progress
For a message sent through Kafka, how does the trace continue from the producer to the consumer?
The producer instrumentation writes the trace context into the Kafka record headers (traceparent), and the consumer reads it and opens its own span. In Spring Kafka you enable observationEnabled for this; for a batch consumer, span links are a better fit than a parent.
📖 Answer
It works like HTTP, except the headers travel in the Kafka record itself. With Spring Boot 3 and Micrometer Tracing:
spring:
kafka:
template:
observation-enabled: true
listener:
observation-enabled: true
After that, KafkaTemplate.send opens a producer span and puts traceparent in the header, and @KafkaListener opens its consumer span as a child of that context. If you use the OpenTelemetry Java agent, this works without any configuration.
Subtle points:
- Time gap: a message can sit in the topic for 10 minutes. In the trace you see a large gap between the producer span and the consumer span. That is not a bug; it shows the consumer lag.
- Batch listener: if you get 500 messages in one poll, they come from 500 different traces, and a single span can't have 500 parents. OpenTelemetry offers span links for this case: the consumer span starts in a new trace and keeps a link to the context of each message.
- Retry and DLT: when a message goes to a dead-letter topic, the headers must be copied over, otherwise you can't tie the message in the DLT back to the original request.
When debugging, the first thing I do is check whether the record headers contain traceparent, using kafka-console-consumer --property print.headers=true.
Sign up to mark studied questions and save your progress.