Where did the time go? Distributed tracing

A checkout takes 2.5 seconds across five services, and every service's logs are somewhere else. Follow one trace id through every hop until you can see where the time went, then fix it with numbers to show for it.

Level: DeepWatch: 13 steps · ~1 minuteOpen any spanRecall: 3 questions · 8 cardsCompare 4 ways to keep tracesTypeScript · YAML

What you'll take away

  • Explain how a trace id in traceparent ties every hop of one request together
  • Read a waterfall: overlapping bars ran together, bars in a row waited, red ones failed
  • Pick tail sampling over head when every slow or failed trace has to be kept
  • Prove a fix worked with a new trace and p95 before and after, not a feeling

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
One checkout: 2.5 secondsGET /checkout
GET /checkout → …
Step 1 / 13 · step by step
0.00 sWhole request
0span
0Spans with errors
?Takes the longest
?Of the request

The picture: the first checkout is not traced; it walks through the services once, and three of them write their own logs. The next one is traced and played a call at a time: each call walks its street carrying the trace id and lays a gold thread behind it, and a light stands at every service whose span is open, red for a moment where one failed. The waterfall (one span a row, indented under its parent, time to the right, red a span that failed) stands in the city as a screen. The timings are made up; the waterfall is what tracing tools draw.

Step 4 · Every option at once, on one clock

Compare them all: Distributed tracing

The same hundred requests in every tile: three slow (2.5 s), two failing, the rest fine. Each tile keeps traces its own way. See whether the ones you most want to see are kept, and how many you store.

request 0
No tracingeach service's logskept 0 · slow 0/0 · error 0/0

Use it when One app, one service: logs and metrics are enough

Skip it when Many services: you know it's slow, not where

A model: head sampling at 10% picks by trace id at the start, so it keeps some ten, and this time none of the slow or failing ones (each had a 10% chance). Tail sampling decides after the trace ends. Press any tile to see it large above, with when it fits.

What each one tells you

AnswersExample
MetricsIs something wrong?p95 of /checkout went from 400 ms to 2.5 s
TracesWhere in the request?The SELECT in orders takes 68% of it
LogsWhat happened right there?The query, its parameters, the error text

Let the SDK do the passing

In real code you don't write the header by hand: OpenTelemetry's SDKs and auto-instrumentation make spans for incoming and outgoing HTTP and for database calls, and pass traceparent on. Put the trace id in your log lines too, and you can go from a slow span straight to its logs.

Keep the interesting ones

Keeping every trace gets expensive. Head sampling is cheap but decides before anyone knows a request will be slow; tail sampling waits for the end and keeps the errors and the slow ones, at the cost of holding spans for a while.

In real code

traceparent.ts
// Three small services on 127.0.0.1 passing a W3C traceparent header along, the way OpenTelemetry's propagator does:
// gateway → checkout → db. Each one reads the trace id, makes a span of its own and sends its span id downstream.
import assert from "node:assert/strict";
import { randomBytes } from "node:crypto";
import { createServer, request, type IncomingMessage, type Server } from "node:http";
import type { AddressInfo } from "node:net";

interface Span { service: string; trace: string; id: string; parent: string | null; ms: number }
const spans: Span[] = []; // what an exporter would ship off; here we keep them to look at
const FORMAT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-0[01]$/; // version-traceid-parentid-flags

function call(port: number, traceparent: string): Promise<string> {
  return new Promise((done, fail) => {
    request({ host: "127.0.0.1", port, headers: { traceparent } }, (res) => { let b = ""; res.on("data", (c) => (b += c)); res.on("end", () => done(b)); }).on("error", fail).end();
  });
}

