Learning center

The slowest span in a trace. Did it make the request slow?

The longest bar in a trace is the cause of a slow request only if the request was waiting for it. It may instead have run in parallel with a longer chain of calls, in which case making it faster saves nothing, or the request's time may sit in gaps between spans, where queueing or uninstrumented work happened. Compute the critical path, the chain of spans the request actually waited on, and the time on that path that no child span covers.

The symptom and three explanations#

A fictional GET /checkout endpoint takes about a second at p99. The team opened a slow trace, saw that the longest child span was recommendations at 700 ms, and proposed caching recommendations. Before anyone writes the cache, three explanations fit that trace view:

  • The slow span is on the critical path. The request waited for it, and a faster recommendations would make the request faster.
  • It ran in parallel with a longer chain. recommendations overlapped with cart, pricing and the pricing database call, and the request was waiting for that chain, not for it.
  • Gaps dominate. Much of the second is in no child span at all: the handler's own work, waiting for a worker or a connection, or code with no instrumentation.

The trace waterfall shows all three the same way: bars of different lengths under one root. The question is which bars the root waited on.

What each explanation predicts#

ObservationSlow span is criticalParallel with a longer chainGaps dominate
Longest child spanrecommendationsrecommendationsany
Its time on the critical pathmost of its durationlittle or noneits duration, but small against the root
A sibling chain that ends later and covers itnoyesno
Root time on the critical path with no child spansmallsmalllarge
Effect of making the span 300 ms fasterrequest about 300 ms fasternonesmall

The critical-path row separates the first two, and the uncovered-time row identifies the third. Neither needs more data than the trace already holds: each span's parent, start and end. OpenTelemetry defines a span by those fields, and a span's start and end timestamps "reflect the elapsed real time of the operation". OpenTelemetry tracing API

The lab: three traces of one endpoint#

The script holds three traces of GET /checkout, each one second long, written as (span, parent, start ms, end ms). It walks each trace backwards from the root's end. At every point it asks which child the parent was waiting for, taking the child that finished last before that point, and charges the time between children to the parent itself. The time charged to the root is time in no child span. It needs Python 3.8 or later.

from collections import defaultdict

# (span, parent, start ms, end ms), as a trace backend would export them
TRACES = {
    "A": [("GET /checkout", None, 0, 1000), ("auth", "GET /checkout", 10, 50),
          ("cart", "GET /checkout", 55, 200), ("pricing", "GET /checkout", 205, 900),
          ("pricing db", "pricing", 220, 850), ("payment", "GET /checkout", 905, 990)],
    "B": [("GET /checkout", None, 0, 1000), ("auth", "GET /checkout", 10, 50),
          ("recommendations", "GET /checkout", 60, 760), ("cart", "GET /checkout", 60, 300),
          ("pricing", "GET /checkout", 305, 900), ("pricing db", "pricing", 320, 880),
          ("payment", "GET /checkout", 905, 990)],
    "C": [("GET /checkout", None, 0, 1000), ("auth", "GET /checkout", 10, 50),
          ("cart", "GET /checkout", 60, 200), ("pricing", "GET /checkout", 210, 450),
          ("payment", "GET /checkout", 900, 980)],
}

def critical_path(spans, name, cursor, path):
    """Walk back from cursor: the child that finished last before it is what the parent waited for."""
    _, _, start, _ = spans[name]
    kids = [k for k, (_, parent, _, _) in spans.items() if parent == name]
    while True:
        waiting = [k for k in kids if spans[k][3] <= cursor] or [k for k in kids if spans[k][2] < cursor]
        if not waiting:
            break
        k = max(waiting, key=lambda k: min(spans[k][3], cursor))
        k_end = min(spans[k][3], cursor)
        path[name] += cursor - k_end              # the parent's own time: no child running
        critical_path(spans, k, k_end, path)
        cursor = spans[k][2]
        kids.remove(k)
    path[name] += cursor - start

for trace, rows in TRACES.items():
    spans = {r[0]: r for r in rows}
    path = defaultdict(int)
    critical_path(spans, "GET /checkout", 1000, path)
    slowest = max((r for r in rows if r[1]), key=lambda r: r[3] - r[2])
    print(f"trace {trace}: slowest child span {slowest[0]} ({slowest[3] - slowest[2]} ms)")
    for name, ms in sorted(path.items(), key=lambda kv: -kv[1]):
        if ms:
            note = "  <- no child span: own work, queueing or uninstrumented" if name == "GET /checkout" else ""
            print(f"  {ms:4d} ms on the critical path in {name}{note}")
    off = [r[0] for r in rows if r[1] and path[r[0]] == 0]
    print(f"  not on the critical path: {', '.join(off) or 'none'}")

