Observability and SREVol. 9 · Part IX
0 / 0

Shelves / Observability and SRE

OB·101

Distributed Tracing

Distributed tracing from first principles: traces and spans, parent/child relationships and span kinds, reading a waterfall to find critical paths, context propagation over HTTP, gRPC and messaging, keeping context across async boundaries (thread pools, coroutines, callbacks, queues, batch jobs) with span links, sampling strategies and their effect on analysis, cross-service traces through proxies, databases and third parties, trace analytics (service maps, span metrics, TraceQL), and common pitfalls, with code in Java, Go, Python, Rust and Node.

25 topics · ~17 min read · 28-question quiz
Updated Suggest a correction

Start here: following one request through many services

A trace is a tree of timed steps

When an order arrives, orders validates it and calls kitchen, which queries stock and reserves ingredients. Each step is a span: a name, a start time, a duration, attributes, a status, and the ID of its parent span. All spans of one request share a trace ID:

Text
a slow biryani order (durations rounded)        0 ms                                        930 ms
GET /order                    (orders)  ████████████████████████████████████████████████████  930 ms
  validate order              (orders)  █                                                        2 ms
  call kitchen                (orders)   ███████████████████████████████████████████████████  925 ms
    GET /cook                 (kitchen)  ███████████████████████████████████████████████████  920 ms
      SELECT stock FROM …     (kitchen)  ██████████████████████████████████████████████████   900 ms
      reserve ingredients     (kitchen)                                                    █    5 ms

Reading it is the skill: the parent spans are long because a child is long, so you look for the deepest span that accounts for the time. Here it's the database query, not the network or the kitchen's own code.

The tree only exists if every hop passes the context on

orders adds the traceparent header when it calls kitchen; kitchen reads it and makes its span a child of call kitchen. Remove that one line (the lab did, with a switch in the service) and the picture falls apart:

Text
context propagated:   1,000 requests → 1,000 traces with spans from both services
propagation broken:   1,000 requests → 1,000 orders-only traces of 3 spans + 1,000 separate kitchen traces
                      traces containing both services: 0 of 1,000

Nothing errors and nothing warns: you just get half-traces that end at call kitchen and can't tell you why it was slow. Every proxy, queue, thread pool and async callback on the path has to carry the context (this chapter shows how).

You can't keep every trace, so you choose which

Each request here made 6 spans; at thousands of requests per second that's a lot of data. Sampling keeps some traces. Where the decision is made matters enormously:

Text
head sampling, 10% decided at the start:   kept 93 traces: errors 2 of 24, slow 2 of 64
tail sampling, decided after it finished:  kept 138 traces: errors 18 of 18, slow 68 of 68, plus 5% of the rest

Head sampling decides when the request starts, before anyone knows how it will go, so it throws away 90% of the failures too. Tail sampling waits until the trace is complete and keeps every error and every slow trace plus a small random share of normal ones, which are exactly the traces you want when investigating.

How deep to go in distributed tracing

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain traces, spans, parents and why context must propagate
L2 Read a waterfall to find the slow or failing step; add manual spans
L3 Propagate context across async, queues and proxies; choose a sampling strategy
L4 Diagnose broken traces, sampling bias and missing spans; run tail sampling
L5 Design tracing for a large system: sampling tiers, links, trace-aware load balancing, cost
L6 Run tracing as a platform: conventions, coverage targets, analytics from traces

Traces and spans

Where tracing came from

Google's Dapper paper (2010) described tracing every request through thousands of services with low overhead, using sampling and context propagation. Twitter's Zipkin (2012) and Uber's Jaeger (2016, CNCF graduated) brought it to everyone, followed by OpenTracing/OpenCensus and now OpenTelemetry (chapter 98).

The model

  • A trace represents one end-to-end operation (usually a request), identified by a 128-bit trace ID.
  • A span represents one unit of work within it: an HTTP handler, a DB query, a call to another service, a function you chose to instrument. Each span has:
  • span ID, parent span ID (none for the root span);
  • name, start and end timestamps (duration);
  • kind: SERVER (handling an incoming request), CLIENT (making an outgoing call), PRODUCER/CONSUMER (messaging), INTERNAL;
  • attributes (key-values), events (timestamped annotations such as exceptions or "cache miss"), links (to other spans, possibly in other traces), and status (UNSET/OK/ERROR).

