Distributed Tracing
Following a single request as it hops across many services, so you can actually find where it went wrong.
Distributed tracing in 30 seconds
- Problem: one user request touches 10 services; when it's slow or broken, which service is to blame?
- Idea: tag the request with a trace ID at the edge and pass it through every hop.
- Spans: each service records a span (its slice of the work, with timing) tied to that trace ID.
- Result: stitch the spans together to see the full timeline and spot the slow or failing step.
- Context propagation is the key — the trace ID must ride along in headers through every call.
- Part of observability: tracing (where), plus logs (what happened) and metrics (how much).
Tracking a parcel across the country
When you order a package, it doesn't teleport to your door. It passes through a sender's warehouse, a sorting hub, a long-haul truck, a regional depot, and a local courier. If it arrives three days late, 'the delivery was slow' is useless — you want to know which leg dragged. That's exactly why every parcel carries a tracking number: scan it at each stop, and the carrier can lay out the whole journey on one timeline and point at the depot where it sat for two days.
A request flowing through a system of services is that parcel. Distributed tracing gives the request a tracking number (a trace ID), scans it at every service it passes through (a span), and reassembles the full journey so you can see exactly which leg was slow or where it got lost. Hold that parcel picture — the whole page is just making it precise.
Why we even need this — microservices hid the story
On a single app, when something's slow you read the logs and you're done — it all happened in one place, in one file, in order. Breaking that app into twenty services buys you independent scaling and deploys, but it quietly takes something away: the ability to see one request from end to end.
Now a single click might pass through the gateway, auth, orders, payments, inventory, and notifications. 'Why was this slow?' becomes a detective problem — the logs are scattered across twenty machines, each service only sees its own slice, and none of them alone tells you the full story. Worse, nothing connects those twenty log files, so you can't even tell which lines belong to the same request. Distributed tracing is how you reassemble that story into one picture.
The problem, told simply
- One user action fans out into many service calls, often nested several layers deep.
- Each service logs to its own machine, in its own format, with no shared thread tying the lines together.
- When it's slow or broken, you can't tell which hop is at fault without reading all of them and guessing.
- You need a single id that rides along the whole way, so every log and timing from one request can be stitched back together.
Two words to learn first: trace and span
How the trick works
- Stamp it once. When a request enters (usually at the gateway), give it a unique trace ID — the parcel's tracking number.
- Carry it everywhere. Every service passes that trace ID along in the request headers to the next service it calls — the scan at each depot.
- Record a span. Each service logs a span — what it did, when it started, how long it took — all labeled with the trace ID.
- Stitch it together. A tracing tool collects every span with the same trace ID and lays them out on one timeline.
async function handleOrder(req) {
// Continue the trace if upstream sent one, else start a new trace id
const traceId = req.headers['x-trace-id'] || newTraceId();
const span = startSpan({ traceId, name: 'orders.handle' });
try {
// Carry the same trace id to the next hop so spans stitch together
await fetch('http://payments/charge', {
headers: { 'x-trace-id': traceId, 'x-parent-span': span.id }
});
span.setStatus('ok');
} catch (err) {
span.setStatus('error'); // this span shows up red on the timeline
throw err;
} finally {
span.finish(); // records duration for the timeline
}
}What a trace tells you at a glance
- Which step is slow — one long bar on the timeline is your culprit.
- Where it failed — the span that errored, with the services before and after it for context.
- Hidden fan-out — a service quietly calling five others you didn't expect.
- Serial vs parallel — calls lined up one-after-another that could have run at the same time.
Sampling — you can't afford to keep every trace
Here's the catch that surprises people: recording a span for every request, at full production scale, produces a firehose of data that's expensive to store and process. So real systems sample — they keep only a fraction of traces. The art is keeping the right fraction: always hold onto the errors and the slow ones (those are what you'll actually debug), and keep just a small percentage of the boring, healthy traffic for a baseline.
function shouldKeep(trace) {
// Always keep problems — they're what you'll actually debug
if (trace.hasError) return true;
if (trace.durationMs > SLOW_THRESHOLD_MS) return true;
// Otherwise keep a small percentage of normal traffic
return Math.random() < 0.01; // 1% sample of healthy requests
}There's a timing wrinkle too: deciding up front whether to keep a trace (head-based sampling) is cheap but you don't yet know if it'll error; deciding after the request finishes (tail-based sampling) lets you keep exactly the errors and slow ones, but costs more to buffer every trace until it completes. Which you choose is a real cost-vs-visibility trade, not an afterthought.
The gap logs alone can't fill
You might think: 'I already log everything — why isn't that enough?' It's a great question, and the answer is the reason tracing exists as its own thing. Logs are brilliant at telling you what happened in one place, but they have a blind spot across service boundaries:
- Logs don't connect across machines. Twenty services write twenty separate log streams. Nothing says 'these lines all came from the same request' unless you deliberately thread an id through.
- Logs have no shared timeline. Even with every line, you can't easily see that payments started while inventory was still running, or that one call waited on another.
- Logs don't show the shape. A trace reveals fan-out and nesting at a glance; raw logs bury it in noise.
Tracing fills the gap by adding the one thing logs lack: a shared id and a timeline. That's also why tracing and logging work best together — attach the trace ID to your logs, and suddenly every log line can be pulled up for a specific request's journey.
Context propagation — the make-or-break detail
Everything above hinges on one quiet mechanism: the trace ID has to ride along on every outbound call, through every service, without anyone forgetting to pass it. This is context propagation, and it's where real tracing setups most often break. Miss it on even one hop and the trace snaps in two — you get a stub journey that ends at the first service that dropped the baton.
// Middleware that runs on EVERY service, for EVERY request.
function withTraceContext(req, next) {
// 1. Read the context an upstream service sent (or start a fresh trace)
const traceId = req.headers['x-trace-id'] || newTraceId();
const parent = req.headers['x-span-id'] || null;
// 2. Make it available to this service's own outbound calls
context.set({ traceId, parentSpanId: parent });
// 3. Any fetch() this service makes MUST re-attach the headers,
// or the trace breaks at this hop. Do it once, centrally:
http.onOutbound(h => {
h['x-trace-id'] = traceId; // same journey continues
h['x-span-id'] = context.currentSpanId();
});
next();
}Tracing, logs, and metrics — the three together
Tracing is one leg of observability, and each leg answers a different question:
| Pillar | Answers | Example |
|---|---|---|
| Metrics | How much / how often? | Requests per second, error rate, p99 latency. |
| Logs | What exactly happened? | A detailed line for a specific event or error. |
| Traces | Where did the time/failure go? | This request spent 800ms in the payments service. |
Distributed tracing is what gives you back the thing microservices quietly took away: the ability to follow one request end to end and actually understand what happened to it.
Why it matters
- It turns 'the system is slow somewhere' into 'the payments span took 800ms' — a guess becomes a fact.
- It exposes the shape of a request you can't see from any single service: hidden fan-out, needless serial calls, surprise dependencies.
- It's one of the three pillars of observability, and the only one that stitches a story across service boundaries.
If ignored
- Debugging cross-service latency becomes archaeology — grepping scattered logs on twenty machines with nothing tying them together.
- Incidents drag on because no one can say which hop in the chain is the culprit.
- Slow regressions and quiet fan-out creep in unnoticed until they're a customer-facing problem.
Where it fits
- Spans the whole request path, from the edge gateway through every downstream service it touches.
- Relies on context propagation — the trace ID riding along in headers through every call.
- Sits beside metrics (how much) and logs (what happened) to answer 'where did the time and failure go?'
Related topics
- API gateway: the natural edge to stamp the trace ID onto an incoming request
- Service discovery: traces reveal the dynamic call graph discovery wires together
- Circuit breaker: a trace shows the dependency that's failing and tripping breakers
- Latency & throughput: traces are how you see where p99 latency is actually spent
Interview lens
Questions it unlocks
- A request is slow across your microservices — how do you find the bottleneck?
- What's a trace ID and a span?
- How do tracing, logging, and metrics differ?
60-second answer
When one request crosses many services, I use distributed tracing: stamp a trace ID at the edge, propagate it in headers through every hop, and have each service record a span with timing. Stitching the spans on one timeline shows exactly which step is slow or failing and reveals hidden fan-out or needless serial calls. I'd place tracing alongside metrics (how much) and logs (what happened) as the three pillars of observability, and I'd call out sampling as a real cost-vs-visibility trade — keeping errors and slow requests while sampling the rest.
Common traps
- Trying to debug cross-service latency from scattered logs with no trace ID.
- Forgetting to propagate the trace context, so the trace breaks at the first hop.
- Tracing 100% of traffic and drowning in cost and data.