Learning center

Why do our errors continue after the dependency has recovered?

Retries may hold the recovered dependency in overload, pooled connections may have died in the outage, or a backlog from the outage may still be draining. Count attempts per logical request and compare the load that reaches the dependency with its capacity. Retries that hold the dependency in overload show attempts near the retry limit and load above capacity, and service returns soon after retries are cut; dead connections show about one attempt per request, errors only on connections older than the outage, and no improvement when retries stop.

The symptom and three explanations#

The example is fictional. The ledger service's database stalled from 09:12:00 to 09:12:40 UTC. By 09:14 the ledger team's dashboard showed its usual request rate, no errors and a p99 of 45 ms. At 09:30 the checkout service, which calls ledger, was still failing 38% of its calls with timeouts. The incident channel had three explanations:

  • Retries hold it in overload. checkout retries a timed-out call three times. During the stall the retries piled up, and the extra attempts keep ledger above its capacity. ledger spends its time on requests whose callers have already given up.
  • Dead connections. The stall broke some of checkout's pooled connections without closing them. Requests sent on them never get an answer, and the pool keeps handing them out.
  • A backlog still draining. Work queued during the stall, in ledger or in checkout's own workers, is ahead of new requests. It clears at the rate of the spare capacity, then the errors stop.

The ledger dashboard can look healthy under all three. A server that keeps working on a request after its client timed out still records a success: from the server's side it returned a response, while the client counted an error. Using load shedding to avoid overload Requests dropped before the server accepted them, in a full listen queue, never reach its metrics at all. A full listen queue

What each explanation predicts#

ObservationRetries hold it in overloadDead connectionsBacklog draining
Our error rate to the dependencyhigh and flathigh, falling as the pool recycleshigh and falling
The dependency's own error rate and latencynormalnormalnormal
Attempts per logical requestnear the retry limita little above 1about 1
Load reaching the dependency ÷ its capacityabove 1below 1below 1
Errors by connection ageon every connectiononly on connections opened before the outage endedon every connection
Errors after retries are cutstop within a minute or tworiselittle change
When it ends without actionnot at allwhen the pool replaces the old connectionsafter backlog ÷ spare capacity

The first two rows are what the incident channel was reading. The second is the same under all three explanations, and a slowly falling error rate fits both dead connections and a backlog. Attempts per logical request and the load-to-capacity ratio separate retries from the other two. Errors by connection age separate dead connections from a backlog.

Retries can hold a recovered system down because each retry is new load. The Builders' Library describes retries as "selfish": when failures come from overload, retries add load and can delay recovery by keeping the load high after the original problem is gone. Timeouts, retries, and backoff with jitter The SRE book's chapter on cascading failures adds that a return to normal traffic may not be enough when the backend spends its time on requests that will fail, and that the way out is to cut load sharply until the retries stop. Addressing Cascading Failures Retries also multiply across layers: with three retries at each of three layers, one user action can reach the database 64 times, according to the same chapter.

The lab: one stall, three ways to stay broken#

The script simulates a dependency that serves 1,000 requests a second, and a client that sends 800 new requests a second with a 2-second timeout. The dependency holds up to five seconds of work in its queue and drops connects beyond that. It processes nothing from second 60 to second 70. From second 150 the client sends no more retries. The worlds differ in the client:

  • backlog: the client never retries.
  • retries: the client retries a failed call up to three times, after a one- or two-second pause.
  • deadpool: the client retries, but within a budget of retries equal to 10% of new requests. The stall kills 6 of its 20 pooled connections, and the pool replaces each connection only when it reaches 200 seconds of age.

It needs Python 3.8 or later.

import collections, random, sys

C, L, T = 1000, 800, 2      # dependency capacity/s, new requests/s, client timeout (s)
QMAX = 5 * C                # requests the dependency holds waiting; beyond this, connects are dropped
STALL = range(60, 70)       # the dependency processes nothing in these seconds
CUT = 150                   # from this second the client sends no retries
POOL, LIFETIME = 20, 200    # client connections, and how long each lives before the pool replaces it

