Course contents

13. Observability Lesson 3 of 6

Distributed Tracing

Spans, trace context propagation and self time: find the slow service in a call chain where every caller looks slow, and where traces break.

14 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • One user request becomes a tree of calls; a trace records it as spans with start, duration and parent.
  • Every caller’s latency includes its callees’, so one slow service makes all its callers look slow.
  • Trace context (same trace id, new parent span id per hop) travels in headers, and must also travel in message headers.
  • Look for the span with high self time; a slow span whose time is all in a child only passes the blame down.
  • Put trace ids in log lines so spans and logs link to each other.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Distributed tracing records the path of one request through a distributed system. A trace is a tree of spans; each span is a unit of work (an incoming request, an outgoing call, a database query) with a start time, a duration, attributes, a status and the id of its parent span. Displayed as a waterfall, a trace shows what ran, in which order and for how long.

Why it exists

In a microservice system, latency propagates upstream: if Payments is slow, Checkout and the gateway are slow too, because their time includes waiting. Per-service metrics all turn red at once and cannot say where the time actually goes. Logs from each service can be joined by id, but reconstructing timing from them is slow. A trace answers "where did the time go?" directly.

How it works

Instrumentation. Server and client libraries (HTTP, gRPC, database drivers, messaging clients) start and end spans automatically; developers add spans for important business steps. OpenTelemetry is the common standard.

Propagation. When a service calls another, it injects the trace context into the request. The W3C Trace Context header is traceparent: 00-<32-hex trace id>-<16-hex parent span id>-<flags>; the trace id is constant for the whole trace, the parent id is the caller's span, and the flags carry the sampling decision. A tracestate header carries vendor-specific data, and baggage can carry application key-values. The callee extracts the context and starts a child span.

Asynchronous work. For messages, inject the context into message headers at publish time. The consumer either continues the trace with a child span or starts a new trace with a span link to the producer, which suits batch consumers and work that happens long after the request finished.

Analysis. Sort a trace's spans by self time (duration minus time spent in children). The span with high self time is where work happens; a long span whose time is all inside a child is only waiting. The critical path is the chain of spans that determines end-to-end latency; speeding up anything off it does not help.

Export and storage. Spans are batched and exported (usually via an OpenTelemetry Collector) to a trace backend such as Jaeger, Grafana Tempo, Zipkin or a commercial APM. Because traces are large, they are usually sampled.

When to use it

In any system where a request crosses more than a couple of services, queues or databases, especially when latency matters or failures cascade. Also invaluable for understanding unfamiliar systems: traces document the real call graph.

When not to

  • A single monolith with one database may get most of the value from good metrics, logs and a profiler.
  • Do not use traces as the source of counts and rates when sampling is on; use metrics.
  • Very high-volume, low-value paths (health checks, static assets) are often excluded from tracing.

Trade-offs

Choice You gain You pay
Auto-instrumentation Coverage with little code Generic span names; some overhead and noise
Manual business spans Meaningful steps in the waterfall Code to maintain
Higher sampling rate More traces to investigate Network, storage, collector capacity
Child spans across queues One trace end to end Very long traces; awkward for batch consumers (links fit better)
Rich span attributes Faster filtering and grouping Cost; risk of sensitive data in attributes

Alternatives

  • Correlated logs: request ids on log lines give a poor man's trace without timing structure.
  • Metrics per dependency: client-side latency histograms per downstream call locate slow dependencies at an aggregate level.
  • Service mesh telemetry: sidecars can emit per-hop spans without code changes, but cannot see inside a service or link across async work, and still need header propagation in the app.
  • Continuous profiling for "which function is slow" inside one service.

Failure modes

  • Broken context: a hand-written HTTP client, a thread pool or a queue that does not carry the context splits one request into orphan traces.
  • Clock skew: spans from different hosts with drifting clocks appear to start before their parents; backends adjust, but durations within a host stay reliable.
  • Sampling hides the problem: the rare failing request was not sampled (see tail sampling in the OpenTelemetry lesson).
  • Span explosion: a span per loop iteration produces traces with thousands of spans and high cost.
  • Blaming the wrong span: picking the longest span rather than the one with the most self time.

In production

Use OpenTelemetry SDKs and auto-instrumentation, propagate W3C Trace Context everywhere (including message headers), name spans by operation (route template, not full URL), add the trace id to log lines, and sample deliberately. Use traces from alerts: exemplars on latency histograms and trace links in error logs shorten investigations considerably.

Common misconceptions

  • "The service with the highest latency is the culprit." The entry point always has the highest latency; look at self time.
  • "A service mesh gives me tracing for free." The application must still forward the trace headers it received to its outgoing calls.
  • "Trace ids and request ids are different things to maintain." Use the trace id as the correlation id.
  • "Tracing is too slow for production." Span creation is cheap relative to network calls; cost is mostly export and storage, controlled by sampling.

Interview angle

When asked how to debug latency in a microservice system, explain that metrics show a symptom everywhere, traces locate it: context propagation via traceparent, spans with parent ids, self time and the critical path. Mention propagation through queues, sampling (head vs tail) and linking traces with logs and metrics (exemplars).

Model assumptions

