Propagating Trace Context Across Services
Carry a trace identifier through HTTP, queues and background jobs so a single request can be followed end to end without gaps that hide the real bottleneck.
On this page
Introduction
A distributed trace is only as good as its weakest link. If one service drops the context header, the trace splits into two unrelated fragments and the latency you were chasing hides in the gap between them. Propagation is the act of carrying the trace identifier and span identifiers across every boundary: HTTP calls, message queues, scheduled jobs and even threads inside one process. It is simple in principle and easy to break in practice, especially at boundaries that are not obvious HTTP calls.
What a Trace Context Contains
A trace context carries a trace identifier that is constant for the whole request and a span identifier that names the current unit of work, plus flags such as sampled. The W3C traceparent header encodes these compactly so that heterogeneous systems agree on the format. When a service makes an outbound call it starts a child span, sets the parent to its own span, and sends the new context downstream. Every span then joins into one tree that reconstructs the request.
package tracing
import (
"context"
"net/http"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
)
// Server side: extract the remote context from the incoming request.
func Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := otel.GetTextMapPropagator().Extract(
r.Context(), propagation.HeaderCarrier(r.Header),
)
ctx, span := otel.Tracer("api").Start(ctx, "handle "+r.URL.Path)
defer span.End()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Client side: inject the current context into outbound headers.
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))
return client.Do(req.WithContext(ctx))
}
Propagating over HTTP
For HTTP the mechanics are standard: read the incoming traceparent header on the server, extract it into the request context, create a child span, and inject the updated context into every outbound request. Middleware libraries do this automatically when using an instrumented HTTP client, but a hand rolled client that bypasses the instrumentation silently breaks the chain. Verify propagation by asserting that the header is present on outbound calls in tests rather than assuming the framework handles it.
// Carrying context across a queue hop.
type Envelope struct {
Payload []byte `json:"payload"`
TraceCtx map[string]string `json:"trace_ctx"` // traceparent and tracestate
}
func Publish(ctx context.Context, e Envelope) error {
h := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, h)
e.TraceCtx = h
return broker.Publish(e)
}
func Consume(ctx context.Context, e Envelope) {
parent := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(e.TraceCtx))
ctx, span := otel.Tracer("worker").Start(parent, "process message")
defer span.End()
handle(ctx, e.Payload) // downstream spans attach to this parent
}
Propagating Through Queues
Message queues do not carry HTTP headers, so the context must travel in the message metadata or payload. A producer writes the traceparent into message attributes and a consumer reads it back and starts a span as a child, marking it as a new trace or a link depending on whether it is a continuation or a new unit of work. Without this, asynchronous work appears disconnected from the request that caused it, which is exactly where latency and failures tend to hide.
Propagating into Background Jobs
A delayed job scheduled by a request must either carry the original context or start a fresh trace with a link to the origin. Carrying the original context preserves causality across the delay, while a new trace avoids a single trace spanning hours, which is hard to visualise. Choose based on whether you care about the causal chain or about the job own timeline, and record the originating request identifier either way so you can pivot between them.
Context Inside a Process
Within a process, the trace context must travel through goroutines, threads, promise chains and callbacks. A context object passed explicitly is the reliable mechanism; relying on thread local storage fails the moment work moves to another thread. When spawning a goroutine or worker, pass the context so its spans attach to the right parent. A context that loses its parent produces orphan spans that still look plausible but connect to nothing.
Sampling Decisions
Sampling decides which traces are recorded, and the decision must be propagated so all services either record the whole trace or none of it. A sampled flag in the context enforces consistency; without it, one service records and another does not, yielding half traces. Head based sampling decides at the start and is simple; tail based sampling decides after seeing the whole trace and can keep all errors, but requires buffering. Propagate the decision regardless of which you use.
Correlation Across Systems You Do Not Control
Not every hop uses traceparent: a payment provider or a legacy service may return only its own identifier. Record that identifier as an attribute on your span so you can pivot from your trace to theirs when investigating. Also propagate your own request identifier in logs so log based investigation lines up with traces. Linking the two is what lets you move from a slow span to the exact log lines around it.
Common Ways Propagation Breaks
Propagation most often breaks at boundaries someone forgot: a cron job, a fire and forget goroutine, a retry that builds a fresh request without the context, or a caching layer that returns a stored response without joining the trace. Each break is invisible until you need the trace and find a gap. Instrument the boundaries explicitly and test them, because the framework only covers the paths it knows about.
Verifying End to End
Write an integration test that makes a request through the full chain, including a queue hop and a background job, and asserts that a single trace contains spans from every service with a correct parent chain. Assert that the outbound calls carry the header and that no span is orphaned. Run this test in CI so adding a new boundary that forgets to propagate fails fast rather than producing silent gaps in production.
Sources
Sources: W3C trace context, OpenTelemetry propagation, OpenTelemetry Go.
FAQ
- Why is my trace broken in the middle?
- A boundary is not propagating the context. Common culprits are queue hops, background jobs, retries that rebuild a request, and hand rolled HTTP clients. Instrument those boundaries and test them explicitly.
- Should a delayed job reuse the original trace?
- Either is valid. Reuse to preserve causality, or start a new trace with a link if a single trace spanning hours is hard to read. Record the originating request id so you can pivot between them.
Report a problem with this articleOpens a pre-filled issue on GitHub.