def run(world, seed=1, end=240):
    rng = random.Random(seed)
    max_retries = 0 if world == "backlog" else 3
    budget = 0.1 * L if world == "deadpool" else None   # retries per second allowed
    opened = [-10 * i for i in range(POOL)]
    dead = [False] * POOL
    queue = collections.deque()                 # attempts waiting at the dependency
    served = set()                              # attempts answered within the client's timeout
    timeouts = collections.defaultdict(list)    # second -> attempts that time out then
    due = collections.defaultdict(list)         # second -> retries to send then
    w = collections.Counter()
    rows, rid = [], 0
    for t in range(end):
        for i in range(POOL):                   # the pool replaces connections at their lifetime
            if t - opened[i] >= LIFETIME:
                opened[i], dead[i] = t, False
        if world == "deadpool" and t == STALL.start:
            for i in rng.sample(range(POOL), 6):    # the stall silently kills 6 connections
                dead[i] = True
        sends = [(rid + k, 0) for k in range(L)] + due.pop(t, [])
        rid += L
        w["new"] += L
        for req, attempt in sends:
            w["sent"] += 1
            conn = rng.randrange(POOL)
            key = (req, attempt, conn)
            if dead[conn]:
                w["err_old" if opened[conn] < STALL.stop else "err_new"] += 1
            elif len(queue) < QMAX:
                w["offered"] += 1
                queue.append((t, key))
            else:
                w["offered"] += 1               # dropped at the dependency's listen queue
            timeouts[t + T].append(key)
        if t not in STALL:
            for _ in range(min(C, len(queue))):
                enq, key = queue.popleft()
                w["work"] += 1
                if t - enq <= T:
                    served.add(key)
        retries_left = budget
        for key in timeouts.pop(t, []):
            if key in served:
                served.discard(key)
                w["ok"] += 1
                continue
            req, attempt, _ = key
            if attempt < max_retries and t < CUT and (retries_left is None or retries_left >= 1):
                if retries_left is not None:
                    retries_left -= 1
                due[t + rng.randint(1, 2)].append((req, attempt + 1))
            else:
                w["failed"] += 1
        if (t + 1) % 30 == 0:
            done = w["ok"] + w["failed"]
            rows.append(f"  {t-29:3d}-{t:3d}s  offered/C {w['offered']/(30*C):4.2f}  attempts/req "
                        f"{w['sent']/w['new']:4.2f}  ok {w['ok']/done:6.1%}  busy {w['work']/(30*C):4.0%}  "
                        f"dead-conn errors old/new {w['err_old']}/{w['err_new']}")
            w.clear()
    print(f"world={world}")
    print("\n".join(rows))

if len(sys.argv) < 2 or sys.argv[1] not in ("backlog", "retries", "deadpool"):
    sys.exit("usage: python3 stuck.py backlog|retries|deadpool [seed]")
run(sys.argv[1], seed=int(sys.argv[2]) if len(sys.argv) > 2 else 1)

Save it as stuck.py. Before you run it, write down your prediction for each world: does it recover before second 150, and does it recover at 150? Then run:

for world in backlog retries deadpool; do python3 stuck.py "$world"; done

Python 3.11 printed:

world=backlog
    0- 29s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   30- 59s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   60- 89s  offered/C 0.80  attempts/req 1.00  ok  38.3%  busy  67%  dead-conn errors old/new 0/0
   90-119s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  81%  dead-conn errors old/new 0/0
  120-149s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
  150-179s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
  180-209s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
  210-239s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
world=retries
    0- 29s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   30- 59s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   60- 89s  offered/C 2.64  attempts/req 3.30  ok  10.3%  busy  67%  dead-conn errors old/new 0/0
   90-119s  offered/C 3.20  attempts/req 4.00  ok   0.0%  busy 100%  dead-conn errors old/new 0/0
  120-149s  offered/C 3.20  attempts/req 3.99  ok   0.0%  busy 100%  dead-conn errors old/new 0/0
  150-179s  offered/C 0.92  attempts/req 1.15  ok  45.7%  busy  95%  dead-conn errors old/new 0/0
  180-209s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
  210-239s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
world=deadpool
    0- 29s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   30- 59s  offered/C 0.80  attempts/req 1.00  ok 100.0%  busy  80%  dead-conn errors old/new 0/0
   60- 89s  offered/C 0.61  attempts/req 1.09  ok  41.2%  busy  56%  dead-conn errors old/new 7809/0
   90-119s  offered/C 0.65  attempts/req 1.10  ok  80.5%  busy  65%  dead-conn errors old/new 6980/0
  120-149s  offered/C 0.71  attempts/req 1.10  ok  87.5%  busy  71%  dead-conn errors old/new 5234/0
  150-179s  offered/C 0.68  attempts/req 1.00  ok  84.9%  busy  68%  dead-conn errors old/new 3661/0
  180-209s  offered/C 0.70  attempts/req 1.00  ok  87.6%  busy  70%  dead-conn errors old/new 2882/0
  210-239s  offered/C 0.76  attempts/req 1.00  ok  94.4%  busy  76%  dead-conn errors old/new 1201/0