Spans form a tree via parent IDs, and the tree is displayed as a waterfall (Gantt chart):

0 ms420 ms gateway GET /checkout orders POST /orders db SELECT cart inventory reserveparallel payments POST /charge fraud-score GETcritical path ⚠ 270 ms db INSERT order children nest under parents; gaps inside a parent are its own work (or uninstrumented time) critical path = longest dependent chain → optimise fraud-score first, not inventory
A trace waterfall. The root SERVER span at the gateway covers the whole request; child CLIENT spans call the orders service, whose SERVER span contains a database query and a call to payments. The critical path (the chain that determines total latency) runs through payments' fraud check; the parallel inventory call isn't on it.

Reading a trace

When debugging latency:

  1. Find the critical path: the chain of spans that actually determines end-to-end time. Speeding up work off the critical path (parallel calls that finish early) doesn't help users.
  2. Look for gaps: time inside a parent span not covered by children is either the service's own work (CPU, serialisation) or uninstrumented calls; add spans or check profiles.
  3. Look for patterns: - sequential calls that could be parallel; - N+1 queries (dozens of identical DB spans in a loop); - retries (repeated client spans); - fan-out (one request calling 50 services); - slow serialisation (long gaps before a response); - queueing (a CLIENT span much longer than the matching SERVER span: time spent waiting in a connection pool, a proxy, or the network).
  4. Compare with a normal trace for the same endpoint (backends can show span-level diffs and percentile breakdowns).

The CLIENT/SERVER span pair for one call is particularly informative: the client span's duration minus the server span's duration is network + queueing + proxy time.

Context propagation

Across services

For a trace to span services, trace context must be passed with every call, and the receiving service must extract it and make it the parent of its SERVER span (chapter 98):

Transport Carrier
HTTP traceparent / tracestate / baggage headers
gRPC Metadata entries (same keys)
Kafka, RabbitMQ, SQS, Pub/Sub, NATS Message headers / attributes (OTel messaging instrumentation injects on send, extracts on receive)
Serverless (Lambda, API Gateway) Headers, plus X-Ray headers on AWS (X-Amzn-Trace-Id); propagation through SQS/SNS/EventBridge via message attributes
Databases Usually not propagated; some support SQL comments with trace context (sqlcommenter), so slow-query logs can be linked to traces

