SENIORCHAPTER 21

Debugging with traces: exemplars, span links, critical path

Go from a spike on a latency graph to the one request that made it, find the part of that request that actually set its duration, and follow the causal edges a parent id cannot express

60 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

Your gateway latency histogram has exemplars. On the p99 panel you hover a dot in the 2 to 3 s bucket at 14:12 and open its trace. What have you got?

The previous chapters gave you the three signals and a way to correlate them by trace id. This chapter is about using that correlation under pressure. There are three moves. From an aggregate (a histogram) to an example (a trace) through exemplars. From a trace to the cause through critical-path analysis. And from one trace to a related one when a parent id is the wrong shape, through span links. Underneath all three sits TraceQL, which turns a pile of traces back into a population you can count.

From a graph to a trace: exemplars

A histogram aggregates. That is its job: 10,000 requests a second become 13 bucket counters per label set, and the cost of a metric does not grow with traffic. The price is that the individual requests are gone. When p99 jumps you know the shape of the slowness and nothing about any one slow request.

An exemplar puts one request back. When the client library records an observation, it can attach a small label set (by convention trace_id, sometimes span_id) and keep it next to the bucket that observation landed in. The scrape carries it; Prometheus stores it beside the series; Grafana draws it as a dot on the graph with a link to the trace.

Four pieces have to line up, and each one fails silently:

piece demo-app setting what happens without it
the client records a trace id with each observation observe(elapsed, exemplar={"trace_id": ...}) in services/common/metrics.py nothing to expose
the endpoint serves a format that can carry exemplars OpenMetrics text, chosen from the scrape’s Accept header the classic text format drops them without error
Prometheus stores them --enable-feature=exemplar-storage (already in compose.yaml) scraped and discarded
Grafana knows which label is the trace id exemplarTraceIdDestinations: [{ name: trace_id, datasourceUid: tempo }] (already provisioned) dots without a link

The second row catches most teams. The classic Prometheus exposition format has no syntax for exemplars. OpenMetrics does: a bucket line ends with # {trace_id="4bf9..."} 2.31 1762092751.123, the labels, the observed value, and an optional timestamp. Prometheus v3.2.1 asks for OpenMetrics first: with native histograms off, its default scrape_protocols order is OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText1.0.0, PrometheusText0.0.4. But the lab’s /metrics handler ignores the Accept header and always returns generate_latest(), which is the classic format. prometheus_client.exposition.choose_encoder(accept_header) returns the right encoder and content type for whatever the scraper asked for; the lab makes that change. The OTLP path has the same trap one layer up: the Collector’s prometheus exporter exposes exemplars only with enable_open_metrics: true.

Three properties shape how you use exemplars:

  • Recency, not rank. prometheus_client keeps the last exemplar per bucket per label set. Prometheus keeps exemplars in a fixed-size circular buffer (storage.exemplars.max_exemplars in the config file, 100,000 by default) shared by every series. You see a sample, not the worst case.
  • Only sampled traces are worth recording. If the trace was not sampled, the id points at nothing. Record an exemplar only when the span context is valid and its sampled flag is set. With tail sampling in the Collector, even a sampled-at-the-SDK trace can be dropped later; the link then 404s, and that is expected.
  • The bucket tells you which population. A dot in the le="3" bucket is a request between 2 and 3 s. Pick a dot in the bucket that moved, not the highest dot on the panel, which may be an unrelated outlier from yesterday’s deploy.

An exemplar is one example. Before you reason from it, confirm it is typical with a population query: if the exemplar trace has fault.slow_delay_s set on its payments span, count how many slow gateway traces have it too. That is TraceQL’s job, below.

From a trace to a cause: the critical path

You have the trace. It has ten spans:

gateway GET /checkoutgateway POSTorders POST /ordersorders INSERT, INSERTorders POST (client)payments POST /chargepayments GET (redis)payments SET (redis)orders UPDATEshaded = on the critical path; almost all of it is payments’ own time, with no child span to blame

Every span on the left is between 2.3 and 2.4 s long. Duration does not localise anything in a synchronous call chain: a parent always lasts at least as long as the child it waits for. Sorting spans by duration gives you the root first and the culprit last.

