The most common gap in distributed tracing looks like this: one trace ends at producer.send(), and a second, unrelated trace starts in a consumer a few milliseconds or a few hours later. HTTP and gRPC instrumentation carry context automatically because the request itself carries it. A message queue breaks that. The producer and the consumer never talk to each other, and the only thing they share is the message. OpenTelemetry context propagation across a queue therefore means writing the trace context into the message and reading it back out on the other side.
This post covers how that works for Kafka, RabbitMQ and Amazon SQS: the header that carries the context, the propagation API for doing it by hand, the span kinds the messaging semantic conventions define, when a consumer span should be a child and when it should link, and the failures that quietly break the chain.
What travels in the message
With the default propagators (OTEL_PROPAGATORS=tracecontext,baggage), the context is a W3C traceparent value with four dash-separated fields: a version, the 16-byte trace ID, the 8-byte ID of the span that sent the message, and trace flags, where 01 means sampled.
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
An optional tracestate carries vendor-specific data, and a baggage header appears if your code sets baggage. Each transport has its own place for these values:
- Kafka: record headers, whose values are byte arrays. Headers arrived in Kafka 0.11, so producers, brokers and consumers all need to use the newer record format.
- RabbitMQ: the
headerstable in the AMQP 0-9-1 basic properties of each message. - SQS: no headers at all. Context goes either into message attributes, with a limit of ten per message, or into the
AWSTraceHeadersystem attribute, which uses the AWS X-Ray format rather than W3C.
Producers and consumers must agree on the format. A producer writing W3C traceparent and a consumer that only reads X-Ray headers will not connect, and neither side logs an error.
Let instrumentation handle it first
Before writing propagation code, check whether a library already does it. The OpenTelemetry Java agent instruments the Kafka clients, the RabbitMQ Java client, Spring Kafka, Spring Rabbit, JMS and the AWS SDK. Python has instrumentation packages for kafka-python, confluent-kafka, aiokafka, pika, aio-pika and botocore. Node.js has them for kafkajs, amqplib and the AWS SDK. These inject on send and extract on receive without any code.
Manual propagation is for what they do not reach: a client library without instrumentation, a custom envelope format, a batch loop you control yourself, or a transport such as a transactional outbox table. The rest of this post shows the manual version, because it is also the clearest way to see what the instrumentation does for you.
Inject on the producer
The propagation API works on any carrier through a setter and a getter you supply. Here they adapt Kafka headers, which confluent-kafka represents as a list of (key, bytes) tuples:
from opentelemetry import propagate, trace
from opentelemetry.propagators.textmap import Getter, Setter
from opentelemetry.trace import Link, SpanKind
tracer = trace.get_tracer("orders.messaging")
class KafkaHeaderSetter(Setter):
def set(self, carrier, key, value):
carrier.append((key, value.encode("utf-8")))
class KafkaHeaderGetter(Getter):
def get(self, carrier, key):
values = [v.decode("utf-8") for k, v in (carrier or []) if k == key and v is not None]
return values or None
def keys(self, carrier):
return [k for k, _ in (carrier or [])]
SETTER, GETTER = KafkaHeaderSetter(), KafkaHeaderGetter()
def publish(producer, order):
with tracer.start_as_current_span(
"send orders",
kind=SpanKind.PRODUCER,
attributes={
"messaging.system": "kafka",
"messaging.operation.type": "send",
"messaging.operation.name": "send",
"messaging.destination.name": "orders",
},
):
headers = []
propagate.inject(headers, setter=SETTER)
producer.produce("orders", key=order.id, value=order.to_json(), headers=headers)propagate.inject writes whatever the configured propagators produce, so the same code emits traceparent today and keeps working if you add another propagator later. The injection happens inside the producer span on purpose: the context written into the message is the send span's own context, which makes it the message's creation context in semantic convention terms. Inject outside the span and the consumer attaches to the request handler instead, hiding the send entirely.
Note that produce() in confluent-kafka only queues the message; delivery happens later on a background thread. The span measures the enqueue. If you need delivery latency, record it from the delivery callback as an attribute or a metric.
Extract on the consumer
For a consumer handling one message at a time, extract the context from the headers and start the processing span from it:
def handle(msg):
parent = propagate.extract(msg.headers(), getter=GETTER)
creation = trace.get_current_span(parent).get_span_context()
with tracer.start_as_current_span(
"process orders",
context=parent,
kind=SpanKind.CONSUMER,
links=[Link(creation)] if creation.is_valid else [],
attributes={
"messaging.system": "kafka",
"messaging.operation.type": "process",
"messaging.operation.name": "process",
"messaging.destination.name": msg.topic(),
"messaging.destination.partition.id": str(msg.partition()),
"messaging.kafka.offset": msg.offset(),
},
):
process_order(msg.value())extract returns a context and does nothing else. Until a span starts from it, or it is attached with context.attach(), the consumer is still running in whatever context it had before. Forgetting this step is the single most common reason extraction "works" and traces stay disconnected.
This consumer makes the producer's span its parent and also links to it. The semantic conventions say a processing span should link to the creation context of each message it handles, and may use it as the parent, but only in single-message scenarios. Parent and child gives you one trace from HTTP request to consumer, which is what most people want to see. The link keeps the relationship explicit for tools that follow links.
Batch consumers: links instead of a parent
A span has exactly one parent. A consumer that pulls 500 messages and writes them to a database in one transaction is doing work on behalf of up to 500 different traces, and none of them can be the parent. This is the case span links exist for:
msgs = consumer.consume(num_messages=500, timeout=1.0)
links = []
for m in msgs:
ctx = trace.get_current_span(propagate.extract(m.headers(), getter=GETTER)).get_span_context()
if ctx.is_valid:
links.append(Link(ctx))
with tracer.start_as_current_span(
"process orders",
kind=SpanKind.CONSUMER,
links=links,
attributes={
"messaging.system": "kafka",
"messaging.operation.type": "process",
"messaging.destination.name": "orders",
"messaging.batch.message_count": len(msgs),
},
):
write_batch(msgs)If the time spent waiting in poll() matters too, wrap the call in a receive span of kind CLIENT that links to the messages it returned. Skip receive spans for empty polls in tight loops, or they will outnumber everything else. The batch span starts its own trace, or joins the ambient one if the loop already runs inside a span, and points back at every producer. Pass links when you create the span rather than adding them afterwards, so samplers can take them into account. The semantic conventions use links as the default for all consumers for exactly this reason: they are the only structure that works the same way for batches, for push and pull models, and for consumers that already run inside another span, such as a broker pushing messages over HTTP.
The same in Java, with RabbitMQ
Java follows the same pattern through TextMapSetter and TextMapGetter. RabbitMQ headers are a Map<String, Object>, which adds one trap on the consuming side:
TextMapPropagator propagator = GlobalOpenTelemetry.getPropagators().getTextMapPropagator();
// Producer
Span span = tracer.spanBuilder("send orders")
.setSpanKind(SpanKind.PRODUCER)
.setAttribute("messaging.system", "rabbitmq")
.setAttribute("messaging.operation.type", "send")
.setAttribute("messaging.destination.name", "orders")
.startSpan();
try (Scope ignored = span.makeCurrent()) {
Map<String, Object> headers = new HashMap<>();
propagator.inject(Context.current(), headers, (carrier, key, value) -> carrier.put(key, value));
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().headers(headers).build();
channel.basicPublish("orders", "order.created", props, body);
} finally {
span.end();
}
// Consumer
static final TextMapGetter<Map<String, Object>> GETTER = new TextMapGetter<>() {
@Override
public Iterable<String> keys(Map<String, Object> carrier) {
return carrier == null ? List.of() : carrier.keySet();
}
@Override
public String get(Map<String, Object> carrier, String key) {
Object value = carrier == null ? null : carrier.get(key);
// The RabbitMQ client delivers string headers as LongString, not String
return value == null ? null : value.toString();
}
};A getter that casts header values to String throws or returns nothing, because the client hands back LongString objects. Calling toString() handles both. On the consumer, pass propagator.extract(Context.current(), delivery.getProperties().getHeaders(), GETTER) to spanBuilder(...).setParent(...) with SpanKind.CONSUMER.
Span kinds and attributes from the semantic conventions
The messaging conventions define five operation types and the span kind for each, which is what lets a backend draw producer and consumer edges without guessing:
- create:
PRODUCER. One span per message, used when a batch send needs a separate creation context for each message. - send:
PRODUCERwhen its context is the one injected into the message, otherwiseCLIENT. - receive:
CLIENT. A pull call such aspoll()that the application initiates. - process:
CONSUMER. The handler or callback doing the work. - settle:
CLIENT. Acknowledgements, rejections and offset commits.
Span names follow {operation name} {destination}, such as send orders or process orders. The attributes worth setting on every messaging span are messaging.system (kafka, rabbitmq, aws_sqs), messaging.operation.type, messaging.operation.name and messaging.destination.name, plus messaging.batch.message_count on batch operations only. Kafka adds messaging.consumer.group.name, messaging.destination.partition.id and messaging.kafka.offset.
These conventions are still marked Development, and instrumentation libraries do not all emit the same version. Older releases use messaging.operation instead of messaging.operation.type, messaging.kafka.consumer.group instead of messaging.consumer.group.name, and give receive spans the CONSUMER kind. Build dashboards on the names your instrumentation actually emits, and check again after upgrades.
Pitfalls that break the chain
- Hops that drop headers. Stream processors, retry and dead-letter republishers, and bridges between brokers often build a new message from the key and body only. Copy the headers when forwarding, or start a new span that links to the original context.
- Duplicate context. Running an agent that already instruments the client and also injecting by hand writes
traceparenttwice. Kafka allows duplicate header keys, so the consumer may read the wrong one. Pick one mechanism per client. - SQS attributes you never asked for.
ReceiveMessagereturns message attributes only when the request lists them inMessageAttributeNames(or asks forAll), and system attributes such asAWSTraceHeaderonly when requested separately. Without that, extraction finds nothing. SNS fan-out to SQS without raw message delivery moves the attributes into the JSON body. - Traces that last for hours. A message consumed after a long backlog or a replay turns a parent and child trace into one spanning hours, which distorts duration views. Links keep both sides bounded.
- Sampling across the queue. As a child, the consumer follows the producer's sampled flag under the default
parentbasedsamplers. With links only, the consumer decides on its own, so a sampled producer can point to a consumer trace that was dropped. OpenTelemetry sampling: head vs tail covers how to keep complete traces. - Context lost inside the consumer. Frameworks that hand each message from the poll loop to a thread pool or an async task drop the current context unless that executor is instrumented. Extract from the message on the thread that does the work, and start the processing span there, not in the poll loop.
- Baggage leaks. Everything in
baggagetravels to every downstream consumer, including ones owned by other teams. Keep identifiers and secrets out of it.
Seeing it in aiAxonIQ
Once producers and consumers share context, the trace no longer stops at the broker. The APM & Distributed Tracing module ingests these spans over OTLP and follows context propagation across Kafka event streams and background queues, so a slow consumer shows up inside the request that enqueued its work rather than as an orphan trace.
If you want the auto-instrumented path instead of the manual one, the Java monitoring page and the Python monitoring page show the agent and distro setup that covers the common clients without code changes.