/** One service: continue the trace it was sent (or start one), do its work, maybe call the next. */
function service(name: string, work: (traceparent: string) => Promise<void>): Server {
  return createServer(async (req: IncomingMessage, res) => {
    const start = performance.now();
    const m = FORMAT.exec(String(req.headers.traceparent ?? ""));
    const trace = m ? m[1] : randomBytes(16).toString("hex"), id = randomBytes(8).toString("hex");
    await work(`00-${trace}-${id}-01`); // downstream calls carry OUR span id as their parent
    spans.push({ service: name, trace, id, parent: m ? m[2] : null, ms: performance.now() - start });
    res.end("ok");
  });
}
const listen = (s: Server) => new Promise<number>((r) => s.listen(0, "127.0.0.1", () => r((s.address() as AddressInfo).port)));

const db = service("db.query", () => new Promise((r) => setTimeout(r, 300))); // the slow query
const dbPort = await listen(db);
const checkout = service("checkout", async (tp) => { await call(dbPort, tp); });
const checkoutPort = await listen(checkout);
const gateway = service("gateway", async (tp) => { await call(checkoutPort, tp); });
const gatewayPort = await listen(gateway);

await call(gatewayPort, ""); // a request from outside: no traceparent yet, the gateway starts the trace
for (const s of [db, checkout, gateway]) s.close();

const [q, c, g] = spans; // spans finish inside-out: db, then checkout, then gateway
assert.equal(new Set(spans.map((s) => s.trace)).size, 1); // one trace id on every hop
assert.deepEqual([g.parent, c.parent, q.parent], [null, g.id, c.id]); // each span's parent is the caller's span
// Where the time went: the slow query is most of the request (the two hops on 127.0.0.1 take a few ms, more on a busy
// machine, so the share is held loosely: over half, never an exact figure that a slow run would miss).
assert.ok(q.ms >= 290 && q.ms / g.ms > 0.5);
console.log(`${spans.length} spans, one trace id · gateway → checkout → db.query, each the parent of the next · db.query is most of the request`);
Run: node traceparent.ts (three services on 127.0.0.1 really passing the header on; no OpenTelemetry package used)It printed: 3 spans, one trace id · gateway → checkout → db.query, each the parent of the next · db.query is most of the request

Three small services on 127.0.0.1 (gateway → checkout → db) pass a W3C traceparent header along, the way OpenTelemetry's propagator does: each reads the trace id, makes a span of its own and sends its span id downstream. Written by hand with node:http, so you can see what the SDK does for you; really run.

Common questions

What's the difference between a trace and a span?

A trace is one request's whole journey; a span is one piece of work in it, like taking a request, calling a service or a query, with a name, a start, an end and a parent span. Every span in a trace shares its trace id.

What does a traceparent header look like?

00-<32 hex trace id>-<16 hex span id of the caller>-<flags>, where a trailing -01 means sampled. It's the W3C Trace Context standard OpenTelemetry uses. Each hop puts its own span id in before passing it on.

Do I have to pass the header along myself?

No. OpenTelemetry's SDKs and auto-instrumentation make spans for incoming and outgoing HTTP and for database calls, and pass traceparent on for you. What's worth adding is the trace id in your log lines, so you can jump from a slow span to its logs.

Logs, metrics and traces: what is each for?

Metrics tell you something is wrong (p95 up, more errors). Traces tell you where in a request it's slow or failing. Logs tell you what happened right there. You usually go through them in that order.

Table: what each one tells you

Head vs tail sampling: what's the difference?

Head sampling decides when the request starts: cheap and simple, but nobody knows yet if it will be slow or fail, so at 10% you keep about 10% of the errors. Tail sampling waits for the end and keeps every error and slow one, but something like an OpenTelemetry Collector must hold the spans meanwhile.

What do overlapping bars in a waterfall mean?

The two ran at the same time. Inventory and payments start together in the picture, so the time spent is the longer of the two. Bars one after another mean waiting on each other, and a red bar is a span that failed (payments got a 503, then retried).

I fixed it. How do I know it's really faster?

Look at a new trace: with an index on customer_id the query takes 40 ms and the whole request 0.84 s instead of 2.5. Then compare p95 in your metrics before and after, to see it's faster for everyone and not one lucky request.

Next lesson

Scaling a databaseLevel: Deep

The trace found a SELECT with no index taking most of the time; next, the order of fixes for a slow database, index first.