The useful quantity is self time on the critical path. The critical path is the sequence of work that determined when the root span ended. Walk it backwards: start at the root’s end time; find the child that finished last before that point; the gap between that child’s end and the cursor is the parent’s own time; recurse into the child; move the cursor to the child’s start; repeat until you reach the parent’s start, and count what is left as the parent’s own time. Children that ran entirely in parallel with a child already on the path are skipped, because finishing them earlier would not have ended the request earlier.

For the trace above, that walk gives the gateway and orders a few milliseconds each, the Postgres statements a few more, and payments’ POST /charge almost all of 2.3 s, as self time. That is the planted FAULT_SLOW_PAYMENTS_PCT sleep: asyncio.sleep inside the handler, with no child span around it. A self-time hole like that is itself a finding. It says the time is in code you did not instrument, and the next move is a manual span or a profile, not another dashboard.

The demo app is a chain, so its critical path is the whole trace. Fan-out is where the critical path earns its name. With parallel calls, the request waits for the slowest, and speeding up any other child changes nothing:

▶ SIMULATION
PARENT (waits for all 20)
requests done 0 / 1000
p50 — · p99 —
—
P(PARENT HITS A SLOW BACKEND)
measured: —
1 − 0.9920 = 18.2%
BACKENDS (each)
calls 0
p95 —
slow calls (150–250 ms): 0 of 0 (0%)
SLOparent p99 ≤ 50 ms
parents over 50 ms0 of 0
✓ parent p99 ≤ 50 ms
SCHEDULE
01[CLIENT]fan out to FANOUT backends, wait for every reply
02[CLIENT]parent requests 1–200
03[CLIENT]parent requests 201–400
04[CLIENT]parent requests 401–600
05[CLIENT]parent requests 601–800
06[CLIENT]parent requests 801–1000
07[CLIENT]report percentiles
Start of wait for all scenario. 7 steps.
// wait for every shard
const parts = await Promise.all(shards.map((s) => s.query(q)));
// latency = the slowest of N calls

Watch the parent’s latency follow the slowest backend in each batch while the other calls finish early and sit idle. On a trace of that request, every backend span is shorter than the parent, and only one of them per batch is on the critical path. Hedging, the fix in the sim, works by shortening the critical path rather than any average.

Where critical-path analysis goes wrong:

  • Clock skew. Spans from different hosts carry different clocks. A child that appears to start before its parent, or end after it, is skew; clamp it to the parent’s bounds, as the lab’s script does. Within one Docker host this is negligible; across data centres it can be milliseconds.
  • Missing spans. Self time is “time not covered by a child”. A missing span (an uninstrumented client, a dropped batch) turns into self time on its parent, and you blame the wrong service. If a span’s self time is large, check that its children are all there before you blame it.
  • Async work. Work started by the request but finished after the response (a fire-and-forget publish) is outside the root’s end and off the critical path by definition. That is correct for latency, and wrong if your question is cost.
  • One trace is an anecdote. CRISP’s contribution is aggregating critical paths over many traces: per endpoint, which operations most often sit on the path, and for how long. You can approximate that with TraceQL, next.

Asking the population: TraceQL

TraceQL, Tempo’s query language, selects spansets: groups of spans within a trace that match a condition. The lab stack pins Tempo 2.7.1. The pieces you use for debugging:

{ resource.service.name = "payments" && span:name = "POST /charge" && span:duration > 1s }

Scoped attributes (resource. for the process, span. for the operation) and intrinsics with a colon (span:duration, span:name, span:kind, span:status). Durations take units (500ms, 1s). Unscoped .attr searches both scopes and is slower.

{ trace:rootService = "gateway" && trace:duration > 1500ms }

Trace-level intrinsics (trace:duration, trace:rootService, trace:rootName) are cheaper than span-level ones because Tempo stores them once per trace. Use them to select the slow population.

{ resource.service.name = "gateway" } >> { span.fault.slow_delay_s > 0 }