Simulated: a gateway (16 workers, 5 ms), Checkout (16 workers, 20 ms), Inventory (8 workers, 15 ms), Payments (12 workers, 30 ms) and a ledger database (8 connections, 10 ms), called in sequence; callers hold a worker while waiting. Degraded Payments is 8× slower in its own work. Spans quoted in the text are measured from the simulation's hop events (arrival of a request at a service to its answer). The trace context values, the waterfall walk-through, the email queue and the mailer are scripted illustrations; the engine has no notion of trace context. Arrivals are Poisson, service times lognormal, hops a fixed 2–20 ms. Numbers show behaviour, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. One click, five components

    Users send about 40 checkouts a second. Each one passes the gateway, then Checkout, which calls Inventory and then Payments, which writes to the ledger database. Every caller waits for its answer before it can reply.

    Right now a checkout takes about 140 ms end to end. The latency tile measures that whole journey from the user’s side; it does not say how the time is split between the five components.

    Scene: Users send about 40 checkouts per second. Each passes the gateway and Checkout, which calls Inventory and then Payments, which writes to the ledger database. Requests take about 140 ms and none fail.

    Key idea: In a microservice system one user request becomes a tree of calls across many services.

  2. 2. Checkout is slow. Where?

    One second in, something downstream degrades. P50 and P95 jump to several hundred milliseconds, yet there are no errors: everything is slow, nothing is broken.

    Every service’s own latency dashboard now looks bad: the gateway, Checkout and Payments all report slow responses, because each one’s time includes the time it waits for the services it calls. Metrics say *that* checkout is slow. They do not say *where* the time goes.

    Scene: A downstream component degrades. P50 and P95 latency jump to several hundred milliseconds with no errors. The gateway and Checkout both look slow because they wait for their callees.

    Key idea: Latency propagates upstream: every caller looks slow when one callee is. Per-service metrics alone cannot locate it.

  3. 3. A trace is a tree of spans

    Traffic is turned down so you can follow one checkout. A trace records it as a tree of spans: one span per unit of work, each with a start time, a duration, the service that did it, attributes (route, status, db statement) and its parent span.

    Watch the packets and read the annotations as a waterfall. The gateway’s span covers about 370 ms. Inside it, Checkout’s span; inside that, Inventory takes 15 ms and Payments about 260 ms, of which the ledger write is just 10 ms. The time is in Payments itself.

    Scene: One checkout is followed hop by hop. Annotations show each span’s timing: the gateway span covers about 370 ms, Inventory takes 15 ms, Payments about 260 ms of which the ledger write is 10 ms.

    Key idea: A trace shows where the time went: nested spans with start, duration and parent.

  4. 4. Trace context travels with the request

    How does Payments know its span belongs to *this* trace? The caller sends a trace context header with every call. The W3C standard is traceparent: 00-<trace-id>-<parent-span-id>-<flags>: a 16-byte trace id that stays the same for the whole request, the id of the calling span (which changes at every hop) and a sampled flag.

    Each service reads the header, starts its own span as a child of the parent id, and sends a new header with its own span id to the next service. Instrumentation libraries do this for HTTP and gRPC clients and servers automatically; a hand-rolled HTTP client that drops headers breaks the chain.

    Scene: One request travels the chain again. Each hop carries a traceparent header: the trace id is the same everywhere, the parent span id is that of the caller.

    Key idea: Same trace id everywhere, a new parent span id at every hop: that is all propagation is.

  5. 5. Find the slow span

    Back to full traffic, Payments still degraded. Open a handful of slow traces and the pattern is the same in all of them: the Payments span takes most of the request, while its child, the ledger write, still takes only about 10 ms. Inventory is quick too.

    That difference is self time: a span’s duration minus its children’s. Payments has a lot of it, so the problem is inside Payments (its code, its CPU, its runtime), not in the database it calls. Without the trace, the database would have been a natural first suspect.

    Scene: Full traffic with Payments degraded. In every slow request the Payments span takes most of the time while its ledger child span and the Inventory span stay short.

    Key idea: The slow span with high self time is where to look; a slow span whose time is all in its children only passes the blame down.

  6. 6. Where traces break: the async hop

    After a checkout, Checkout publishes an *order placed* event to a queue and a mailer sends the receipt later. Watch the packets: the user’s answer goes back before the mailer even starts.

    If the message carries no trace context, the mailer starts a brand-new trace with a different trace id, and the receipt email can no longer be tied to the checkout that caused it. The fix: put traceparent into the message headers when publishing. Because the mailer’s work happens after the request has finished, OpenTelemetry records it as a separate trace with a span link to the producer, or as a child span, depending on the convention you choose.

    Scene: Checkout publishes an event to a queue and answers the user; later the mailer consumes the event. Without trace context in the message headers, the mailer starts a new trace with a different trace id.

    Key idea: Context must be propagated through queues and background jobs too, usually in message headers.

  7. 7. Fix Payments, verify with the same signals

    The trace pointed at Payments’ own code: a release one hour earlier had switched on an expensive fraud rule for every payment. One second in, the rule is turned off and Payments recovers.

    Verify with the same signals that showed the problem: P95 drops back to its healthy level of about 160 ms, and new traces show a Payments span of a few tens of milliseconds again. Traces that span the incident stay in the trace store as evidence for the post-incident review.

    Scene: Payments recovers. P95 latency returns to about 160 ms and the Payments span shrinks back to a few tens of milliseconds.

    Key idea: Use the signal that found the problem to confirm the fix.

  8. 8. What tracing costs and gives

    Tracing gives you the path and timing of individual requests across services: which call was slow, which failed, what ran in parallel or in sequence. It costs instrumentation in every service, propagation through every hop (including queues) and storage, which is why traces are usually sampled: see the OpenTelemetry lesson for head and tail sampling.

    Put the trace id into your log lines too. Then a slow span leads straight to the log lines written during it, and an error log leads to its whole trace.

    Scene: The healthy checkout system with the email queue and mailer attached to Checkout.

    Key idea: Metrics: is something wrong. Traces: where. Logs: what exactly. Link them by trace id.