Propagate trace context
Propagate trace context
A distributed trace connects spans (timed units of work) across processes. Go context.Context carries cancellation and values inside a process; it does not automatically serialize values into HTTP headers. W3C Trace Context defines traceparent with version, trace ID, parent span ID and flags. Use an instrumentation library for production propagation, validation, span creation and sampling. Never interpret a trace ID as identity or authorization.
package main
import ( "context" "fmt" "net/http")
type traceKey struct{}
func main() { ctx := context.WithValue(context.Background(), traceKey{}, "synthetic-trace") r, err := http.NewRequestWithContext(ctx, "GET", "http://example.invalid", nil) if err != nil { panic(err) } fmt.Println(r.Context().Value(traceKey{}), r.Header.Get("traceparent") == "")}The value exists on the local request context, but no trace header was injected. Use a typed private key to avoid collisions. Context values should carry scoped metadata, not arbitrary dependencies. Cancellation still follows the parent context.
Expected output:
synthetic-trace truePreserve trace identity while changing the parent span
package main
import ( "fmt" "net/http/httptest" "strings")
func main() { in := "00-1234567890abcdef1234567890abcdef-1111111111111111-01" parts := strings.Split(in, "-") out := strings.Join([]string{parts[0], parts[1], "2222222222222222", parts[3]}, "-") r := httptest.NewRequest("GET", "/", nil) r.Header.Set("traceparent", out) fmt.Println(r.Header.Get("traceparent"))}The known valid synthetic input illustrates a service sending its own span ID as the downstream parent. This is not a parser: production must handle invalid or zero IDs, duplicate headers, flags, supported versions and tracestate, and generate unpredictable IDs. Use vetted propagators and control whether untrusted incoming context crosses trust boundaries. No trace backend is used here.
Expected output:
00-1234567890abcdef1234567890abcdef-2222222222222222-01Try it locally
Attach a cancellation-aware context to an HTTP request, cancel it, and verify that the request context is canceled without sending any traffic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reliability and observability 04: Propagate trace context
Check the lesson objective before moving on.
Does NewRequestWithContext serialize custom context values into headers?
What stays the same when a child span continues a trace?