Structural operators relate spans in the same trace: >> descendant, > direct child, << ancestor, < direct parent, ~ sibling. The result is the right-hand side’s spans. The union forms (&>>, &> and so on) return both sides.

{ span:kind = server && span:duration > 1s } | by(resource.service.name) | count() > 0

Pipelines filter and group spansets: count(), avg(span:duration), max, min, sum, by() and select(). select(span.order.id, span.payment.cached) adds attributes to the result without filtering on them.

The question that validates an exemplar is a pair of searches. How many gateway traces over 1.5 s are there in the last 15 minutes, and how many of them have a payments span with fault.slow_delay_s set? If the counts match, the exemplar is typical and the cause is the slow-charge path. If only half match, there is a second cause hiding behind the first, and you look at the slow traces that do not have it.

TraceQL also does metrics (rate(), quantile_over_time()), but in Tempo 2.7 that needs the metrics-generator’s local-blocks processor, which the lab’s single-binary config does not enable. The lab sticks to search.

A parent id says “this operation is part of that one”. Some causal relationships are not containment:

  • A batch consumer handles 100 messages in one span. Each message came from a different trace. The batch span cannot have 100 parents.
  • A retry from a queue runs an hour after the original request has ended. Making it a child would stretch the original trace to an hour.
  • An idempotent replay: a client retries POST /charge with the same idempotency key, and payments returns the stored result. The replay is its own request, with its own trace, and it is about the original charge.

A span link is a reference from one span to another span context (trace id, span id, and optional attributes), which may be in a different trace. Links are normally set when the span starts; recent versions of the specification also allow adding them afterwards. Tempo stores them in the vParquet4 block format, the default in 2.7, and TraceQL exposes them as link:traceID, link:spanID and link. attributes. In Grafana’s trace view a span with links shows them in its detail pane, each one clickable into the other trace.

The demo app has no links yet. Its idempotent-replay path is the natural first one: payments already stores the result of each charge under charge:<idempotency_key> in Redis. If it also stores the trace and span id of the request that made the charge, a replay can link back to it. Then “which requests replayed this charge?” is the TraceQL query { link:traceID = "<original trace id>" }, and the replay’s trace opens the original with one click. The messaging chapter in module four uses the same mechanism for producer and consumer spans across a queue.

Links are not free of traps. A link to a trace that was sampled out leads nowhere, so link targets should be sampled consistently (tail sampling by trace id, or a decision recorded on the original). And a link is a hint for a human or a query, not a structural edge: the critical-path walk above ignores links, because the linked work did not run inside this request.

The loop

Put together, debugging latency with traces is a loop that ends in a population, not an anecdote:

  1. Graph. The latency histogram moved. Pick the bucket that moved.
  2. Exemplar. Open one trace from that bucket.
  3. Critical path. Find the span with the most self time on the path. Check its children are all present.
  4. Hypothesis as TraceQL. Turn what that span has in common with the problem (an attribute, a service, a version) into a query.
  5. Count. Compare the matching population with the slow population. If they agree, you have the cause. If not, take a slow trace that does not match and go back to step 3.
LAB From a p99 spike to the span that caused it ~60 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2 and about 4 GB of RAM freethe ATLAS repo cloned, working in labs/observability, with the telemetry stack workingcurl, jq and Python 3.10+ on the hosta browser for Grafana on localhost:3000

You will turn on exemplars, follow one from the gateway’s latency histogram into Tempo, compute the critical path of the trace, check the population with TraceQL, and add a span link to payments’ idempotent replay.

1. Start the stack with a slow-payments fault.

cd labs/observability
printf 'OTEL_SDK_DISABLED=false\nLOG_FORMAT=json\nOTEL_SEMCONV_STABILITY_OPT_IN=http/dup\nFAULT_SLOW_PAYMENTS_PCT=10\n' > .env
docker compose --profile telemetry up -d --build
curl -s localhost:8080/metrics | grep -c ' # {'
The stack comes up with 10% of charges sleeping 1.5 to 3 s. The grep -c prints 0: the /metrics endpoint has no exemplars, because nothing records them and the handler only speaks the classic format. With this module’s alerts loaded, 10% slow charges against the 1% latency budget is a burn rate of 10, so the pager soon shows an ErrorBudgetBurn ticket for checkout-latency, and on a young stack possibly a page later in the lab. That is the alerting doing its job; the fault comes out at the end of the lab.