The backlog world recovered inside the window that held the stall and stayed recovered. The retries world served nothing useful for 80 seconds after the dependency came back, with the dependency 100% busy on requests whose callers had already timed out; offered load was 3.2 times capacity and every logical request used all four attempts. Cutting retries at second 150 brought it back within one window. The deadpool world kept attempts near 1 and offered load below capacity. All its dead-connection errors were on connections opened before the stall ended, cutting retries lowered its success rate from 87.5% to 84.9%, and its errors fell only as the pool replaced the old connections.

The prediction fails if the retries world recovers on its own before second 150, if it stays broken after the cut, or if the deadpool world recovers at the cut. Run python3 stuck.py retries 7 to change the seed. To find the trigger, change STALL to range(60, 62) and then range(60, 63): with this model, a two-second stall recovers by itself and a three-second stall, one second longer than the client's timeout, does not.

Read it on a real system#

Attempts per logical request need two counters from the client: one per call the code makes, one per attempt the client library sends. gRPC's OpenTelemetry metrics provide both, grpc.client.attempt.started and grpc.client.call.duration, each labelled with the channel's grpc.target. gRPC retry · gRPC OpenTelemetry metrics Exported names differ by exporter; with Prometheus, the ratio looks like this:

sum(rate(grpc_client_attempt_started_total{grpc_target=~".*ledger.*"}[5m]))
  /
sum(rate(grpc_client_call_duration_seconds_count{grpc_target=~".*ledger.*"}[5m]))

An HTTP client usually needs a counter added around the retry loop. The server can count attempts too if callers send an attempt number in the request metadata, as the SRE book's chapter on handling overload describes. Handling Overload

Offered load is what reached the dependency, including what it dropped. Its accepted request rate is on its dashboard; drops before accept show in the kernel's listen-queue counters, which the listen queue guide reads. Read the queue and the counters Compare the sum with the highest rate the dependency has sustained, from a load test or a past peak.

Errors by connection age need the client to log a connection identifier, or its local port, with each error. Group the errors by whether that connection was opened before the outage ended. To check whether the pool or the resolver still points at an old address, compare the open connections' remote addresses with the address the name resolves to now. Compare the resolved address with the open connections

Cutting retries changes production. Do it through the client's configuration, and record the time. The AWS SDKs' standard retry mode includes a retry quota, a token bucket that stops retries when it runs out while never delaying the first attempt, and gRPC has a comparable retry throttle. AWS SDK retry behavior · gRPC retry Either keeps a recovered dependency from being held down by its callers' retries.

Limits#

The test of cutting retries is only clean if nothing else changes in the same minute. If the dependency's owners restart it, or autoscaling adds capacity, as retries are cut, recovery cannot be credited to either. Change one thing at a time and record each change with its time. Choose the observation where explanations disagree

More than one caller can hold a dependency down. Your own client's attempts per request can be 1.0 while another team's client retries four times. Read the dependency's request rate by caller before deciding that retries are not involved.

A slow recovery alone does not prove that retries hold the dependency down. A client with a retry limit and no budget can recover by itself after a short outage, as the two-second stall in the lab did; offered load above capacity and the response to the cut are the evidence.

Questions#

Why does the dependency's dashboard show success while our calls time out?

The dependency counts a request as a success when it returns a response, even if the caller gave up before it arrived. Requests that waited in its queue past the caller's timeout are wasted work that looks healthy from its side. Compare its served rate with the rate of successes your client actually received.

How do we get out of a retry-driven overload?

Reduce the load below capacity until the retries stop: lower the retry limit, enable a retry budget, or shed a share of traffic at the edge. Adding capacity can also work, but the SRE book notes that a service in a death spiral may not recover from added resources alone. Addressing Cascading Failures Restore normal retry settings only once offered load is back below capacity.

Does exponential backoff with jitter prevent this?

It spreads retries out in time, so clients do not all retry at the same instant. It does not cap the number of attempts, so a client that retries every failure still adds load to an overloaded dependency. A per-request limit plus a client-wide retry budget bounds the extra load.

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