Context Propagation Across Async Calls
A trace is only as complete as its weakest hop. Context propagation carries the trace ID and the current span ID from one unit of work to the next: across function calls (in-process), across network calls (headers), and across asynchronous boundaries (goroutines, queues, scheduled jobs), where most traces break.
The carriers
| Boundary | Carrier | Done by |
|---|---|---|
| function calls | context.Context (Go), thread-local/async context (Java, Python contextvars, Node AsyncLocalStorage) |
the language + SDK |
| HTTP, gRPC | traceparent + tracestate headers (W3C Trace Context); baggage header for user key-values |
instrumentation libraries (otelhttp, gRPC interceptors) |
| message queues (Kafka, RabbitMQ, SQS, NATS) | message headers/attributes with the same keys | the producer and consumer instrumentation, or you |
| goroutines, thread pools | pass the ctx explicitly |
you |
| batch jobs consuming many messages | span links to each message's context | you |
The propagator API is the same everywhere: inject the current context into a carrier (a map of strings), extract it on the other side.
W3C Trace Context and baggage
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
tracestate: vendorA=opaque-value (optional, vendor-specific)
baggage: tenant=acme,plan=pro (optional, application key-values)Baggage travels with the request to every downstream service, which can read it (tenant=acme) and copy it onto their spans or logs. It is sent in plain text to every hop, including third-party APIs if your HTTP client propagates it: never put secrets or personal data in it, and keep it small.
Propagation, modelled
This standard-library model does what the OTel propagators do: inject writes a traceparent header (or message header) from the span in the context, extract reads it back into a new context. It follows one linkly request through an HTTP call to a second service, a goroutine, and a queue consumed later by a worker:
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
)
type spanCtx struct{ traceID, spanID string }
type key struct{}
var (
mu sync.Mutex
next = 0x10
log []string
newTrace = []string{"4bf92f3577b34da6a3ce929d0e0e4736", "7d2c90e1a4b35f68c0e2d4f6a8b1c357"} // a real SDK generates fresh IDs
)
func newSpanID() string { mu.Lock(); defer mu.Unlock(); next++; return fmt.Sprintf("%016x", next) }
// start begins a span as a child of whatever span ctx carries.
func start(ctx context.Context, name string) context.Context {
parent, _ := ctx.Value(key{}).(spanCtx)
sc := spanCtx{traceID: parent.traceID, spanID: newSpanID()}
if sc.traceID == "" { // no parent: start a new trace
mu.Lock()
sc.traceID, newTrace = newTrace[0], newTrace[1:]
mu.Unlock()
}
p := parent.spanID
if p == "" {
p = "-"
}
mu.Lock()
log = append(log, fmt.Sprintf("%-24s trace=…%s span=%s parent=%s", name, sc.traceID[28:], sc.spanID[12:], lastN(p, 4)))
mu.Unlock()
return context.WithValue(ctx, key{}, sc)
}
func lastN(s string, n int) string {
if len(s) <= n {
return s
}
return s[len(s)-n:]
}
// inject / extract: the W3C traceparent format over any string map
func inject(ctx context.Context, set func(k, v string)) {
if sc, ok := ctx.Value(key{}).(spanCtx); ok {
set("traceparent", fmt.Sprintf("00-%s-%s-01", sc.traceID, sc.spanID))
}
}
func extract(ctx context.Context, get func(k string) string) context.Context {
parts := strings.Split(get("traceparent"), "-")
if len(parts) != 4 || len(parts[1]) != 32 || len(parts[2]) != 16 {
return ctx // missing or malformed: a new trace will start
}
return context.WithValue(ctx, key{}, spanCtx{traceID: parts[1], spanID: parts[2]})
}
type message struct {
body string
headers map[string]string
}
func main() {
queue := make(chan message, 10)
// service 2: an HTTP API linkly calls (e.g. a URL safety checker)
checker := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := extract(r.Context(), r.Header.Get)
start(ctx, "checker: GET /check")
w.WriteHeader(http.StatusOK)
})
// linkly: POST /links
ctx := start(context.Background(), "linkly: POST /links")
callCtx := start(ctx, "linkly: HTTP GET check")
req := httptest.NewRequest("GET", "/check", nil)
inject(callCtx, req.Header.Set)
checker.ServeHTTP(httptest.NewRecorder(), req)
var wg sync.WaitGroup
wg.Add(1)
go func(ctx context.Context) { // pass ctx into the goroutine explicitly
defer wg.Done()
start(ctx, "linkly: warm cache")
}(ctx)
wg.Wait()
pubCtx := start(ctx, "linkly: publish created")
m := message{body: "link q1x9 created", headers: map[string]string{}}
inject(pubCtx, func(k, v string) { m.headers[k] = v })
queue <- m
m2 := message{body: "legacy producer, no headers", headers: map[string]string{}}
queue <- m2
close(queue)
// later, in another process: the analytics worker
for msg := range queue {
wctx := extract(context.Background(), func(k string) string { return msg.headers[k] })
start(wctx, "worker: process "+strings.Fields(msg.body)[0])
}
for _, l := range log {
fmt.Println(l)
}
}linkly: POST /links trace=…4736 span=0011 parent=-
linkly: HTTP GET check trace=…4736 span=0012 parent=0011
checker: GET /check trace=…4736 span=0013 parent=0012
linkly: warm cache trace=…4736 span=0014 parent=0011
linkly: publish created trace=…4736 span=0015 parent=0011
worker: process link trace=…4736 span=0016 parent=0015
worker: process legacy trace=…c357 span=0017 parent=-
Every span except the last joined trace …4736: the checker service through the HTTP header, the goroutine through the explicitly passed ctx, the worker through the message header. The message from the legacy producer had no traceparent, so its worker span started a new trace (…c357) with no parent: in the UI it is unconnected to any request.
Async patterns in practice
- Goroutines / thread pools: pass
ctxas a parameter. With a detached background task that must outlive the request, usecontext.WithoutCancel(ctx)(Go 1.21+) to keep the trace but drop the request's cancellation. - Queues: the producer span is kind
PRODUCER, the consumer spanCONSUMER. Whether the consumer span is a child of the producer (one trace from HTTP request to background job) or a new trace linked to it is a choice: children make long-lived traces that stay open for hours if the queue is slow; links keep traces short and still navigable. OTel's messaging semantic conventions describe both. - Batch consumers: one span processing 100 messages can't have 100 parents; it gets one link per message context.
- Cron jobs and schedulers start new traces; put the job run ID on the root span.
- Service meshes (Istio, Linkerd) create proxy spans but cannot propagate context through your code: the app must still forward the headers from its inbound request to its outbound calls.
When traces break
| Symptom in the tracing UI | Usual cause |
|---|---|
| a service's spans appear as separate one-service traces | it doesn't extract incoming headers (missing server instrumentation) |
| downstream services missing from the trace | outgoing client isn't instrumented, so traceparent isn't injected |
| traces cut at a queue | producer/consumer don't copy headers onto messages |
| "orphan" spans with a parent that never arrives | the parent's service doesn't export (not sampled, wrong endpoint, crashed before flush) |
| mixed formats | an old service uses B3 or Jaeger headers: configure a composite propagator (tracecontext,baggage,b3) during migration |
Test yourself
How does the trace context reach a goroutine in Go?
- Automatically through thread-local storage
- You pass the context.Context into the goroutine explicitly
- Through an environment variable
- It can't
What should never go into W3C baggage?
- A tenant id
- Secrets or personal data, because baggage is sent in clear text to every downstream hop
- A feature flag
- A region name
A worker processes a batch of 50 queued messages in one span. How does it relate to the 50 producing traces?
- It picks one as parent
- With 50 span links, one per message context
- It can't be related
- It copies all 50 trace IDs into attributes