Save it as critical.py. For each trace, read the spans and write down which one will contribute the most time to the critical path. Then run python3 critical.py. Python 3.11 printed:

trace A: slowest child span pricing (695 ms)
   630 ms on the critical path in pricing db
   145 ms on the critical path in cart
    85 ms on the critical path in payment
    65 ms on the critical path in pricing
    40 ms on the critical path in auth
    35 ms on the critical path in GET /checkout  <- no child span: own work, queueing or uninstrumented
  not on the critical path: none
trace B: slowest child span recommendations (700 ms)
   560 ms on the critical path in pricing db
   240 ms on the critical path in cart
    85 ms on the critical path in payment
    40 ms on the critical path in GET /checkout  <- no child span: own work, queueing or uninstrumented
    40 ms on the critical path in auth
    35 ms on the critical path in pricing
  not on the critical path: recommendations
trace C: slowest child span pricing (240 ms)
   500 ms on the critical path in GET /checkout  <- no child span: own work, queueing or uninstrumented
   240 ms on the critical path in pricing
   140 ms on the critical path in cart
    80 ms on the critical path in payment
    40 ms on the critical path in auth
  not on the critical path: none

Each trace's contributions add up to its 1,000 ms. In trace A the slowest span, pricing, is on the path, and most of its time is its database call. In trace B the slowest span, recommendations, contributes nothing: pricing started after cart finished, and payment after pricing, so the request waited on that chain while recommendations ran beside it. A recommendations cache would not have moved trace B's latency. In trace C, half the request is in the root with no child span, between pricing ending at 450 ms and payment starting at 900 ms.

The prediction fails if recommendations shows time on trace B's critical path. To see the condition under which it would, change its end from 760 to 995, after payment ends: it then takes 935 ms of the path and cart, pricing and payment drop off.

Read it on a real system#

Export the slow trace from your tracing backend as JSON and feed its spans to the same function, keyed by span ID instead of name. In the OTLP JSON encoding, spans carry spanId, parentSpanId, startTimeUnixNano and endTimeUnixNano, with IDs hex-encoded and timestamps as decimal strings. OTLP specification

jq -r '.resourceSpans[].scopeSpans[].spans[]
       | [.spanId, .parentSpanId, .name, .startTimeUnixNano, .endTimeUnixNano] | @tsv' trace.json

On AWS X-Ray, aws xray batch-get-traces --trace-ids TRACE_ID returns the trace's segment documents, which hold the same start, end and parent information. batch-get-traces

Read one trace, then a handful. A single slow trace can be an outlier with its own critical path; the span that appears on the critical path of most slow traces is the one worth changing. When the root's uncovered time is large, add spans where the gap is: around the handler's own work, the wait for a worker or connection, and serialization. A span on a client call that is much longer than the server's span for the same call is itself a gap: time between the client starting the call and its code running again. Dependency slow for the client but fast on the server

Limits#

Spans from different hosts use different clocks. A child that appears to start before its parent, or a gap of a few milliseconds that should not exist, may be clock skew between the services. The walk above trusts timestamps across hosts, so a skew larger than the gaps you are reading makes its answer unreliable. Log timestamps out of order

The walk assumes a parent waits for the child that finished last before it moved on. Work that the parent started and did not wait for, such as a background publish that outlives the request, can look like a child the parent waited on if it ends just before something else starts. OpenTelemetry has span links for relating spans outside a parent-child relationship, and instrumentation that uses them for detached work makes this clearer. OpenTelemetry traces

A span's duration can include time when its thread could not run, such as a garbage collection pause, so a long span on the critical path still needs its own explanation. GC pause or a slow dependency? For the general method, see Choose the observation where explanations disagree.

Questions#

What is the critical path of a trace?

The chain of spans that the request was waiting on from its start to its end. Shortening a span on it shortens the request, up to the point where another chain becomes the longest. Shortening a span off it changes nothing for that request.

What does a gap between spans in a trace mean?

Time the parent spent with no child span running: its own computation, waiting for a thread, a connection or a lock, or calls nobody instrumented. A large gap on the critical path is a reason to add spans before optimising anything that is already measured.

Is span self-time the same as critical path time?

No. Self-time is a span's duration minus the time its children cover, whether or not the request waited for it. Critical path time counts only what the request waited for, so a span running in parallel can have large self-time and no critical path time.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading