Learning center

A calls B calls C, and all three report timeouts. Which one started it?

Find the deepest service whose own work got slower: its server-side time minus the time it spent waiting on the services it calls. When deadlines are passed down the chain, every hop reports timeouts wherever the slowdown began, so timeout counts and the order of alerts point at the wrong service. If no hop's own work grew, read the deadline each hop received; a budget that shrank everywhere in the same minute points to a configuration change at the top.

The symptom and three explanations#

The example is fictional. A request to storefront calls cart, and cart calls inventory. They use gRPC with deadline propagation. At 14:05 UTC all three started reporting DEADLINE_EXCEEDED, and each team's channel said the problem was somewhere else. Three explanations fit:

  • inventory got slow. The leaf is slower, and its callers run out of time waiting for it.
  • cart got slow. The middle service spends longer on its own work before it calls inventory, which then receives too little time and times out too.
  • storefront's deadline changed. A configuration change lowered the deadline storefront sets on each request, and every hop now has less time for the same work.

Deadline propagation is why all three report timeouts. A gRPC server that calls another server can pass on the deadline of the incoming call; gRPC converts it into a timeout with the time already elapsed deducted, and some languages, Java and Go among them, do this by default. gRPC deadlines The SRE book recommends it so that a deep service gives up on a request its caller has already abandoned. Addressing Cascading Failures The consequence for diagnosis is that the timeout appears at whichever hop is working when the shared budget runs out, which is often the deepest one, whatever spent the budget.

What each explanation predicts#

Observationinventory got slowcart got slowstorefront's deadline changed
Timeouts at each hopall threeall threeall three
inventory's own workrisesunchangedunchanged
cart's own work, excluding its wait on inventoryunchangedrisesunchanged
cart's server-side time, including the waitrisesrisesunchanged
Deadline inventory receivesunchangedshortershorter
Deadline storefront setsunchangedunchangedshorter, from one moment

The first row is the incident channel's evidence, and it is the same in every column. Own work per hop separates the two slowdowns, and the deadline each hop receives separates a slowdown from a configuration change. Server-side time including the wait is not enough on its own: cart's rises when either cart or inventory is slow.

The lab: one chain, three causes#

The script sends 5,000 requests through a chain of three hops at minute 5 and again at minute 15. Each hop does its own work, then passes on what is left of the deadline it received. storefront (A) gives each request 1,000 ms. At minute 10 one thing changes: inventory (C) does ten times as much work in leaf, cart (B) does twenty times as much in middle, and A's deadline drops to 200 ms in config. For each hop it prints the 99th percentile of its own work, the median deadline it received and the share of requests that timed out there. It needs Python 3.8 or later.

import math, random, statistics, sys

def one_request(world, minute, rng):
    """A calls B calls C. Each hop passes on what is left of the deadline it received."""
    changed = minute >= 10                                  # whatever changed, changed at minute 10
    budget = 200 if world == "config" and changed else 1000   # ms that A gives each request
    work = {"A": rng.lognormvariate(math.log(20), 0.4),
            "B": rng.lognormvariate(math.log(30), 0.4) * (20 if world == "middle" and changed else 1),
            "C": rng.lognormvariate(math.log(50), 0.5) * (10 if world == "leaf" and changed else 1)}
    rows, left = {}, budget
    for hop in "ABC":
        rows[hop] = {"budget": left, "self": min(work[hop], left)}
        left -= work[hop]
        if left <= 0:                                       # this hop ran out: it and every caller time out
            for h in rows:
                rows[h]["timeout"] = True
            break
    for h in rows:
        rows[h].setdefault("timeout", False)
    return rows

def summary(world, minute, seed):
    rng = random.Random(seed * 100 + minute)
    reqs = [one_request(world, minute, rng) for _ in range(5000)]
    out = {}
    for hop in "ABC":
        seen = [r[hop] for r in reqs if hop in r]
        out[hop] = (statistics.quantiles([s["self"] for s in seen], n=100)[98],
                    statistics.median(s["budget"] for s in seen),
                    sum(s["timeout"] for s in seen) / len(seen))
    return out

if len(sys.argv) < 2 or sys.argv[1] not in ("leaf", "middle", "config"):
    sys.exit("usage: python3 chain.py leaf|middle|config [seed]")
world = sys.argv[1]
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 4
before, after = summary(world, 5, seed), summary(world, 15, seed)
print(f"world={world}   (minute 5 -> minute 15)")
for label, i, fmt in (("own work p99 ms", 0, "{:5.0f}"), ("budget p50 ms", 1, "{:5.0f}"), ("timeouts", 2, "{:5.1%}")):
    cells = [f"{h}: " + fmt.format(before[h][i]) + " -> " + fmt.format(after[h][i]) for h in "ABC"]
    print(f"  {label:16s}" + "   ".join(cells))

Save it as chain.py. Before you run it, write down which hop's own work will change in each world, and whether C's timeout share will rise in all three. Then run:

for world in leaf middle config; do python3 chain.py "$world"; done

Python 3.11 printed:

