Skip to content

Tracing

Traces as request lifecycles across service boundaries: spans, context propagation, and sampling with OpenTelemetry.

Traces capture the lifecycle of a request as it crosses service and process boundaries: which service called which, what work each one did, and where time was spent. A single trace is a tree of spans: each span is one unit of work, linked to its parent by a shared trace_id.

Where metrics tell you that p99 latency spiked, and logs tell you what happened during a request, traces tell you where the time went and which dependency caused it. They are the primary tool for debugging latency and understanding how services depend on each other at runtime.

OpenTelemetry is the vendor-neutral standard for distributed tracing: one API and SDK, pluggable exporters for Jaeger, Grafana Tempo, Honeycomb, Datadog, and any OTLP-compatible backend. Use it for all tracing instrumentation; there is no reason to reach for a vendor-specific SDK.

Concepts

A trace is a tree of spans. Each span represents one unit of work: an HTTP handler, a database query, a cache lookup. Every span in a trace shares the same trace_id; each span has its own span_id and a parent_span_id pointing to the span that created it.

trace_id: 4bf92f3577b34da6a3ce929d0e0e4736

[HTTP POST /orders          ] 0ms–142ms  ← root span
  [auth.ValidateToken       ] 1ms–8ms
  [db.InsertOrder           ] 9ms–98ms
    [db.Begin               ] 9ms–11ms
    [db.Exec (INSERT)       ] 12ms–95ms  ← slow; worth investigating
    [db.Commit              ] 96ms–98ms
  [queue.Publish            ] 99ms–138ms

Setup

import (
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
    "go.opentelemetry.io/otel/propagation"
    "go.opentelemetry.io/otel/sdk/resource"
    "go.opentelemetry.io/otel/sdk/trace"
    semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

func setupTracing(ctx context.Context, serviceName string) (func(context.Context) error, error) {
    exp, err := otlptracehttp.New(ctx) // reads OTEL_EXPORTER_OTLP_ENDPOINT from env
    if err != nil {
        return nil, err
    }
    tp := trace.NewTracerProvider(
        trace.WithBatcher(exp),
        trace.WithResource(resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceName(serviceName),
        )),
        trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(0.1))),
    )
    otel.SetTracerProvider(tp)
    otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
        propagation.TraceContext{},
        propagation.Baggage{},
    ))
    return tp.Shutdown, nil
}

Call it at startup and defer the shutdown function to flush any buffered spans:

shutdown, err := setupTracing(ctx, "orders-service")
if err != nil {
    log.Fatal(err)
}
defer shutdown(ctx)

OTEL_EXPORTER_OTLP_ENDPOINT configures the collector URL without code changes; set it in your deployment environment.

Creating spans

var tracer = otel.Tracer("orders-service")

func (s *Service) CreateOrder(ctx context.Context, req CreateOrderRequest) error {
    ctx, span := tracer.Start(ctx, "CreateOrder")
    defer span.End()

    span.SetAttributes(
        attribute.String("order.customer_id", req.CustomerID),
        attribute.Int("order.item_count", len(req.Items)),
    )

    if err := s.db.Insert(ctx, req); err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
        return err
    }
    return nil
}

Pass ctx through every function call so child spans can attach to the correct parent. Never store a span in a struct field.

HTTP instrumentation

Use the OTEL contrib middleware instead of hand-rolling span creation for every handler. It extracts incoming trace context, starts a server span, and injects trace_id into the response.

import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

mux := http.NewServeMux()
mux.HandleFunc("/orders", s.handleOrders)

// wraps the entire mux; span name defaults to the matched route pattern
handler := otelhttp.NewHandler(mux, "server",
    otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
)

For outgoing HTTP calls, wrap the client transport:

client := &http.Client{
    Transport: otelhttp.NewTransport(http.DefaultTransport),
}

Context propagation

Traces cross service boundaries via the W3C traceparent header:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
              ^^ trace-id (32 hex)                 parent-span-id    flags

The OTEL contrib middleware handles extraction and injection automatically. For manual cases (message queues, async workers):

// inject into outgoing message headers
otel.GetTextMapPropagator().Inject(ctx, propagation.MapCarrier(headers))

// extract from incoming message headers
ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(headers))

Sampling

Recording every span at high throughput is expensive. The recommended strategy is parent-based, head-sampling:

// sample 10% of new traces; always match the parent's decision for existing traces
trace.ParentBased(trace.TraceIDRatioBased(0.1))
  • If an incoming request carries a sampled flag in its traceparent, honor it.
  • For root spans (no parent), sample the configured fraction.
  • Always sample errors, regardless of rate, by adding a custom sampler or marking spans as errors and handling them at the collector.

Span naming and attributes

  • Use verb noun or object.action: "db.Query", "cache.Get", "CreateOrder".
  • Avoid high-cardinality values in span names ("GET /users/12345" → use an attribute for the ID, keep the name "GET /users/:id").
  • Follow OTEL semantic conventions for well-known attributes: db.system, http.request.method, rpc.service, etc. Backends use these to build automatic dashboards and service maps.

Type to search…

↑↓ navigate↵ selectEsc close