Reliability and security · L2Distributed tracing in practice

Distributed tracing in practice

A trace shows where one request spent its time across many services. Learn to pass the trace ID along and read the waterfall.

L2 SeniorReliability and security18 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

What broke

In 2020, Logz.io received reports that its product was slow. It happened mostly between 2 PM and 7 PM, when European and American customers were online together. Their own staff saw the same slowness 1.

Logs showed slow endpoints in that window. They also showed a growing number of calls to an internal service that serves user session tokens from the database. Metrics showed big database commits and replication lag at the same times 1. Both said that something was wrong. Neither said where.

The team then filtered traces to show only requests slower than 5 seconds. At peak times, almost every endpoint was slow when it fired a search request 1. The obvious suspect was Elasticsearch, the search database.

The trace said no. Matched with its logs, it showed that the Elasticsearch query took only 15 ms 1. With Elasticsearch ruled out, the team found the cause in the session token service: too many requests reached it 1.

The fix was a two-line change to the session token cache's eviction policy. Calls to that service dropped by more than 80%, and latency fell on all affected endpoints 1. The trace ruled out Elasticsearch, so the team could look elsewhere.

Section 2 of 8

The idea in simple words

A trace is the story of one request as it moves through your services. It is made of spans. Each span is one piece of work with a name, a start time and an end time 3.

Spans form a tree. The first span is the root span and has no parent. Every other span stores its parent span ID. All spans in the tree share one trace ID 3. Google described this tree of spans in its Dapper paper in 2010 11. OpenTelemetry uses the same model today 3.

A span can carry more detail 3:

  • Attributes: key-value pairs, like cart.items = 5 or http.route = /checkout.
  • Events: a named moment with a timestamp inside the span, like "retry started".
  • Status: Unset (the default, meaning no error), Error, or Ok when the developer marks success on purpose.
  • Links: a pointer to another span, often in a different trace, that is causally related to this one.

Your tool draws the spans as a waterfall: one bar per span, placed on a time line. Child bars sit under their parents.

The key idea. Metrics and logs tell you that a request is slow. A trace shows which span used the time. Read the critical path first: it is the only place where saving time makes the request faster.

Section 3 of 8

How it works

Passing the trace ID along

For one trace to cover many services, each call must carry the trace ID and the caller's span ID. This is context propagation 4. Instrumentation libraries usually do it for you. OpenTelemetry's default uses the W3C Trace Context headers 4.

The main header is traceparent 2:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             │  │                                │                └ trace-flags
             │  │                                └ parent-id (16 hex)
             │  └ trace-id (32 hex)
             └ version
  • version is 00 today. The value ff is invalid 2.
  • trace-id is 16 bytes as 32 lowercase hex characters. All zeros is invalid 2.
  • parent-id is 8 bytes as 16 lowercase hex characters: the caller's span ID 2.
  • trace-flags is 8 bits. Only the lowest bit is defined: 01 means the caller may have recorded this trace ("sampled") 2.

When a service receives a valid traceparent, it keeps the trace ID. Before it calls the next service, it sets a new parent-id: the ID of its own current span. This is the normal case 2. If the header is invalid, the service starts a new trace 2. A second header, tracestate, carries vendor-specific data 2.

Step through one checkout request. Use Next and Back, or the ← and → keys.

One checkout request as a trace waterfall: find the critical path, then shorten it0400 ms gatewaytraceparent: 00-4bf9…4736-…-01same trace ID in every span below cartpricing→ stock call db × 5N+1: same query, once per item stock svc40 ms gap: queue wait, not traced critical path: cart → pricing → stockpricing alone: 240 of the 400 ms pricingstock✓ about 150 ms in total SeniorPath
  1. A user taps Pay. The gateway starts a trace and creates the root span. It sends the trace ID to each service it calls, in the traceparent header. The bar shows the whole request: 400 ms.
  2. The gateway calls cart, then pricing, then stock, one after the other. Each call is a child span of the root. Pricing and stock both need only the cart, so they did not have to wait for each other.
  3. Open the pricing span. It runs the same database query five times, once per item in the cart. That is the N+1 pattern: many small calls in a row where one batched call would do.
  4. The gateway's call to stock starts at 300 ms. The stock service's own span starts at 340 ms. Nothing is recorded in between. A gap like this often means waiting in a queue or code that has no spans.
  5. The critical path is the chain of spans that sets the total time. Here it is cart, then pricing, then stock, because each call waits for the one before. Pricing takes 240 of the 400 ms, so start there.
  6. The fix: load all prices in one query, and call pricing and stock in parallel. The new waterfall is about 150 ms, because the two calls now overlap.