world=leaf   (minute 5 -> minute 15)
  own work p99 ms A:    50 ->    51   B:    74 ->    75   C:   159 ->   964
  budget p50 ms   A:  1000 ->  1000   B:   980 ->   980   C:   948 ->   948
  timeouts        A:  0.0% ->  9.6%   B:  0.0% ->  9.6%   C:  0.0% ->  9.6%
world=middle   (minute 5 -> minute 15)
  own work p99 ms A:    50 ->    51   B:    74 ->   988   C:   159 ->   163
  budget p50 ms   A:  1000 ->  1000   B:   980 ->   980   C:   948 ->   408
  timeouts        A:  0.0% -> 13.8%   B:  0.0% -> 13.8%   C:  0.0% ->  3.9%
world=config   (minute 5 -> minute 15)
  own work p99 ms A:    50 ->    51   B:    74 ->    75   C:   159 ->   148
  budget p50 ms   A:  1000 ->   200   B:   980 ->   180   C:   948 ->   148
  timeouts        A:  0.0% ->  1.9%   B:  0.0% ->  1.9%   C:  0.0% ->  1.9%

Every world produced timeouts at every hop. In middle, C timed out on 3.9% of the requests that reached it although its own work did not change, because the deadline it received fell from 948 ms to 408 ms. Own work moved at exactly one hop in each slowdown, C in leaf and B in middle, and at none in config, where only the deadlines moved, all by the same 800 ms. C's own work in config reads slightly lower because work cut off at the deadline is counted only up to the deadline.

The prediction fails if own work rises at a hop that did not change, or if the deadlines move in leaf. Run python3 chain.py middle 8 to try another seed.

Read it on a real system#

Own work per hop is clearest in traces: a span's duration minus the time covered by its child spans. Choose a slow trace from after the change and one from before, and compare each service's server span with its client spans to the next hop. Which trace span is on the critical path?

Metrics give the same comparison per service when each one records both sides. OpenTelemetry's HTTP conventions define http.server.request.duration for the time a server spends on a request and http.client.request.duration for calls a client makes, with server.address naming the callee. OpenTelemetry HTTP metrics gRPC's own metrics are grpc.server.call.duration and grpc.client.call.duration. gRPC OpenTelemetry metrics With Prometheus, and your own label for the service:

histogram_quantile(0.99,
  sum by (le, service) (rate(http_server_request_duration_seconds_bucket[5m])))

histogram_quantile(0.99,
  sum by (le, service, server_address) (rate(http_client_request_duration_seconds_bucket[5m])))

Percentiles do not subtract, so the gap between a service's server-side p99 and its client-side p99 to the next hop is not its own-work p99. Read the trend instead: in a cart slowdown, cart's server-side time rises while its client-side time to inventory stays flat, and in an inventory slowdown both rise by about the same amount.

The deadline each hop receives is visible only if someone logs it. In Go, ctx.Deadline() returns the deadline of the incoming request's context, and logging the time remaining at the start of each request gives the third row of the table. Go context A gRPC server that misses the deadline sees the call cancelled, while the client sees DEADLINE_EXCEEDED, so the same event carries different status codes on the two sides. gRPC deadlines

Without propagation, each hop has its own fixed timeout, and those need to nest. List each caller's timeout beside the time its callee may spend, including the callee's own timeout to the next hop. The SRE book describes the failure when they do not nest: a caller gives up while its callee keeps working under a longer, hard-coded timeout, doing work nobody will use. The Builders' Library suggests setting a timeout from the downstream service's latency at a chosen percentile, such as p99.9 for an accepted 0.1% of false timeouts. Timeouts, retries, and backoff with jitter

Limits#

Own work includes everything a service's timer covers that is not a call to an instrumented callee. Waiting for a pooled connection, a lock or an uninstrumented dependency counts as own work, so a hop can look slow on its own when it is waiting on something else. A client can also time a call as slow that the server handled quickly. Is the dependency slow, or the client?

Fan-out changes the arithmetic. A service that calls several others in parallel waits only for the slowest, and one that retries a call spends the budget more than once; a retry storm after a slowdown can keep every hop short of time after the first cause has passed. Errors that persist after the dependency recovers

Sampled traces can miss the slow requests, and a timeout that cuts a span short records less time than the work would have taken, as C did in the lab's config world. The method behind the table is in Choose the observation where explanations disagree.

Questions#

Why does a service that did not change report timeouts?

With deadline propagation, every hop works against what is left of one budget. When a hop above it spends more of that budget, the deadline it receives shrinks, and work that used to fit no longer does. In the lab's middle world, C's own work was unchanged and it still timed out on 3.9% of its requests.

Which service's timeout alert fired first, and does that matter?

The first alert shows which hop crossed its alert threshold first, which depends on thresholds and traffic as much as on the cause. Compare own work per hop instead; the deepest hop whose own work rose is the best candidate for where it started.

Should a caller's timeout be longer than its callee's?

Yes, when timeouts are fixed per hop: the caller's timeout should cover the callee's whole time, including the callee's own timeout to the services it calls. Otherwise the caller gives up while the callee keeps working. Propagating one deadline through the chain avoids setting each by hand.

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