Agent Trace Context Across Message Queues

How to carry agent trace context through SQS, Kafka, RabbitMQ and Redis queues: inject per message, extract per message, link batch receives, and debug gaps.

Ephraim Duncan

Agent trace context across a message queue works when the producer injects a W3C traceparent into every message's metadata, the consumer extracts it per message, and a batch receive span links to each message's context instead of parenting to one of them. Skip any of those steps and your agent runs show up as orphaned root traces with no connection to the request that enqueued them.

This is the most common reason queue-driven agents look broken in OpenTelemetry-based LLM tracing. The model calls and tool steps are instrumented fine. The trace just starts over at the consumer. The fix is application instrumentation, not a new tool, and it follows the OpenTelemetry messaging conventions closely.

What agent trace context means once a queue sits in the middle

Agent trace context is the trace ID and parent span ID that tie an agent run back to the work that caused it, and a queue breaks that chain unless you carry it in the message itself. In a synchronous call the context travels in HTTP headers. A queue has no such channel. The producer finishes, the process may be gone, and the consumer picks the message up seconds or hours later on a different host.

The OpenTelemetry messaging conventions define the pieces: a producer creates and sends a message, an intermediary forwards it, and a consumer receives and acts on it. Context propagation is the job of attaching trace context to the message so the consumer can pick it up.

That is also the plain answer to "what are traces in AI agents": a trace is the connected record of one unit of work, including every model call, tool step and retrieval. With a queue in the middle, the connection is exactly what you have to rebuild by hand. For the queued-job angle in more depth, see Generative AI Monitoring: Trace Queued Agent Jobs.

How is AI agent monitoring different from traditional APM?

Traditional APM watches request latency, errors and resource use across services. Agent monitoring adds the content and cost of each step: model calls, tool calls, retrievals, token counts and the decisions between them, all within one run. With a queue in the middle, it also has to keep a run connected to the message that started it, which is why per-message trace context and span links matter. The standard OpenTelemetry tracing model underlies both, so you extend it with agent-specific spans and attributes rather than replacing it.

What is AI agent monitoring?

AI agent monitoring is recording what an agent does during each run so you can find slow steps and inspect failed calls. That means traces of model calls, tool steps and retrievals, with latency, token usage, cost and errors on each. When agents run from queue workers, monitoring also needs trace context passed through the message, so a run shows up as part of the request that enqueued it instead of as an orphaned trace.

Inject context into every message at the producer

Inject trace context into each message's own metadata at send time, one message at a time, using your OpenTelemetry propagator. Use message attributes in SQS, headers in Kafka and RabbitMQ, and a metadata field in the payload envelope for Redis-style queues that have no header concept.

In TypeScript:

import { context, propagation } from "@opentelemetry/api";

const carrier: Record<string, string> = {};
propagation.inject(context.active(), carrier);
// carrier now holds traceparent (and tracestate if present)
await producer.send({ value: payload, headers: carrier });

In Python:

from opentelemetry import propagate

carrier = {}
propagate.inject(carrier)
producer.send(topic, value=payload, headers=list(carrier.items()))

Two rules matter. First, inject inside an active span, ideally a create or send span, so the injected traceparent points at something real. Second, inject per message, not per batch. If you publish 10 messages in a loop, each needs its own carrier. Reusing one carrier gives every message the same parent and hides which request produced which job.

Keep the payload for business data and the metadata for context. Do not put trace IDs in the body of a message the agent will feed to a model.

What security considerations apply to trace context in messages?

Put only trace identifiers in message attributes: traceparent and, if needed, tracestate. Never put prompts, user data or secrets in them, since message headers are often visible to many consumers and logs. Separately, prompts and outputs recorded on spans can contain sensitive data. With telemetry.dev, prompt capture can be turned off per environment before storage, and redaction patterns help but cannot catch all sensitive data, so filter in your instrumentation if content must never leave the app.

In a batched consumer, extract context from each message separately and link the batch receive span to every message context, because a single span cannot have multiple parents. The OpenTelemetry conventions say the same: when a batch is received, correlate with producers through links rather than a parent.

In Python, a batch handler looks like this:

from opentelemetry import propagate, trace
from opentelemetry.trace import Link

tracer = trace.get_tracer("agent-worker")

def handle_batch(messages):
    links = []
    for m in messages:
        ctx = propagate.extract(dict(m.headers))
        sc = trace.get_current_span(ctx).get_span_context()
        if sc.is_valid:
            links.append(Link(sc))
    with tracer.start_as_current_span(
        "receive my-queue",
        kind=trace.SpanKind.CONSUMER,
        links=links,
        attributes={"messaging.batch.message_count": len(messages)},
    ):
        for m in messages:
            ctx = propagate.extract(dict(m.headers))
            with tracer.start_as_current_span(
                "process my-queue", context=ctx, kind=trace.SpanKind.CONSUMER
            ):
                run_agent(m)

The receive span gets links and a messaging.batch.message_count attribute. Each process span uses that message's extracted context as its parent, so the agent run lands inside the originating request's trace. When per-message values differ, such as message IDs, put them on the individual link attributes rather than on the shared span.

Do not parent the receive span to the first message. It makes one request look like the cause of nine others.