2. Record exemplars and serve OpenMetrics. Open services/common/metrics.py. Change the imports at the top so they read:

from fastapi import FastAPI, Request, Response
from opentelemetry import trace
from prometheus_client import REGISTRY, Counter, Gauge, Histogram
from prometheus_client.exposition import choose_encoder

In PrometheusMiddleware.__call__, in the finally: block, replace the LATENCY.labels(...).observe(elapsed) line with:

            ctx = trace.get_current_span().get_span_context()
            exemplar = None
            if ctx.is_valid and ctx.trace_flags.sampled:
                exemplar = {"trace_id": format(ctx.trace_id, "032x")}
            LATENCY.labels(method=method, route=route, status=status).observe(elapsed, exemplar=exemplar)

And replace the metrics() handler in install_metrics with one that honours the Accept header:

    @app.get("/metrics", include_in_schema=False)
    def metrics(request: Request) -> Response:
        encoder, content_type = choose_encoder(request.headers.get("accept", ""))
        return Response(encoder(REGISTRY), media_type=content_type)

The OpenTelemetry middleware wraps this one (it is installed after it in create_app), so the request’s span is current in the finally: block. Rebuild the three services, which share common/, and ask for both formats:

docker compose --profile telemetry up -d --build gateway orders payments
sleep 20
curl -s localhost:8080/metrics | grep -c ' # {'
curl -s -H 'Accept: application/openmetrics-text; version=1.0.0' localhost:8080/metrics \
  | grep 'http_request_duration_seconds_bucket' | grep '/checkout' | grep ' # {' | head -n 3
The first count is still 0: without the header you get the classic format. The second prints bucket lines ending in an exemplar, such as http_request_duration_seconds_bucket{le="3.0",method="GET",route="/checkout",status="200"} 61.0 # {trace_id="7a1c..."} 2.4113 1.7620927e+09: the bucket, its count, then the exemplar’s trace id, its observed latency in seconds and the Unix time it was recorded. Prometheus sends that header on every scrape, so it now receives these.

3. Read the exemplars Prometheus stored.

now=$(date +%s)
curl -sG localhost:9090/api/v1/query_exemplars \
  --data-urlencode 'query=http_request_duration_seconds_bucket{job="gateway",route="/checkout"}' \
  --data-urlencode "start=$((now - 900))" --data-urlencode "end=$now" \
  | jq -r '[.data[].exemplars[]] | sort_by(.value | tonumber) | reverse | .[:5][] | "\(.value)\t\(.labels.trace_id)"'

Copy the first trace id into a shell variable: TID=<the id>.

Five lines, latency then trace id, the top ones between 1.5 and 3 s: requests that hit a slow charge. Lower down you would see exemplars from the fast buckets, a few milliseconds each. Then in Grafana: Explore, Prometheus, query histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="gateway",route="/checkout"}[1m]))), and turn on Exemplars under Options. Dots appear along the graph; hovering one shows its trace_id with a link that opens the trace in Tempo.

4. Compute the critical path. Save as critical_path.py in labs/observability:

#!/usr/bin/env python3
"""Self time on the critical path for one trace, from Tempo's GET /api/traces/<id>.
usage: python3 critical_path.py trace.json"""
import json
import sys
from collections import defaultdict

doc = json.load(open(sys.argv[1]))
doc = doc.get("trace", doc)
spans = {}
for batch in doc.get("batches") or doc.get("resourceSpans") or []:
    attrs = batch.get("resource", {}).get("attributes", [])
    svc = next((a["value"].get("stringValue") for a in attrs if a["key"] == "service.name"), "?")
    for scope in batch.get("scopeSpans") or batch.get("instrumentationLibrarySpans") or []:
        for s in scope["spans"]:
            spans[s["spanId"]] = {"id": s["spanId"], "parent": s.get("parentSpanId") or None,
                                  "name": f'{svc}: {s["name"]}',
                                  "start": int(s["startTimeUnixNano"]), "end": int(s["endTimeUnixNano"])}

