Distributed tracing 101: spans, context, propagation
One request, five processes, one id: how a trace is built, how it travels in a header, and how it breaks in two
orders calls payments over HTTP. Someone rewrites the call and forgets to forward the traceparent header. A checkout goes through and succeeds. In Tempo, what do you find?
A metric tells you that checkout p95 rose at 10:04. A log line tells you that order 4521 took 1 900 ms. Neither tells you where the 1 900 ms went across five processes, and neither can, because each process records only what it saw. A trace is the one signal designed around the request rather than the process. This chapter is about the small amount of machinery that makes it work: an id, a parent id, a header, and a decision made once at the top.
Spans and traces
A span is a timed operation with a name: GET /checkout, POST /charge, INSERT orders, GET redis. It has a start and an end timestamp, so it has a duration. It has a span id, 8 bytes, random. It has a trace id, 16 bytes, shared by every span in the same request. And it has a parent span id, which is the id of the span that was active when it started, or empty for the root span, the first span of the request.
That is the whole structure. A trace is the set of spans sharing one trace id, and the backend draws them as a tree by following parent ids. Drawn against time, the tree becomes the waterfall you see in Tempo or Jaeger: each child starts after its parent starts and ends before its parent ends, and the horizontal gaps are where time went.
For a checkout in the demo app, the tree is:
gateway GET /checkout [server] ──────────────────────── 212 ms
gateway POST http://orders:8081/orders [client] ───────────────────── 198 ms
orders POST /orders [server] ──────────────────── 195 ms
orders INSERT orders [client] ── 4 ms
orders INSERT order_items [client] ── 3 ms
orders POST http://payments:8082/charge [client] ────────────── 168 ms
payments POST /charge [server] ──────────── 165 ms
payments GET redis [client] ─ 1 ms
payments SET redis [client] ── 2 ms
orders UPDATE orders [client] ─ 2 ms
Ten spans, five processes if you count Postgres and Redis as the leaves they are. (Tempo shows the database and Redis spans by operation, INSERT, UPDATE, GET, SET, and the client spans as POST; the names above add the table or URL for reading.) Read it and you know, without a hypothesis, that payments took 165 of 212 ms and that the database was 9 ms. No combination of per-service metrics gives you that sentence about one request.
Each span also carries:
- Attributes: key/value pairs describing the operation.
http.request.method=POST,http.response.status_code=200,db.system=postgresql,user.id=42,order.items=3. This is where high cardinality lives and is welcome: a trace backend indexes or scans attributes per span, and a user id on a span costs nothing like a user id on a metric. - Events: timestamped annotations inside the span. “cache miss” at +3 ms, “retry 2” at +120 ms. An exception recorded with
record_exceptionis an event with the stack trace as attributes. Use an event when the moment matters and an attribute when it does not. - Status:
Unsetby default,Errorwhen the operation failed, andOkonly when a developer explicitly asserts success, which is rare. A 500 setsError; a 404 on a server span does not, because the server did what it was asked. - Kind: one of
SERVER,CLIENT,INTERNAL,PRODUCER,CONSUMER.INTERNALis the default. The kinds tell the backend how to pair spans: aCLIENTspan in one process and theSERVERspan in the next are the two sides of one network call, and the gap between their durations is the network.PRODUCERandCONSUMERare the same idea for a message that is handled later, where the consumer may start after the producer has finished.
Context and the traceparent header
The parent id is the trick. For orders to set its server span’s parent to the gateway’s client span, the gateway has to tell orders which span id it was in. That information is the context: trace id, span id, and flags. Propagation is moving it across a process boundary, and the W3C standardised how, in a header called traceparent:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ │ │ │
│ trace-id, 16 bytes parent-id, 8 bytes: the
version 00 sender's current span id
trace-flags:
bit 0 = sampled
The sender writes its current span id into parent-id and sends the header. The receiver reads it, starts a server span with that parent, and the tree joins. A second header, tracestate, carries vendor-specific key/value pairs and you can ignore it for a long time.
In OpenTelemetry, every HTTP client instrumentation calls inject(headers) before sending and every server instrumentation calls extract(headers) before handling. When you write the call yourself, you do it yourself:
from opentelemetry import trace
from opentelemetry.propagate import inject, extract
# client side (orders → payments)
headers = {}
inject(headers) # adds traceparent (and tracestate if any)
r = httpx.post(f"{PAYMENTS_URL}/charge", json=body, headers=headers)
# server side (payments)
ctx = extract(request.headers) # a Context holding the remote span
with tracer.start_as_current_span("POST /charge", context=ctx,
kind=trace.SpanKind.SERVER) as span:
...
inject reads the current span from the context the SDK keeps for the running thread or task. In Python that is a contextvars variable; in Java a thread-local; in Go you pass ctx by hand everywhere, which is tedious and never breaks. In Python it breaks exactly where contextvars do not follow the work.
Propagation through async boundaries
In-process propagation works because the SDK knows what “the current span” is. That knowledge is attached to the execution unit: a thread, an asyncio task. await keeps it, because the task is the same task. These lose it:
- A new thread, or a thread pool:
ThreadPoolExecutor.submit(fn)runsfnwith an empty context. The spansfncreates become new roots. The fix is to capture the context before the hand-off and attach it inside:ctx = context.get_current()thentoken = context.attach(ctx)in the worker. - A background task that outlives the request:
asyncio.create_taskcopies the current contextvars at creation, so the span is inherited, but the parent span ends when the response is sent and the child ends later, which backends draw as a child longer than its parent. Use a span link instead of a parent: a new root with a link to the request’s span. - A queue: the producer writes to Kafka or Redis and the consumer runs on another machine a second later. There is no header. You put the context into the message itself:
inject(message.headers)on the producer,extracton the consumer, and the consumer span’s kind isCONSUMER. Most teams make it a link rather than a child, because a consumer span that starts an hour after its parent ended tells a misleading story as a tree. - A retry library or a client that strips unknown headers. Some proxies and some HTTP clients copy only a whitelist. A trace that always breaks at one hop is a header being dropped there, and the lab reproduces it.
The rule that covers all of these: context moves only if something moves it. Nothing infers it from timing or from the socket.
What a trace shows that nothing else does
A dashboard aggregates; a trace is one request. That makes it the only signal that shows the critical path: the sequence of spans that, if any one were shorter, would make the whole request shorter. In the checkout above, the critical path runs gateway → orders → payments → Redis SET. Making the Postgres inserts twice as fast changes nothing the user can feel; making payments 20 ms faster changes everything.
It also shows shape. A request that runs five queries in series looks like five short bars in a staircase; the same five in parallel look like five bars stacked at the same x position. A request with an N+1 looks like a row of N identical child spans under one parent, each a millisecond, adding up to something a user notices. You cannot see any of this in a histogram, because a histogram has thrown away which request the observations came from. And it shows absence: a 400 ms gap in the waterfall where no child span exists is time spent in code nobody instrumented, which is often the answer.
What a trace does not show is how often. One slow trace is an anecdote. The way out is to query traces in aggregate, which TraceQL lets you do in Tempo: { resource.service.name = "orders" && span:duration > 500ms } returns every matching trace in the window, and that count is a number you can trust in the way a metric is. Module three’s chapter on debugging with traces takes this further, through exemplars that link a histogram bucket to the traces that landed in it.
The sampling decision
A trace with ten spans for every one of a service’s 5 000 requests per second is 50 000 spans per second, each a few hundred bytes, which is tens of gigabytes a day before you have a second service. Nobody keeps all of it. Something decides which traces to keep, and the place it is decided matters.
In head sampling, the root span’s SDK decides when the trace starts: keep 10 % at random, say. The decision is written into the sampled bit of trace-flags, and every downstream service uses a parent-based sampler that reads the bit and follows it. The result is that a kept trace is kept whole and a dropped trace is dropped whole, which is what you want; a trace with a missing middle is worse than none. The cost is that the decision is made before anything has happened, so a 10 % sampler drops 90 % of the errors and 90 % of the slow requests along with 90 % of the boring ones.
Tail sampling moves the decision to the Collector, which buffers every span of a trace for a few seconds and then keeps the trace if any span had an error or exceeded a duration. It sees the whole story before choosing. It costs memory, it needs all spans of a trace to reach the same Collector instance, and it is module four’s problem. For the lab stack the sampler is always_on and the root makes the decision for every request: keep it.
The one thing to carry away: a downstream service never makes its own sampling decision unless the header is missing. Which is the second symptom of broken propagation, after the split: payments starts sampling on its own, at its own rate, and its half of the trace appears for requests the gateway dropped.
Start the stack with the OpenTelemetry SDK enabled and JSON logs, so every log line carries its trace id:
cd labs/observability
OTEL_SDK_DISABLED=false LOG_FORMAT=json docker compose --profile telemetry up -d1. Send one checkout and capture its trace id.
curl -s 'http://localhost:8080/checkout?user=42&items=3' | jq .
docker compose logs --no-log-prefix gateway | grep '"user": 42' | tail -1 | jq -r .trace_id{"order_id": 1234, "status": "paid", "ms": 212} or similar. The second command prints a 32-character hex string: the trace id the gateway’s root span was given, which the JSON logger added to the line because the span was current when the line was written. The load generator also sends user 42 occasionally, so take the last line.2. Open the trace in Tempo. In Grafana at http://localhost:3000 (admin / admin), go to Explore, pick the Tempo data source, choose the TraceQL tab and paste the id as a bare query (an id on its own is a trace lookup). Or search instead:
{ resource.service.name = "gateway" && span.http.route = "/checkout" && span.user.id = 42 }GET /checkout (gateway, SERVER) at the top; under it the gateway’s CLIENT span POST to orders, made by the httpx auto-instrumentation; POST /orders (orders, SERVER); three Postgres CLIENT spans with db.system=postgresql (INSERT, INSERT, UPDATE); the orders CLIENT span POST to payments, which orders opens by hand; POST /charge (payments, SERVER); and two Redis spans, GET and SET, with db.system=redis. user.id is an integer attribute, which is why the query compares it without quotes. Click the orders server span: the attributes include http.method=POST, http.status_code=200 (the instrumentations’ default, older names; the OpenTelemetry chapter switches them) and order.items=3. Note the duration of each level: the gateway span is a few milliseconds longer than the orders span, which is a few longer than payments. Those differences are the network and the serialisation.3. Read the headers that made it happen. Ask the gateway to show what it sent downstream by watching orders’ access log, then send one more checkout:
docker compose logs -f --no-log-prefix orders &
curl -s 'http://localhost:8080/checkout?user=42&items=1' > /dev/null
kill %1request line for route=/orders carries a trace_id field that matches the gateway’s for the same request, and a span_id that is different: it is orders’ own server span, whose parent is the gateway client span id that arrived in traceparent. The lab does not log request headers; the header itself was 00-<trace id>-<gateway span id>-01, and the final 01 is the sampled bit, set because the default sampler is parent-based always-on.4. Break propagation. Open services/orders/app.py and find the call to payments. Orders does not auto-instrument httpx; it opens its own CLIENT span and injects the context by hand:
with tracer.start_as_current_span("POST", kind=SpanKind.CLIENT) as call:
...
headers = {}
inject(headers) # adds traceparent; delete this line and payments starts a new trace
try:
resp = await client.post(f"{PAYMENTS_URL}/charge", json=charge, headers=headers)Comment out the inject line:
headers = {}
# inject(headers) # <- propagation off: payments receives no traceparent
try:
resp = await client.post(f"{PAYMENTS_URL}/charge", json=charge, headers=headers)Rebuild orders and send a checkout:
OTEL_SDK_DISABLED=false LOG_FORMAT=json docker compose --profile telemetry up -d --build orders
curl -s 'http://localhost:8080/checkout?user=42&items=3' | jq .
docker compose logs --no-log-prefix gateway | grep '"user": 42' | tail -1 | jq -r .trace_idOpen the new trace id in Tempo.
{ resource.service.name = "payments" && span:kind = server }, and sort by time: the newest result is a three-span trace with a different trace id, rooted at POST /charge, with the Redis spans under it. Same request, two traces, and nothing in either one names the other. The checkout itself succeeded; propagation is not on the request path, which is why this breaks silently in production.5. Restore it and prove the join.
git checkout -- services/orders/app.py
OTEL_SDK_DISABLED=false LOG_FORMAT=json docker compose --profile telemetry up -d --build orders
ORDER=$(curl -s 'http://localhost:8080/checkout?user=42&items=3' | jq .order_id)
for s in gateway orders payments; do
docker compose logs --no-log-prefix $s | grep "\"order_id\": $ORDER," | tail -1 | jq -r .trace_id
doneinject, add OTEL_PROPAGATORS: b3multi to the orders service’s environment: block only in compose.yaml and run OTEL_SDK_DISABLED=false LOG_FORMAT=json docker compose --profile telemetry up -d orders (the image already includes opentelemetry-propagator-b3). Orders now reads and writes B3 headers (X-B3-TraceId, X-B3-SpanId), the gateway and payments still speak W3C. The trace splits twice: gateway’s client span has no child, orders becomes a new root, and payments becomes a third root because it ignores the B3 headers orders sent. Three traces for one request, all of them correct and none of them useful. This is the shape of a trace in an organisation where one team adopted a different tracing library, and it is why the propagator is a platform-wide setting, not a service-level one. Delete the line and run the same command again; later chapters assume W3C everywhere.orders publishes an 'order.paid' event to a queue after checkout. A fulfilment worker consumes it between 50 ms and 40 minutes later, depending on backlog, and runs for 2 s. The team wants fulfilment visible in tracing. How should the consumer's span relate to the checkout trace?
- PAPER Dapper, a Large-Scale Distributed Systems Tracing Infrastructure Sigelman, Barroso, Burrows et al., 2010
The paper that defined the model every tracer since has copied: spans, trace ids, parent ids, annotations, and sampling at the root. Still the clearest statement of why ubiquity and low overhead beat completeness. Read: sections 2 (the model) and 3 (instrumentation and the trace id in the RPC); skim 4 on sampling for the 1 in 1024 figure and the reasoning.
- DOC Trace Context, Level 1 W3C, 2021
The specification of traceparent and tracestate: the exact byte layout, what to do with a header you cannot parse, and the sampled flag. Read sections 3.2 and 3.3; the rest is for people writing a propagator.
- DOC OpenTelemetry: Traces
The vocabulary this chapter uses, as OTel defines it: span context, attributes, events, links, status and kind, with the advice to set attributes at span creation so samplers can see them.
- DOC OpenTelemetry: Context propagation
Short page on what context is and how propagators inject and extract it. It names W3C TraceContext as the default, which is why the lab's split happens when one service deviates.
- DOC OpenTelemetry Tracing API specification
The normative definitions: the five SpanKinds and when each applies, the three status codes and their precedence, and what a span must carry. Use it to settle arguments; do not read it end to end.
- CODE opentelemetry.propagate (Python API)
The inject and extract signatures used in the lab, and how to hand them a custom getter or setter when the carrier is not a dict of headers, such as a message envelope.
- DOC Tempo: Construct TraceQL queries
The query language you used in the lab: resource and span attribute scoping, the span:duration, span:kind and span:status intrinsics, and structural operators for asking about parent and child spans.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.