Instrumentation libraries (HTTP clients and servers, gRPC interceptors, messaging clients) do this automatically. Breakages happen at custom transports, proxies that strip headers, legacy services without instrumentation (the trace continues but has a hole, or restarts), and third-party services (you'll see your CLIENT span but not their internals).

Across async boundaries inside a process

Context is "current" for the thread or task that's executing. When work moves to another thread, task or callback, context must move with it or the new span becomes a new root (an orphaned trace):

Language Pitfall Fix
Java ExecutorService.submit(), CompletableFuture.supplyAsync(), scheduled tasks, reactive (Reactor) pipelines The Java agent instruments common executors automatically; otherwise Context.current().wrap(runnable) / Context.taskWrapping(executor); Reactor uses context propagation library hooks; virtual threads work like platform threads (context captured at task submission)
Go Starting a goroutine without passing ctx Always pass ctx into goroutines; for work that should outlive the request (fire-and-forget), create a new root span linked to the request span, using context.WithoutCancel(ctx) to keep values but drop cancellation
Python threading.Thread, ThreadPoolExecutor, run_in_executor contextvars.copy_context().run(...), OTel threading instrumentation; asyncio tasks copy context automatically
Node.js Callbacks from libraries that break AsyncLocalStorage (custom pools, some native modules, event emitters) context.with(ctx, fn) / context.bind(ctx, fn)
Rust tokio::spawn doesn't carry the current tracing span .instrument(span) / .in_current_span() on the future
.NET Mostly automatic with Activity and async/await Watch custom thread scheduling
Java
// Java: propagate context into a custom executor (if not using the agent's automatic instrumentation)
ExecutorService pool = Context.taskWrapping(Executors.newFixedThreadPool(8));
CompletableFuture<Price> price = CompletableFuture.supplyAsync(() -> pricing.quote(cart), pool);
// The span started inside pricing.quote() now has the request span as parent.
Go
// Go: background work that outlives the request: new root span linked to the request's span
func (h *Handler) placeOrder(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    reqSpanCtx := trace.SpanContextFromContext(ctx)
    go func(bg context.Context) {
        bg, span := tracer.Start(bg, "send_confirmation_email",
            trace.WithNewRoot(), trace.WithLinks(trace.Link{SpanContext: reqSpanCtx}))
        defer span.End()
        _ = h.mailer.Send(bg, orderEmail)
    }(context.WithoutCancel(ctx))                     // keep values, don't die when the request ends
    w.WriteHeader(http.StatusAccepted)
}
Rust
// Rust: carry the current span into a spawned task
use tracing::Instrument;
let span = tracing::info_span!("recompute_recommendations", user.id = %user_id);
tokio::spawn(async move { recompute(user_id).await }.instrument(span));

Asynchronous messaging breaks the simple tree:

  • A producer sends a message with context in headers; the consumer may process it seconds or hours later, possibly in a batch of messages from many different traces.
  • Options:
  • Make the consumer span a child of the producer span (same trace). That's natural for one message → one processing step, but traces can become very long-lived.
  • Start a new trace for processing and add a span link to the producer's context. For batches, one processing span gets links to each message's span context. OpenTelemetry messaging conventions describe both, and many backends display linked traces.
trace A: publish trace B: publish trace C: publish Kafkactx in headers trace D: process batchlinks → A, B, C single message → child span is finebatch → new trace + span links
Messaging and span links. A producer span sends three messages from three different traces; a consumer processes them in one batch, so its processing span can't have three parents. Instead it starts its own trace and records a span link to each message's originating span, preserving causality.
Java
// Java: consumer batch span with links to each record's producer context
Span batchSpan = tracer.spanBuilder("orders process")
        .setSpanKind(SpanKind.CONSUMER)
        .setNoParent();
for (ConsumerRecord<String, byte[]> rec : records) {
    Context producerCtx = propagator.extract(Context.root(), rec.headers(), KAFKA_HEADERS_GETTER);
    batchSpan.addLink(Span.fromContext(producerCtx).getSpanContext());
}
Span span = batchSpan.startSpan();
try (Scope s = span.makeCurrent()) { process(records); } finally { span.end(); }

Long workflows (sagas, durable executions, data pipelines) often combine links, baggage and a business correlation ID (chapter 99), since one trace per hours-long workflow is impractical.

Sampling and its consequences

Tracing every request is usually too expensive, so traces are sampled (chapter 98 covers mechanisms). What sampling means for analysis:

  • Consistency: all services must agree whether a trace is kept, or you get broken traces (some spans missing). Parent-based head sampling honours the upstream decision; tail sampling sees all spans before deciding.
  • Counts from traces are biased unless you know the sampling rate. Compute request rates, error rates and latency percentiles from metrics (or from spans before sampling, via the span metrics connector), not from stored traces.
  • Rare paths: a 1% sample of a rarely used endpoint might keep zero traces; rate-limited per-endpoint sampling or tail policies (keep at least N per operation) help.
  • Errors and slow requests are what you need most when debugging: tail sampling policies keep them all.
  • Debug on demand: force sampling for one request with a header or baggage (sampled flag set by the edge for internal users, or a "debug" bit), useful for reproducing a customer issue.

Cross-service traces in practice

Through proxies, gateways and meshes

  • Load balancers and API gateways should forward traceparent (and ideally create their own spans): Envoy, NGINX (OTel module), Istio/Linkerd generate spans for every hop, AWS ALB adds X-Amzn-Trace-Id.
  • Service meshes can generate spans for traffic between services, but they can't propagate context through your application code: the app must still copy incoming trace headers onto outgoing requests (or use OTel instrumentation), or traces break at every service.

Databases, caches and third parties

  • Client instrumentation creates CLIENT spans for every query/command with sanitised statements (db.query.text), giving N+1 detection and slow-query attribution per endpoint.
  • Third-party APIs appear as CLIENT spans: you can't see inside, but you can measure them, alert on their latency and error rates, and prove "it's the payment provider" during incidents.
  • Browser and mobile: real user monitoring (RUM) SDKs (OTel JavaScript web, Grafana Faro, vendor RUM) start traces in the client, so a slow page load connects to backend spans (requires CORS allowing traceparent).

Serverless and managed services

  • Lambda: OTel Lambda layers or ADOT; X-Ray integration traces through API Gateway, SQS, SNS, Step Functions.
  • Managed services (queues, databases) appear as client spans; some (AWS X-Ray, Azure Application Insights) add service-side segments.

Trace analytics

Individual traces explain individual requests; aggregated across many traces, they reveal system behaviour:

  • Service maps / dependency graphs: built from span parent-child relationships (Collector servicegraph connector, Jaeger's dependency view, Tempo service graphs), showing request rates, error rates and latency on each edge, and surfacing unexpected dependencies.
  • Span metrics (RED) per service and operation, derived from spans before sampling (spanmetrics connector).
  • Trace queries: search by attributes and structure. TraceQL (Grafana Tempo) queries spans and their relationships:
Text
# TraceQL: traces where a checkout request took > 1 s and somewhere inside it the fraud service errored
{ resource.service.name = "gateway" && span.http.route = "/checkout" && duration > 1s }
  >> { resource.service.name = "fraud-score" && status = error }

# Slow DB statements called from the orders service
{ resource.service.name = "orders" && span.db.system.name = "postgresql" && duration > 200ms }
  • Comparisons: latency breakdown by span for p50 versus p99 traces ("the slow traces spend their extra time in X"), or before versus after a deploy.
  • Backends: Jaeger (with Elasticsearch, OpenSearch, Cassandra or ClickHouse storage; Jaeger v2 is built on the OTel Collector), Grafana Tempo (object storage, cheap at scale, TraceQL), Zipkin, ClickHouse-based tools (SigNoz, Uptrace), and commercial APMs.

Pitfalls and good practice

Pitfall Effect Practice
Missing service.name Everything shows as unknown_service Set it in every deployment
Raw IDs in span names Unusable aggregation, high cardinality in span metrics Use templated routes; IDs in attributes
Lost context in async code Orphan traces, broken waterfalls Use instrumented executors, pass ctx, instrument() futures
Proxies dropping headers Traces split at the proxy Configure forwarding; instrument proxies
Spans never ended Leaks, misleading durations finally/defer/with
Too many tiny spans Overhead and noise Instrument meaningful operations, not every function
Sensitive data in attributes Compliance problems Allow-list attributes; Collector redaction
Inconsistent sampling Partial traces Parent-based sampling; tail sampling at a gateway with trace-aware routing
Using traces to count Wrong rates Use metrics for counts and SLOs; traces to explain

Lab: head sampling, tail sampling and broken context

The Start Here services with lab switches: LAB_HEAD_RATIO (SDK parent-based ratio sampler), LAB_OTLP (send to a Collector instead of straight to Jaeger), LAB_FAIL_RATE=0.03 (3% of kitchen calls fail with "out of stock", so the order fails too) and LAB_NO_PROPAGATION. Each pass sent 1,000 orders from 8 concurrent clients; the services' own JSON logs are the ground truth for which requests failed or were slow. OpenTelemetry Python SDK 1.45, Collector Contrib 0.149, Jaeger 2.14.

The tail-sampling Collector

YAML
processors:
  tail_sampling:
    decision_wait: 3s          # how long to wait for a trace's spans before deciding
    num_traces: 20000          # traces held in memory at once
    policies:                  # keep the trace if ANY policy says so
      - {name: errors,   type: status_code,   status_code: {status_codes: [ERROR]}}
      - {name: slow,     type: latency,       latency: {threshold_ms: 500}}
      - {name: baseline, type: probabilistic, probabilistic: {sampling_percentage: 5}}
connectors:
  spanmetrics: {}
  forward: {}
service:
  pipelines:
    traces/in:      {receivers: [otlp], exporters: [spanmetrics, forward]}   # metrics from 100% of spans
    traces/sampled: {receivers: [forward], processors: [tail_sampling], exporters: [otlp_grpc/jaeger]}
    metrics:        {receivers: [spanmetrics], exporters: [prometheus]}

The forward connector splits the pipeline so spanmetrics sees every span before sampling: request rates and latency histograms stay exact while only 14% of traces are stored.

Results

Text
everything kept:      1000 requests, 40 errors, 57 slow | kept 1000 traces (6000 spans): errors 40/40, slow 57/57, other 903/903
head sampling 10%:    1000 requests, 24 errors, 64 slow | kept   93 traces  (558 spans): errors  2/24, slow  2/64, other  89/912
tail sampling:        1000 requests, 18 errors, 68 slow | kept  138 traces  (828 spans): errors 18/18, slow 68/68, other  52/914
propagation broken:   1000 requests, 31 errors, 69 slow | orders traces of 3 spans each; traces with both services: 0/1000

(The error counts differ between passes because the failures are random.)

What the numbers say:

  • Tail sampling stored 14% of the traces and 100% of the interesting ones. Head sampling stored 9% and kept about one error in twelve: if you're investigating "why did these 24 orders fail?", you'd find 2 examples.
  • Every kept trace was complete in both sampled passes (93/93 and 138/138 contained both services). Parent-based head sampling makes the decision once at the root and every downstream service honours the sampled flag; tail sampling keeps or drops whole traces. Neither produces half-traces, if context propagates.
  • Policy accounting: the processor's own metrics said errors sampled 18, slow sampled 68, baseline sampled 59, and 138 traces were sampled overall. The policies overlap (a slow trace can also win the 5% lottery), which is why the parts add up to more than the whole.
  • The cost of tail sampling is memory and delay: the Collector's RSS was 182 MB holding traces for 3 seconds at this low rate, and traces appear in Jaeger only after decision_wait. A trace whose spans arrive later than the wait (long-running requests, slow batch exports) is decided on partial data.

Running tail sampling for real

All spans of a trace must reach the same Collector instance, or each instance sees a fragment and decides differently. Production setups use two tiers: agents (or a first gateway layer) export with the loadbalancing exporter, routing by trace ID to a pool of tail-sampling Collectors; the pool is sized for traffic × decision wait. If you can't run that, the fallback is consistent head sampling plus "always sample" rules for things you know matter (a header set by synthetic tests, a debug flag) and span metrics for completeness.

The broken-propagation pass

With LAB_NO_PROPAGATION=1, orders called kitchen without the traceparent header. Results: 1,000 three-span orders traces ending at call kitchen, 1,000 orphan kitchen traces, and not a single error or warning anywhere. The only signals were structural: kitchen root spans with SpanKind.SERVER and no parent, and call kitchen CLIENT spans with no child. Tracing backends (and a simple query: "CLIENT spans whose trace has no matching SERVER span from the callee") can surface this; it's worth an automated check after every change to HTTP clients, proxies or message libraries.

Try it yourself

  1. Lower decision_wait to 100 ms and look for kept traces that are missing their kitchen spans.
  2. Add a string_attribute policy that always keeps traces with tiffin.dish = "biryani", and a rate_limiting policy; compare the kept counts.
  3. Combine head sampling (25%) in the SDK with tail sampling in the Collector. What fraction of errors survive, and why is this combination usually a mistake?

Revision sheet: distributed tracing

Key ideas

  • Model: trace = tree (DAG with links) of spans; span = name, kind, start, duration, attributes, events, status, parent, links.
  • Reading a trace: critical path, the deepest span explaining the time, gaps (queueing, uninstrumented work), fan-out.
  • Propagation: inject/extract at every boundary; carry context through thread pools, async tasks, queues (in message headers) and proxies.
  • Links vs parents: batch consumers and fan-in use span links.
  • Sampling: parent-based head sampling; tail sampling in a gateway with trace-ID load balancing; derive metrics before sampling.
  • Analytics: compare slow vs fast traces by attribute, service dependency maps, span metrics.

Numbers to remember

  • Lab: head 10% kept 2 of 24 errors; tail sampling kept 18/18 errors and 68/68 slow traces while storing 14% of traces; broken propagation joined 0 of 1,000 traces silently.

Pitfalls

  • A single library or proxy dropping traceparent.
  • Head sampling at low rates (losing rare errors).
  • Tail sampling without trace-aware routing; decision waits shorter than trace duration.
  • Huge spans (every SQL row, request bodies) or high-cardinality span names (IDs in names).
  • Clock skew between hosts confusing waterfalls.

Glossary

  • Span kind: SERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL.
  • Critical path: the chain of spans that determines total latency.
  • Span link: reference to a span in another trace (or a non-parent in the same one).
  • Decision wait: how long tail sampling buffers before deciding.
  • loadbalancing exporter: Collector exporter that routes spans by trace ID.