children = defaultdict(list)
for s in spans.values():
    if s["parent"] in spans:
        children[s["parent"]].append(s)
root = min((s for s in spans.values() if s["parent"] not in spans), key=lambda s: s["start"])


def walk(span, cursor, out):
    """Walk back from cursor; time not covered by a child on the path is the span's own."""
    for child in sorted(children[span["id"]], key=lambda c: c["end"], reverse=True):
        if child["start"] >= cursor:      # ran alongside a child already on the path
            continue
        end = min(child["end"], cursor)   # clamp clock skew
        out[span["name"]] += cursor - end
        walk(child, end, out)
        cursor = max(child["start"], span["start"])
        if cursor <= span["start"]:
            break
    out[span["name"]] += max(0, cursor - span["start"])


out = defaultdict(int)
walk(root, root["end"], out)
total = root["end"] - root["start"]
print(f"trace {total / 1e6:.1f} ms, {len(spans)} spans, root {root['name']}")
for name, ns in sorted(out.items(), key=lambda kv: -kv[1]):
    print(f"{ns / 1e6:9.1f} ms {100 * ns / total:6.1f}%  {name}")
curl -s "localhost:3200/api/traces/$TID" > trace.json
python3 critical_path.py trace.json
Something like trace 2412.7 ms, 10 spans, root gateway: GET /checkout, then payments: POST /charge at well over 95%, and every other line at a few milliseconds or less: the gateway’s own time, orders’ INSERT statements, the Redis GET and SET. Every one of those spans is over 2 s long in the waterfall; only one has the time as its own. Run the script on a fast exemplar from step 3 and the shares spread out across orders and Postgres, which is what a healthy checkout looks like.

5. Check the population with TraceQL. Count the slow traces, then the slow traces explained by the fault:

tq() { curl -sG localhost:3200/api/search --data-urlencode "q=$1" \
  --data-urlencode "start=$(( $(date +%s) - 300 ))" --data-urlencode "end=$(date +%s)" \
  --data-urlencode 'limit=1000' | jq '.traces | length'; }
tq '{ trace:rootService = "gateway" && trace:duration > 1500ms }'
tq '{ trace:rootService = "gateway" && trace:duration > 1500ms } && { span.fault.slow_delay_s > 0 }'
tq '{ resource.service.name = "gateway" } >> { span.fault.slow_delay_s > 0 }'

Then in Grafana, Explore, Tempo, TraceQL, run { span:kind = server && span:duration > 1s } | by(resource.service.name) and open a result.

The first two counts are equal, or within one or two of each other (a trace still being written can match one query and not the other): every slow checkout has a slow charge in it. At 5 requests per second with 10% slow, the 5-minute window holds about 150. The third returns the same traces from the structural side. The grouped query in Grafana returns one spanset per service for each slow trace, gateway, orders and payments all over 1 s, which is the duration trap in one screen.

6. Add a span link to the idempotent replay. In services/payments/app.py, add to the imports:

from opentelemetry.trace import Link, SpanContext, TraceFlags

and below app, log = create_app("payments", lifespan=lifespan):

tracer = trace.get_tracer("payments")

In charge(), replace the if existing: block with:

    if existing:
        result = json.loads(existing)
        origin = result.pop("origin", None)
        links = []
        if origin:
            original = SpanContext(trace_id=int(origin["trace_id"], 16), span_id=int(origin["span_id"], 16),
                                   is_remote=True, trace_flags=TraceFlags(TraceFlags.SAMPLED))
            links.append(Link(original, {"relation": "replay_of"}))
        with tracer.start_as_current_span("charge.replay", links=links):
            result["cached"] = True
            span.set_attribute("payment.cached", True)
            log.info("charge replayed from idempotency key", extra={**fields, "charge_id": result["charge_id"]})
        return result