Step 1 of 6

Across a queue

A message may wait in a queue for minutes. One consumer may also process many messages in one batch. So OpenTelemetry's messaging rules say the producer should attach a creation context to each message, for example in the message headers 8. The consumer then adds a span link to it by default, not a parent. A span can have only one parent, but it can link to every message in a batch 8. For one message at a time, using the producer as parent is allowed 8. See Queues vs logs for how messages move.

from opentelemetry import trace
from opentelemetry.propagate import inject, extract

tracer = trace.get_tracer("orders")

with tracer.start_as_current_span("publish order", kind=trace.SpanKind.PRODUCER):
    headers = {}
    inject(headers)                 # adds traceparent of this span
    queue.publish(body, headers=headers)

# consumer
ctx = trace.get_current_span(extract(msg.headers)).get_span_context()
with tracer.start_as_current_span("process order", kind=trace.SpanKind.CONSUMER,
                                  links=[trace.Link(ctx)]):
    handle(msg)

Where the spans come from

OpenTelemetry has two ways to instrument code 5. Zero-code instrumentation records spans from the libraries you already use, such as web frameworks and database clients. Code-based instrumentation uses the API to add spans for your own business logic. You can use both at once 5.

The API is what libraries depend on. It has no effect until the application also adds the SDK 5. The SDK is the part that records and exports spans. OpenTelemetry recommends sending spans to an OpenTelemetry Collector running next to the service 6. It can retry, batch, filter sensitive data and send to one or more backends 6.

Reading the waterfall

Open a slow trace from your tail latency graph and look for four shapes:

  1. The critical path. Follow the chain of spans that ends last. Only shortening these spans shortens the request.
  2. Calls in a row that do not depend on each other. They could run in parallel.
  3. N+1 calls. The same short span repeats many times, once per item. Replace them with one batched call.
  4. Gaps. Time where no span is recorded. It is often queue wait, a busy thread pool, or code without spans.

To estimate if a span's time is reasonable, compare it with latency numbers.

Section 4 of 8

Trade-offs

You rarely keep every trace. There are two ways to choose: head sampling decides when the request starts, and tail sampling decides after the trace ends 7.

ChoiceKeeps rare slow and error traces?CostUse it when
Keep every traceYes Very high at scale.Low traffic: tens of traces per second or fewer 7.
Head-based sampling (for example 5%)Not reliably. It decides at the start 7.Low. Easy to set up.You need a cheap first step. Dapper kept about 1 trace in 1,024 and still had enough data for busy services 11.
Tail-based samplingYes It can keep every error and every slow trace 7.High. Needs stateful collectors that hold spans until the trace ends 7.You must catch rare failures, and you can run the extra servers.
Head first, then tailOnly among the traces the head sampler kept.Medium.Very high volume: head sampling protects the pipeline, tail sampling picks the useful traces 7.

The sampled flag in traceparent carries the caller's decision to the next service, so all services keep or drop the same trace 2.

Section 5 of 8

At work: how a senior uses this

  • Put the trace ID in every log line. Then a slow trace leads you straight to that request's logs. OpenTelemetry SDKs can add it for you 4. The debugging lesson shows how to use it during an incident.
  • Turn on exemplars on latency histograms. An exemplar stores the trace ID of one real request with the metric point 9. In tools that support it, you click a spike on the p99 graph and land on a slow trace.
  • Put high-cardinality data, like user ID or order ID, on span attributes. Never put it in metric labels. Each new combination of label values creates a new time series, so storage and cost grow 10.
  • Check every hop for broken propagation. A proxy or API gateway that drops unknown headers cuts the trace in two. Test it: send a request and confirm one trace ID in all services.
  • Watch thread pools and async code. Dapper kept the trace context in thread-local storage. It had to copy that context into every callback sent to a thread pool 11. Most OpenTelemetry SDKs, or the language's own context tools, can carry the context into a task. Check yours.
  • Expect clock skew. Spans from different hosts use different clocks 11. A child that seems to start before its parent is usually a clock problem, not a bug.
  • Do not trust incoming trace headers from the internet. An attacker could set sampled on every request and run up your tracing bill 2. Start a new trace at your edge.
  • During an incident, compare a slow trace with a fast one for the same endpoint. The span that differs is your best lead.
