A trace that ends at the HTTP response tells only half the story when the request publishes a Kafka event. The consumer may run seconds later, on another pod, after a retry. Without deliberate context propagation, the two halves become unrelated waterfalls, and incident responders start guessing from timestamps.

1. Decide what relationship the trace should express

An HTTP handler that publishes a record creates a producer span. The consumer performs work in a separate execution context. OpenTelemetry messaging conventions describe producer and consumer operations; a consumer can use a parent-child relationship when appropriate, or a span link when processing is detached, batched, or has multiple upstream causes. A link preserves causality without pretending an asynchronous queue is a synchronous function call.

Do not reuse one request span as the parent of every consumer in a long-lived process. Each message needs its own extracted context, and batch processing may need multiple links.

2. Propagate context in Kafka headers

W3C Trace Context standardizes the traceparent and optional tracestate fields. On publish, inject the active context into a fresh carrier and attach it to the record headers. On consume, extract from that record's headers before creating the processing span. Kafka header values are bytes, so convert carefully at the boundary.

import { context, propagation, trace, SpanKind } from '@opentelemetry/api';

const tracer = trace.getTracer('orders-service');

function headersForMessage(): Record<string, string> {
  const carrier: Record<string, string> = {};
  propagation.inject(context.active(), carrier);
  return carrier;
}

// Inside an active HTTP or producer span:
await producer.send({
  topic: 'orders.created',
  messages: [{
    key: orderId,
    value: JSON.stringify({ orderId }),
    headers: headersForMessage(),
  }],
});

That example assumes the Node.js OpenTelemetry SDK has been initialized before application modules load, with a configured propagator and exporter. The API package alone does not create or export spans. Use instrumentation libraries where they correctly cover your Kafka client; write manual spans only for meaningful gaps.

3. Extract per message and finish spans reliably

import { context, propagation, trace, SpanKind } from '@opentelemetry/api';

const tracer = trace.getTracer('orders-consumer');

function decodeHeaders(headers: Record<string, unknown> = {}) {
  return Object.fromEntries(
    Object.entries(headers).map(([key, value]) => [
      key,
      Buffer.isBuffer(value) ? value.toString('utf8') : String(value ?? ''),
    ]),
  );
}

async function processRecord(message: { headers?: Record<string, unknown>; value: Buffer }) {
  const extracted = propagation.extract(context.active(), decodeHeaders(message.headers));
  const span = tracer.startSpan('process orders.created', {
    kind: SpanKind.CONSUMER,
  }, extracted);
  try {
    await context.with(trace.setSpan(extracted, span), async () => {
      await applyOrder(JSON.parse(message.value.toString('utf8')));
    });
  } catch (error) {
    span.recordException(error as Error);
    span.setStatus({ code: 2 }); // SpanStatusCode.ERROR
    throw error;
  } finally {
    span.end();
  }
}

This illustrates a parent-context model for one message. For a batch, use span links to each extracted message context instead of assigning multiple parents. In real code, validate payloads, handle absent headers, and use the SpanStatusCode enum rather than a numeric literal.

4. Separate delivery identity from trace identity

A trace ID is not an idempotency key. Kafka can redeliver a message, and the same business event may be retried with a different processing span. Persist an event identifier or business operation key for deduplication; use tracing to explain how attempts unfolded. Put stable, low-cardinality identifiers in logs and span attributes where appropriate, but avoid raw payloads, credentials, email addresses, or unbounded IDs as metric labels.

5. Make sampling and cardinality intentional

Head sampling at the HTTP edge can discard traces before a downstream Kafka failure is known. Evaluate tail sampling at the collector when operationally justified, accounting for collector memory and latency. Monitor exporter failures and dropped spans. Use bounded attributes such as topic and operation, and treat partition, offset, and message identifiers as diagnostic fields with a retention and privacy policy rather than unrestricted metric dimensions.

6. Test the broken paths

Production rule. Trace context explains causality; business identifiers establish correctness. Use both, and never let a telemetry outage become a message-processing outage.

Official references

Related engineering notes