and replace the await r.set(key, json.dumps(result), ex=KEY_TTL_SECONDS) line with:

    ctx = span.get_span_context()
    stored = dict(result)
    if ctx.is_valid:
        stored["origin"] = {"trace_id": format(ctx.trace_id, "032x"), "span_id": format(ctx.span_id, "016x")}
    await r.set(key, json.dumps(stored), ex=KEY_TTL_SECONDS)

Rebuild payments, make one charge, and replay it:

docker compose --profile telemetry up -d --build payments
sleep 10
OID=$(curl -s 'localhost:8080/checkout?user=42&items=1' | jq -r .order_id)
curl -s -X POST localhost:8082/charge -H 'content-type: application/json' \
  -d "{\"order_id\": $OID, \"amount\": 0, \"idempotency_key\": \"order-$OID\"}"
sleep 10
curl -sG localhost:3200/api/search --data-urlencode 'q={ span:name = "charge.replay" } | select(span:name)' \
  | jq -r '.traces[0] | "\(.traceID) \(.rootTraceName)"'
The replay returns the original charge_id with "cached": true and no origin field. The search finds the replay’s trace, rooted at POST /charge in payments because curl sent no traceparent. Open it in Grafana: the charge.replay span’s detail pane lists one link, with the attribute relation = replay_of, that opens the checkout trace for order $OID. From the other direction, { link:traceID = "<that checkout's trace id>" } finds every replay of it.
Stop Tempo for two minutes with docker compose --profile telemetry stop tempo, then start it again. Prometheus keeps scraping and storing exemplars the whole time, and the gateway keeps recording trace ids for traces that the Collector could not deliver. Pick an exemplar from that window in Grafana and the link opens “trace not found”. Exemplars and links are pointers into a different store with a different retention and a different failure mode; that is why the step 3 sanity check, and a population query in step 5, come before any conclusion. The same happens permanently when the tail-sampling processor drops a trace whose exemplar was already recorded at the SDK. When you finish, delete the FAULT_SLOW_PAYMENTS_PCT line from .env and run docker compose --profile telemetry up -d payments, so the latency budget stops burning; keep the metrics.py and payments/app.py changes, which later chapters build on.
DECIDE

Your team runs 40 services. Traces are tail-sampled in the Collector: all errors, all requests over 1 s, and 5% of the rest. Someone proposes turning on exemplars everywhere so on-call can click from any latency panel to a trace. Another engineer says exemplars will mostly point at traces that were dropped, and on-call should start from a TraceQL search instead. What do you do?

READING
  1. PAPER
    CRISP: Critical Path Analysis of Large-Scale Microservice Architectures Zhang, Ramanathan, Raj, Parwal, Sherwood, Chabbi, 2022

    Uber's critical-path tool over 40,000 endpoints. The backward walk in the lab is the same idea; the paper adds clock-skew handling and aggregation of paths across many traces. Read: USENIX ATC 2022: sections 1 to 4 for the algorithm and why span duration misleads; skim the evaluation.

  2. PAPER
    Dapper, a Large-Scale Distributed Systems Tracing Infrastructure Sigelman et al., 2010

    Section 6 is a set of debugging stories that are still the template: inferring service dependencies, finding the long tail, and the limits of a single trace. Read: section 2 for the span model and section 6 for how Google engineers actually used traces to debug latency.

  3. DOC
    Introduction to exemplars Grafana Labs

    How exemplars appear on a panel and how the data source maps the trace id label to Tempo. Short; read it before configuring a production data source.

  4. DOC
    Querying exemplars (Prometheus HTTP API) Prometheus

    The query_exemplars endpoint used in step 3, with the response shape. Useful when you want exemplars in a script or a runbook rather than a panel.

  5. DOC
    TraceQL Grafana Labs

    The full reference: scopes, intrinsics including the link and event ones, structural and union operators, and the pipeline aggregates. Check the version selector against the Tempo you run; operators have been added in most minor releases.

  6. DOC
    Traces: span links (OpenTelemetry concepts) OpenTelemetry

    The official explanation of when a link is right and a parent is wrong, with the batch-processing example. Pair it with the messaging semantic conventions when you reach queues in module four.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: High-cardinality, wide events and the Honeycomb model →