Distributed Tracing: Traces & Spans
Metrics say the p99 of POST /links doubled; logs show some requests timed out. Neither says where the time went for one request that crossed linkly, PostgreSQL, Redis and maybe two other services. A trace does: it records every timed operation of one request, across processes, as a tree.
The vocabulary
| Term | Meaning |
|---|---|
| trace | all the work done for one request; identified by a 16-byte trace ID (32 hex characters) |
| span | one timed operation inside it: an HTTP handler, a SQL query, a cache lookup; 8-byte span ID |
| parent span ID | the span that caused this one; the root span has none |
| attributes | key-value details on a span: http.route, http.response.status_code, db.system.name |
| events | timestamped points inside a span (an exception, a retry) |
| status | Unset, Ok or Error |
| kind | SERVER, CLIENT, INTERNAL, PRODUCER, CONSUMER |
| links | references to spans in other traces (a batch job processing messages from many requests) |
| resource | who produced the span: service.name, service.version, k8s.pod.name |
Attribute names follow the OpenTelemetry semantic conventions, so every tool understands http.request.method or db.query.text the same way.
A trace as a tree
A POST /links request on linkly: the HTTP server span is the root; it checks Redis for an existing link, inserts into PostgreSQL (which looked slow), and writes the result to Redis:
trace 4bf92f3577b34da6a3ce929d0e0e4736
POST /links (SERVER, linkly) [0 ms ─────────────────────────────── 212 ms]
├─ GET (CLIENT, redis) [2 ─ 3]
├─ INSERT links (CLIENT, postgresql) [4 ─────────────────────────── 196]
│ └─ pool.acquire (INTERNAL, linkly) [4 ──────────────────── 150]
└─ SET (CLIENT, redis) [198 ─ 200]Tracing UIs draw exactly this as a waterfall (a Gantt chart). This model builds the tree from flat span records (as a backend receives them, in any order), prints the waterfall and computes each span's self time, the time not covered by its children, which is where to look first:
spans = [ # (span_id, parent_id, name, service, start_ms, end_ms)
("c3", "a1", "INSERT links", "postgresql", 4, 196),
("a1", None, "POST /links", "linkly", 0, 212),
("d4", "a1", "SET short:q1x9", "redis", 198, 200),
("b2", "a1", "GET short:q1x9", "redis", 2, 3),
("e5", "c3", "pool.acquire", "linkly", 4, 150),
]
children = {}
for s in spans:
children.setdefault(s[1], []).append(s)
for kids in children.values():
kids.sort(key=lambda s: s[4]) # by start time
SCALE = 4 # ms per character
def walk(span, depth):
sid, _, name, svc, start, end = span
kids = children.get(sid, [])
covered = sum(k[5] - k[4] for k in kids) # children don't overlap in this trace
bar = " " * (start // SCALE) + "█" * max(1, (end - start) // SCALE)
label = " " * depth + f"{name} ({svc})"
print(f"{label:30} {end - start:4} ms self {end - start - covered:4} ms |{bar}")
for k in kids:
walk(k, depth + 1)
walk(children[None][0], 0)POST /links (linkly) 212 ms self 17 ms |█████████████████████████████████████████████████████
GET short:q1x9 (redis) 1 ms self 1 ms |█
INSERT links (postgresql) 192 ms self 46 ms | ████████████████████████████████████████████████
pool.acquire (linkly) 146 ms self 146 ms | ████████████████████████████████████
SET short:q1x9 (redis) 2 ms self 2 ms | █
The waterfall makes the story obvious: the INSERT took 192 ms, but 146 ms of it was waiting for a database connection from linkly's pool (pool.acquire). The database itself was fast; the pool was too small for the load. A metric (pool wait time) can confirm it fleet-wide, but the trace is what pointed there.
(The pool.acquire span is drawn under the INSERT here because the database client library opens its span before acquiring a connection. Where exactly spans nest depends on how libraries are instrumented.)
How a trace crosses services
Each process only knows its own spans. To stitch them together, the caller sends the trace ID and its current span ID with the request, and the callee continues the trace: context propagation. Over HTTP, the standard is the W3C traceparent header:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ │ │ └ flags: 01 = sampled
│ │ └ parent span ID (the caller's span)
│ └ trace ID
└ versionEvery service sends its spans independently to a collector; the backend assembles the tree by trace ID. A service that doesn't forward the header breaks the trace into two. Context Propagation covers headers, goroutines and message queues in detail.
Costs and limits
- Tracing every request of a busy service produces more data than metrics and logs together. Sampling keeps a representative subset (and all the interesting ones): Sampling & Span Metrics.
- Spans need instrumentation in every service on the path. OpenTelemetry's auto-instrumentation for HTTP servers, clients and database drivers covers most of it (OpenTelemetry SDKs).
- Traces show individual requests; for "how often" questions, use metrics, or metrics derived from spans.
Test yourself
What identifies all the spans of one request?
- The span ID
- The trace ID they share
- The service name
- The timestamp
What is a span's "self time"?
- Its total duration
- The part of its duration not covered by its child spans
- The time to export it
- The clock skew
In traceparent: 00-4bf9…4736-00f0…02b7-01, what is 00f067aa0ba902b7?
- The trace ID
- The caller's span ID, which becomes the parent of the callee's span
- A checksum
- The sampling rate