Traces
What a trace and a span are
- A span is one timed piece of work inside one service. It could be an incoming HTTP request, a database query, or a function you chose to wrap.
- A trace is all the spans that share one
trace_id. That is everything that happened because of one starting request.
What is inside a span
| Field | What it is |
|---|---|
trace_id | The same on every span in the trace. 16 bytes (32 hex characters). All zeros is not allowed. |
span_id | Different for every span. 8 bytes (16 hex characters). |
parent_span_id | The span_id of the span that caused this one. Empty on the first span (the root). This one field turns a pile of spans into a tree. |
name | The operation, written so it does not change per request: GET /orders/{id}, not GET /orders/8841. |
kind | Whether this span is the caller or the receiver of a network call: SERVER, CLIENT, PRODUCER, CONSUMER or INTERNAL. |
start / end | Timestamps in nanoseconds. Duration = end − start. Each host has its own clock, so a child can look like it started before its parent. |
status | Unset, Ok or Error. The tracing library sets Error. Your own code should rarely set Ok. |
attributes | Extra key–value fields you can search on, like http.request.method or user.tier. Standard names are in semantic conventions. |
events | Things that happened at one moment inside the span, like an exception event with a stack trace. |
links | A pointer to a related span that is not the parent. Example: a batch consumer linking to the 100 producers whose messages it handled. |
Every span is also tagged with the resource of the process that made it (service.name, k8s.pod.name). That is how the backend knows which bar in the waterfall belongs to which service.
How spans in different services join up: traceparent
For spans in different services to share a trace_id, the caller has to send it along. The standard way is the traceparent header from W3C Trace Context (a W3C standard since November 2021). It has four hex fields joined by hyphens:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ │ │ │
│ trace-id (16 bytes) │ trace-flags: 01 = sampled
version (00) parent-id (8 bytes) = span id of the SENDER's client spanA common mistake: the third field is not "the trace's span id". It is the id of the span on the calling side. Here is what happens at each call:
- The caller sends the header with its own client span id as
parent-id. - The receiver makes a new span with its own fresh
span_id. - The receiver saves the header's
parent-idas itsparent_span_id.
Two related headers: tracestate carries vendor-specific key–value pairs. Baggage (a separate W3C header) carries your own key–value pairs to every service further down the chain. Details: the Distributed Tracing guide.
How a trace tree is put together
No single service ever sees the whole trace. Each one sends its own spans on its own (usually through the Collector), in the order they finish. A parent ends after its children, so it arrives last. The backend rebuilds the tree in three steps:
- Group the spans by
trace_id. - Look each span up by its
span_id. - Attach each span to its
parent_span_id.
spans = {s.span_id: s for s in fetch(trace_id)}
for s in spans.values():
parent = spans.get(s.parent_span_id)
(parent.children if parent else roots).append(s) # root: no parent, or parent missing
for r in roots: print_tree(r) # sort children by start timeIf a span's parent never shows up (it was dropped, is still in flight, or that service is not traced), the span becomes a root of its own. That is why a broken trace looks like several small trees instead of one.
What traces answer that metrics and logs cannot
| Question | Metric says | Log says | Trace says |
|---|---|---|---|
| Checkout p99 went from 400 ms to 2 s. Where? | The gateway's latency went up. | Nothing, unless every service logs its duration. | The payments call to the provider is 220 of the 480 ms. Inventory is fine. |
Which services does orders call, in what order? At the same time or one after another? | Per-service rates only. The order is lost. | You would have to match lines by hand. | The tree shows inventory and payments run one after another. Running them at the same time is the obvious speed-up. |
| Did this one slow request retry? | Lost in the averages. | Maybe, spread across 3 services. | Three client spans side by side under one parent. |
A trace is the per-request view that a metric averages away. That is also why it costs a lot, and why you keep only a sample of traces.
In practice the order is: a metric tells you something is wrong, a trace tells you where, and a log tells you why. You find the right log by its trace_id (see Beyond the three pillars).
Span names
The span name answers "what kind of work is this?". It should come from a small, fixed set of values, maybe a few hundred per service. The details of one request go in attributes. You can filter on attributes, but they never become a grouping key.
Template in the name, instance in the attributes
name: GET /orders/{id} # same for every order lookup
attributes: http.route = /orders/{id}
order.id = 8841 # the specific request lives here
http.response.status_code = 200Backends can group spans by name to give you rate, errors and latency (p50/p99) per operation. This is a convenience built on top of traces, not a replacement for metrics. Every span already records its name, status and duration, so the backend can turn spans into RED numbers without extra instrumentation. For alerts and SLOs, the more reliable source is still real metrics: SDK histograms count every request, while spans are usually sampled. See Turning spans into RED metrics below for how it works and when the numbers can be wrong.
- Stable name: you get one row: "
GET /orders/{id}: p99 = 240 ms". - ID in the name: you get a million rows with one sample each, which tells you nothing.
An ID in the name causes other problems too:
- Names are indexed and often turned into metric labels, so unbounded names blow up cardinality (see Metrics, Cost and vendors).
- Tail-sampling rules and SLO alerts that match on the operation stop working.
- Raw paths can leak emails or tokens into every dashboard and URL.
Sampling in one paragraph each
Keeping every trace is too expensive, so you keep a share. There are two ways to choose which ones.
Head sampling
Decides at the very first span, before anything is known about the request. Usually it keeps a fixed share based on the trace_id (say 5%). The decision travels in the sampled flag, so every service agrees.
Good: cheap, needs no memory.
Bad: it cannot tell good from bad. It keeps 5% of errors and 5% of slow requests, the same as 5% of normal ones.
See the Distributed Tracing guide.
Tail sampling
Decides after the trace has finished, so it can say "keep every trace with an error or taking over 1 s, plus 1% of the rest".
Good: keeps the traces you actually care about.
Bad: something (the Collector's tail_sampling processor) must hold every span of every unfinished trace in memory until it decides. All spans of one trace must also reach the same Collector instance. So you run a separate, memory-heavy layer that keeps state.
See the Distributed Tracing guide and the Cost and vendors part.
Turning spans into RED metrics
Backends turn spans into per-operation numbers: rate, errors and duration (the RED metrics). This happens in one of two places, and most real setups use both.
Why do this if metrics already exist? You do not have to. Metrics are the classic source for latency: they are computed inside the process, cost very little, and count every request. Deriving RED from spans is useful when a service has tracing but no metric instrumentation, for service graphs, and for grouping by attributes you did not plan for. The catch is sampling: spans are usually sampled, metrics are not, so span-derived numbers are only trustworthy if counted before sampling (see below).
Precomputed at ingest
As each span passes through, a component adds it to counters and a duration histogram keyed by (service, span name, status, …). These go out as ordinary time series.
Examples: Tempo's metrics-generator, the Collector's spanmetrics connector (which feeds Jaeger's Monitor tab), Datadog trace metrics.
Good: it runs before sampling, so it sees 100% of traffic. Counts and error rates stay correct even if you keep only 1% of traces.
Bad: every distinct span name becomes a set of series kept forever, so an ID in the name hurts most here. p99 is estimated from histogram buckets, so it is approximate. To combine pods, merge the buckets first and then compute the percentile. Never average percentiles.
Computed at query time
Nothing is prepared ahead of time. When you ask "p99 of GET /orders/{id} over the last hour, by region", the backend scans the stored spans (usually columnar) and calculates the answer right then.
Examples: Honeycomb (built mainly this way), TraceQL metrics queries in Tempo, Datadog's Trace Explorer over indexed spans.
Good: you can group by any attribute, even high-cardinality ones like customer.id, without planning for it. Percentiles are exact over the data you scan.
Bad: it only sees spans that were kept, so with sampling the backend must re-weight counts by each span's sample rate (Honeycomb does this). Long time ranges are slower and cost more to scan.
| Precomputed | At query time | |
|---|---|---|
| Sees all traffic | Yes, if placed before sampling | No, only stored spans |
| Query speed | Instant: it just reads stored metrics | Depends on how much data is scanned |
| Dimensions | Fixed in advance, must be low-cardinality | Any attribute, chosen when you ask |
| Best for | Dashboards, SLOs, alerts | Debugging: "why is it slow for these users?" |
Precomputed RED metrics run your dashboards and alerts. When an alert fires, switch to query-time analysis over stored spans to find the cause. A stable span name matters most for the precomputed path.
Are span metrics accurate if traces are sampled?
Only if the counter sees spans before they are dropped. The tracing library starts a span for every request. Sampling only decides which spans are kept and exported. So accuracy depends on where the counter sits compared to the sampler:
| Setup | What the counter sees | Rate / error rate |
|---|---|---|
Counter before tail samplingapp (100%) → spanmetrics → tail_sampling → Tempo | Every span. The app exports everything. The Collector counts first and samples after. Datadog's agent works the same way. | Exact The cost: you still ship 100% of spans to the Collector, even though you store only a few. |
Head sampling in the appapp (keeps 5%) → spanmetrics → … | Only the 5% that were sampled. The other 95% are non-recording spans that never leave the process. | Estimate You can scale counts by 1/0.05 (OTel probability sampling can carry the rate in tracestate). But rare events are noisy: 1 sampled error could mean 5 real ones or 40. |
Counter after tail samplingapp → tail_sampling → spanmetrics | Only the survivors of a deliberately biased policy (all errors, 1% of successes). | Wrong Request rate collapses and error rate is hugely inflated. See the trap in the Beyond the three pillars part. |
Trace backends
| Backend | Storage model | How you find a trace |
|---|---|---|
| Jaeger (CNCF graduated) | Elasticsearch/OpenSearch, Cassandra, or ClickHouse. Jaeger v2 is built on the OTel Collector. | Search by service, operation, tags or duration. |
| Grafana Tempo | Object storage only (S3/GCS/Azure), in Parquet files. Very little indexing. | Look up by trace ID (fast, using bloom filters), or search fields with TraceQL. You usually arrive with an ID from an exemplar or a log line. |
| Zipkin | Cassandra, Elasticsearch, MySQL, or memory. Older and simpler. Uses B3 headers instead of traceparent. | Search by service, span name or tag. |
| Vendor (Datadog, Honeycomb, New Relic, Lightstep…) | Their own storage. Usually they do tail sampling and indexing for you. | A query UI over indexed fields. |
TraceQL: slow, failing calls to payments
{ resource.service.name = "payments" && status = error && duration > 300ms }Tempo's bet matches the main idea of this guide. It stores traces cheaply in object storage and skips heavy indexing, because it expects you to arrive with an ID from a metric exemplar or a log line (see Beyond the three pillars). Storage trade-offs: the Distributed Tracing guide, the Distributed Tracing guide, and Tempo in the LGTM stack.
Traps
The Invariants
- Guarantees: If every hop passes
traceparentalong, every span has the same 16-bytetrace_idas the request that caused it. Theparent_span_idlinks rebuild the tree no matter what order spans arrive in. A trace shows where the time went across services. - Does not guarantee: That the trace is complete (sampling, dropped spans and untraced services leave gaps). That timestamps from different hosts line up. That every request has a trace. Or why a span was slow: for that you need logs, profiles (see Beyond the three pillars) or the code.