Process spans, receive spans and agent runs: the trace shape to aim for

The target shape has three layers: a receive span that links to many producers, a process span per message parented to its own producer, and the agent run nested under the process span. Each layer answers a different question.

Span Parent or link Answers
Producer send span Request that enqueued the work Who created this job?
Receive span (batch) Links to each message context How big was the batch, how long was the poll?
Process span (per message) Parent is that message's context How long did this one job take end to end?
Agent run and model/tool spans Children of the process span Which step was slow or failed?

The payoff is that the trace opened from the original request now contains the agent run that came out of the queue, and the batch-level receive span is still there for queue-side questions like batch size and poll latency. Link navigation covers the reverse direction: from a receive span you can jump to every producer it served.

If your agent run is created by a framework, make sure it starts as a child of the process span, not as a fresh root. LLM Tracing: Fix Async Parent and Child Span Links covers the common ways async code drops the active context.

What are the best practices for observing agents behind a queue?

Keep one trace per originating request and one process span per message, so each agent run stays attached to its cause. Inject context at the producer, extract it per message rather than per batch, and use span links, not parenting, from the process span to the batch receive span. Put model calls, tool steps and retrievals under the process span as children. Add message ID, attempt number and queue name as attributes so you can search for any message and see its full agent run.

Diagnostic checks when message metadata goes missing

When agent traces arrive disconnected, check the message, then the extraction, then the active context, in that order. Most gaps are one of five causes.

  1. Log the raw metadata on receive. Print the header or attribute keys for one message. If traceparent is absent, the bug is at the producer or in a layer that strips metadata.

  2. Check attribute limits and key casing. SQS caps message attributes at 10 per message, and some brokers or clients lowercase or rewrite header names. A carrier key of Traceparent will not match an extractor looking for traceparent if your code does a case-sensitive lookup.

  3. Check header decoding. Kafka headers arrive as bytes. If you pass bytes to the propagator, extraction silently returns an empty context. Decode to strings first.

  4. Check for a Redis-style envelope. Queues without native headers need the carrier in your envelope. If a library re-serializes the payload, confirm the metadata field survives the round trip.

  5. Check the sampling decision. An extracted context with the sampled flag off yields unsampled children. Disconnected traces and missing traces look similar, so rule this out. See LLM Trace Sampling: Diagnose Missing Runs.

Also check retries and dead-letter queues. A redelivered message keeps its original context, which is usually what you want, but a republish from a dead-letter handler needs a fresh inject or the context is lost.

Verify the result in your trace viewer (and what to log per message)

Verify by picking one enqueued request and confirming its trace contains the process span and the agent run, then opening the receive span and confirming it links back to that request. Do this with a batch of at least three messages, because single-message tests hide the parent-versus-link mistake.

Log these fields per message so a failure is traceable even before the viewer loads:

  • the message ID from the broker

  • the extracted trace ID and whether extraction found a valid context

  • the queue or topic name and consumer group

  • batch size, on the receive span as messaging.batch.message_count

A line like msg=9f2 trace_id=4bf9... extracted=true batch=10 lets you search logs for one trace ID and find every message it touched.

telemetry.dev is LLM observability built on OpenTelemetry: it traces model calls, tool steps and retrievals with cost, latency, token and error tracking, and it accepts spans from any OTLP/HTTP exporter or OpenTelemetry Collector. Once your producers and consumers propagate context as above, those queued agent runs show up in one trace tree instead of scattered roots. For reading the result, see Agent Trace Viewer: Read a Failed Run.

Which signals should you track for each queued agent run?

Track latency per step, token counts, cost, errors and tool calls, and tie each to the message that triggered the run. In a queued setup, also record queue wait time (enqueue to receive), batch size, delivery attempt number and the message ID as span attributes on the process span. Model call and tool spans then show where a run was slow or failed. Cost is only as accurate as the token usage your instrumentation reports and the model pricing it matches, so check that usage attributes are present on model spans.

How do you implement AI agent monitoring with OpenTelemetry when agents run from queue workers?

Instrument the application so every agent run is a span in a trace, then carry that trace across the queue. Inject W3C trace context into message attributes at the producer, extract it per message in the consumer, and create a process span per message with a span link back to the batch receive span. Model calls and tool steps become child spans of the process span. Any OTLP/HTTP exporter or OpenTelemetry Collector can ship the result, and the OpenTelemetry messaging spans conventions (https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/) define the span names and attributes to use.

A queue does not break agent trace context. Dropped metadata and a mis-parented batch span do. Inject into every message, extract for every message, link the receive span, and parent each process span to its own producer. Then send a three-message batch through your worker, point your OTLP exporter at telemetry.dev's free plan (30k units, 14-day retention), and confirm the agent run sits inside the trace of the request that queued it.

Share this article

Related posts

Agent Trace Viewer: Read a Failed Run

An agent trace viewer shows each model call and tool step as a span. Read one failed run end to end: waterfall, first error, and model vs tool latency.

Agent Handoff Tracing: Follow Work Across Agents

Agent handoff tracing with standard OpenTelemetry: parent-child spans in one process, propagated context or links across processes, and handoff IDs that expose lost work.