We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Distributed Tracing

Most applications aren't as simple as Linko. If you ever work in an environment with multiple services, you'll often want to trace a request across different backend services.

Fortunately, OpenTelemetry is prepared!

Context Propagation and Trace Context

When tracing a request across services, we need to tie one service's outbound call to another service's inbound request. This is usually done by propagating trace context in HTTP request headers (for example, W3C traceparent/tracestate).

In Go code, OpenTelemetry stores that trace context in context.Context values after extracting it from inbound requests.

Trace Propagation in Go

You're already using context-aware span creation in Linko!

ctx, span := tracer.Start(r.Context(), "handleRequest")

The r.Context() already contains all the trace context – whether created earlier in the same service, or extracted from an incoming request – the span automatically becomes a child of the appropriate parent span.

If your handler makes an outbound HTTP request, use the OpenTelemetry HTTP client wrapper and pass the active request context. Then trace context will be automatically injected into outbound request headers:

client := http.Client{
	Transport: otelhttp.NewTransport(http.DefaultTransport),
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://other-service/endpoint", nil)
if err != nil {
	return err
}
resp, err := client.Do(req)
// ...