Section 6 of 8

With AI

What to ask the agent

"Add OpenTelemetry to this Python service. Use zero-code instrumentation for Flask, requests and psycopg. Add one manual span around price_cart with the item count as an attribute. Export to a local Collector over OTLP."

"Here is a trace as JSON. List the spans on the critical path, any repeated spans that look like N+1 calls, and any gaps longer than 10 ms between a parent and its first child."

"This worker reads from a queue. Show how to inject trace context into the message headers on publish and add a span link on consume."

What to check yourself

  • The traceparent header really reaches the next service. Agents often forget proxies, queues and thread pools.
  • The trace ID is in your logs, in the same format your tracing tool shows.
  • No user ID, email or order ID ends up as a metric label.
  • Span attributes contain no passwords, tokens or personal data.
  • The sampling setup matches your goal. Head sampling alone will not keep every error trace.
  • The service ignores or restarts trace context from untrusted callers.
Section 7 of 8

Check yourself

1. A service receives traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 and calls the next service. What should it send?

Show answer

The same trace ID, a new parent ID (its own span ID), and the flags. The trace ID stays the same for the whole request. The parent ID must change to the ID of the current operation, so the next span knows its parent.

2. A trace shows 40 ms between the start of a client span and the start of the matching server span. Nothing else is recorded there. What is the most likely cause?

Show answer

Waiting that has no span, such as a queue, a proxy or a full thread pool. A gap means time passed that nobody recorded. Queue wait and code without instrumentation are the usual causes. A slow database call would show up as its own span. Clock skew can also shift a server span, so check that if the gap looks odd.

3. You want to keep every trace that has an error, while storing only 5% of normal traces. Which approach can do this?

Show answer

Tail-based sampling. Head-based sampling decides at the start, before anyone knows the request will fail. Only a decision made after the trace ends can look for errors.

4. In a waterfall, a request takes 500 ms. A cache call takes 20 ms and runs in parallel with a 300 ms pricing call. Nothing else runs at the same time. Which change makes the request faster?

Show answer

Making the pricing call 100 ms faster. The pricing call is on the critical path. The cache call already finishes while pricing is still running, so making it faster changes nothing.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 11 sources and related lessons
  1. Avi Froelich, “Cracking Production Performance Issues with Open Source Observability”, Logz.io blog (23 September 2020) (opens in a new tab)
    A real slowdown at peak hours, and how traces ruled out the obvious suspect before the team found a cache setting.
  2. W3C, Trace Context, W3C Recommendation (23 November 2021) (opens in a new tab)
    The exact format of the traceparent and tracestate headers, and what each service must do when it receives them.
  3. OpenTelemetry documentation: Traces (opens in a new tab)
    Spans, parent IDs, attributes, events, links, status and span kinds, with JSON examples.
  4. OpenTelemetry documentation: Context propagation (opens in a new tab)
    How the trace ID and span ID travel from service A to service B, and how logs pick them up.
  5. OpenTelemetry documentation: Instrumentation (opens in a new tab)
    Zero-code and code-based instrumentation, and why libraries depend only on the API.
  6. OpenTelemetry documentation: Collector (opens in a new tab)
    What the Collector does and why the project recommends running one next to your services.
  7. OpenTelemetry documentation: Sampling (opens in a new tab)
    Head sampling versus tail sampling, with the costs and limits of each.
  8. OpenTelemetry semantic conventions: Semantic conventions for messaging spans (opens in a new tab)
    How a producer attaches context to a message, and why consumers use span links by default.
  9. OpenTelemetry specification: Metrics Data Model (opens in a new tab)
    The Exemplars section explains how a metric point can carry a trace ID.
  10. Prometheus documentation: Metric and label naming (opens in a new tab)
    Why every new label value makes a new time series, and why user IDs do not belong in labels.
  11. Benjamin H. Sigelman et al., “Dapper, a Large-Scale Distributed Systems Tracing Infrastructure”, Google Technical Report dapper-2010-1 (April 2010) (opens in a new tab)
    The Google paper behind most modern tracing tools. Read sections 2 and 4 for span trees, thread pools, clock skew and sampling.

Related: Observability, SLOs and error budgets · Debugging production · Tail latency and queueing · Incident response and postmortems · Queues vs logs and delivery guarantees

Before this lesson: Observability and SLOs covers metrics, logs and error budgets. Next, use traces to find slow requests in Tail latency and queueing.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper