An order hits the API, goes into a Kafka topic, and a consumer processes it two seconds later. In Dynatrace you see two unrelated traces: the HTTP call on one side, the processing on the other. Kafka trace context propagation is missing, and the on-call engineer wastes time stitching the pieces together by hand during an incident.
Goal of this tutorial: carry the W3C Trace Context (the traceparent header) inside Kafka message headers, so that you get a single trace from producer to consumer in Dynatrace. The content applies to Dynatrace SaaS and Dynatrace Managed for OTLP ingestion; the DQL verification queries assume a SaaS environment on Grail.
If traces do not reach Dynatrace at all, start with troubleshooting missing OpenTelemetry traces, then come back here.
The problem: a trace cut in two
With HTTP, propagation is obvious: the client adds traceparent to the request headers and the server reads it. With Kafka there is no direct request. The producer writes a message, the broker stores it, the consumer reads it later. If nobody writes the context into the message, the consumer starts a new trace.
The SRE consequence: the end-to-end time of an order cannot be measured, an « order processed » latency SLI is impossible to compute, and MTTR goes up because you have to correlate by timestamp.
Kafka trace context propagation: how it works
Since Kafka 0.11, every message (record) can carry key-value headers. The principle is simple:
- On the producer side, a
PRODUCERspan is created and the W3C propagator writestraceparent(andtracestateif present) into the record headers. - On the consumer side, the propagator reads those headers, rebuilds the context and starts a
CONSUMERspan attached to the same trace (as a child or through a span link, depending on the instrumentation).
Useful attributes follow the OpenTelemetry messaging semantic conventions: messaging.system = kafka, messaging.destination.name = topic name, messaging.operation.type (publish, process…, which replaces the deprecated messaging.operation). Check the current names in the OpenTelemetry Kafka semantic conventions.
Prerequisites
- Producer and consumer services instrumented with OpenTelemetry (Java agent, Python SDK, etc.) or by OneAgent.
- OTLP export to Dynatrace, direct or through a Collector: see the OpenTelemetry Collector for Dynatrace.
- An API token with the
openTelemetryTrace.ingestscope (SaaS and Managed). - Kafka brokers 0.11 or later (message headers).
Step 1 — Java: let the OpenTelemetry agent inject the context
The OpenTelemetry Java agent instruments kafka-clients without code changes. It injects traceparent on send and extracts it on receive. The basic configuration is enough:
export OTEL_SERVICE_NAME=order-api
export OTEL_PROPAGATORS=tracecontext,baggage
export OTEL_EXPORTER_OTLP_ENDPOINT=https://<environment-id>.live.dynatrace.com/api/v2/otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Api-Token%20${DT_API_TOKEN}"
java -javaagent:opentelemetry-javaagent.jar -jar order-api.jar
Critical lines: OTEL_PROPAGATORS must contain tracecontext on both sides, otherwise the consumer does not understand the header. On Managed, the OTLP URL looks like https://<cluster>/e/<environment-id>/api/v2/otlp. Agent details are in the OpenTelemetry Java agent with Dynatrace.
Watch out: depending on the agent version and its options for receive telemetry, the processing span is either a child of the producer span or a linked span. Both show up in the same distributed view in Dynatrace if the link is kept, but they render differently. Check the README of the Kafka instrumentation for your version.
Step 2 — Python: propagate the context by hand
With confluent-kafka, automatic instrumentation exists but remains partial depending on the version. Manual propagation is short and explicit:
from opentelemetry import trace, propagate
from opentelemetry.trace import SpanKind
tracer = trace.get_tracer("order-api")
def send_order(producer, payload: bytes):
with tracer.start_as_current_span("orders publish", kind=SpanKind.PRODUCER) as span:
span.set_attribute("messaging.system", "kafka")
span.set_attribute("messaging.destination.name", "orders")
carrier = {}
propagate.inject(carrier) # writes traceparent (and tracestate)
producer.produce("orders", value=payload, headers=list(carrier.items()))
On the consumer side, read the headers (bytes) and rebuild the context:
def handle(msg):
carrier = {k: v.decode("utf-8") for k, v in (msg.headers() or []) if v is not None}
ctx = propagate.extract(carrier)
with tracer.start_as_current_span("orders process", context=ctx, kind=SpanKind.CONSUMER) as span:
span.set_attribute("messaging.system", "kafka")
span.set_attribute("messaging.destination.name", "orders")
process(msg.value())
Critical line: context=ctx. Without it, the consumer span becomes the root of a new trace. The Python SDK’s default propagator is tracecontext,baggage.
Step 3 — Mixed OneAgent and OpenTelemetry
If the producer is monitored by OneAgent and the consumer by OpenTelemetry (or the other way round), both must speak W3C Trace Context. OneAgent supports W3C Trace Context, but propagation over messaging depends on the technology and version: check the Kafka page of the OneAgent documentation on docs.dynatrace.com. Also avoid instrumenting the same client twice: it is the classic source of duplicate spans between OneAgent and OpenTelemetry.
Step 4 — Do not break the context along the way
- Kafka Streams, MirrorMaker, connectors: a component that copies a message may drop or keep the headers. Test every hop.
- Batch processing: one poll returns several messages from different traces. Create one span per message, or a batch span with links to each context.
- Sampling: with a
parentbased_*sampler, the consumer follows the producer’s decision. Different sampling on each side produces incomplete traces.
How to check that it works
First, look at a raw message: kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --property print.headers=true --from-beginning --max-messages 1. You should see traceparent:00-<trace-id>-<span-id>-01.
Then, in Dynatrace SaaS, open a Notebook and count the traces that contain both a producer span and a consumer span:
fetch spans, from: now() - 1h
| filter messaging.system == "kafka"
| summarize kinds = collectDistinct(span.kind), services = collectDistinct(service.name), by: { trace.id }
| filter arraySize(kinds) >= 2
| limit 20
If the query returns nothing while both services send spans, the context is lost between them. The exact values of span.kind and the field names may vary: check them first with fetch spans | limit 10. On Managed, open a PurePath of the consumer service in the distributed traces view and check that the producer service appears upstream.
Best practices
- One propagation format across the whole chain:
tracecontext. Remove proprietary formats as soon as you can. - Name spans «
<topic> publish» and «<topic> process« : search stays readable. - Measure the delay between production and processing: it is often the best SLI for an asynchronous pipeline.
- Never put personal data in
baggage: it travels in every message.
Frequently asked questions
Do I need to change the Kafka brokers?
No. Headers are carried as-is by the broker. Only the producer and consumer clients take part in propagation.
Why does the consumer appear in a separate trace despite the header?
Most often, the consumer’s propagator is not tracecontext, the extracted context is not passed to the span, or the instrumentation creates a span link rather than a parent-child relationship. Check those three points in that order.
Does this work with Dynatrace Managed?
Yes for OTLP trace ingestion and the distributed view. DQL queries on fetch spans, however, require a SaaS environment on Grail.
Conclusion
A few lines of configuration are enough for an order to remain a single trace, from the API to the consumer. You gain a measurable end-to-end latency and shorter investigations. Next step: turn that delay into an SLI, as in end-to-end OpenTelemetry.
span.observer is an independent community blog, not affiliated with Dynatrace LLC. Dynatrace is a trademark of Dynatrace LLC. Features evolve quickly: check their availability in your environment and in the official documentation.
Originally published on span.observer. French version: https://span.observer/fr/propagation-contexte-kafka-dynatrace/.
Top comments (0)