retrystack

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: MIT

README

retrystack: find nested retries and retry storms in Go, Envoy and Istio

ci Go Reference

retrystack is a static analysis tool that finds stacked retry layers on the same outbound call and multiplies them into a worst-case attempt count per call, before an incident. It looks at hand-rolled retry loops, retry helpers, retry libraries (go-retryablehttp, avast/retry-go, cenkalti/backoff, the AWS SDK), and the retry policy of the Envoy or Istio sidecar in front of the call.

Retries multiply. Three layers of "retry 3 times" send 27 requests for one logical call, and nobody sees it until the downstream is already failing. That's how a small outage turns into a retry storm (retry amplification). Under normal load, traces show zero retries, so you can't find it from dashboards.

internal/tools/create_image.go:314  worst case 6 attempt(s) per call
  1. code-wrapper x 2   tools.ExecuteWithChain  create_image.go:314 (loop media_provider_chain.go:207)  (no backoff)
  2. code-wrapper x 3   providers.RetryDo       codex_native_image.go:41 (loop retry.go:107)
  -> net/http (*Client).Do at internal/providers/codex_build.go:166

That's goclaw issue #254 ("config says max_retries: 2 but the real backend hit count is 6"), found from source code with -value max_retries=2. The issue author found it from a production trace.

Install

go install github.com/thejusdutt/retrystack/cmd/retrystack@latest

Or download a binary from Releases. You need a Go toolchain on the machine either way: retrystack loads your module with go/packages. Use a Go version at least as new as your module's go line.

Quick start

retrystack -dir path/to/module                   # stacks of 2+ retry layers, and unbounded retry loops
retrystack -dir . -all                           # also single-layer findings
retrystack -dir . -value max_retries=2           # fill in a count that comes from config
retrystack -dir . -routes routes.yaml            # add Envoy / Istio retry layers
retrystack -dir . -format json                   # machine-readable output

The number is an upper bound over the layers it detects. It isn't an estimate. When a count comes from config and isn't known, the finding says so ([unresolved]) and uses the largest default it saw in code.

To add the mesh layer, write a small routes file that says which sidecar config applies to which outbound URL:

routes:
  - url: http://envoy:10000      # URL prefix the code calls
    envoy: envoy.yaml            # Envoy static config; the route on that port
  - url: http://payments
    istio: virtualservices.yaml
    host: payments               # VirtualService host; attaches at the caller's sidecar

Istio's default retry policy is version-aware (-istio-version, default 1.27; 1.26 and older also retry 503).

Use it in CI

Fail the build when a call can be sent more than N times, or when a retry stack has no bound:

# .github/workflows/retrystack.yml
name: retrystack
on: [pull_request]
jobs:
  retries:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
      - run: go install github.com/thejusdutt/retrystack/cmd/retrystack@latest
      - run: retrystack -dir . -max-attempts 10 -fail-on-unbounded

Exit codes: 0 nothing over the limits, 1 a gate tripped, 2 the scan failed. Add -fail-on-unresolved to also fail when a count or host can't be resolved.

Flags on findings:

flag meaning
nested-retries two or more layers retry the same call
unbounded a layer has no bound, or only a time bound
no-backoff a code layer retries without sleeping
retry-ignores-context sleeps between tries but never checks ctx, so it keeps going after the caller gave up
mesh-retries-exceed-route-timeout per-try timeout × attempts is longer than the route timeout
inner-retries-exceed-outer-timeout an inner library's own backoff is longer than the outer per-try timeout

assumes: lines say where a number rests on an assumption, including every over-approximated call edge (via interface/func value: N candidates, via CHA fallback, via callback traced through call sites).

What it detects

layer examples how the count is read
hand-rolled loop for i := 0; i < n; i++ { … if err == nil { break } }, failover over replicas loop counter exits, resolved through constants, call-site arguments, struct fields and config-tagged fields
retry helper in your code RetryDo(ctx, cfg, fn) the helper's loop, bound resolved at each call site
avast/retry-go v4, v5 retry.Do(fn, retry.Attempts(3)) 10 by default, Attempts(n), Attempts(0) / UntilSucceeded() = no limit
cenkalti/backoff v3, v4, v5 backoff.Retry(op, backoff.WithMaxRetries(b, 4)) WithMaxRetries(n) = n+1, WithMaxTries(n), MaxElapsedTime (15 min default, 0 = never stops)
hashicorp/go-retryablehttp client.RetryMax = 3 RetryMax on that client object, default 4 (5 attempts)
aws-sdk-go-v2 any service client call standard retryer, 3 attempts unless RetryMaxAttempts is set
Envoy (static config) retry_policy on a route num_retries + 1, per failure class
Istio VirtualService retries.attempts, or the Istio default per failure class, version-aware default

Outbound calls: net/http, go-retryablehttp, gRPC ClientConn.Invoke / NewStream, aws-sdk-go-v2 operations.

How well it works

Full numbers, method and caveats are in RESULTS.md. In short:

  • Real bug, dynamic: goclaw #254 reproduced with goclaw's own code: 6 backend hits before the fix, 2 after (eval/t1b).
  • Real bug, static: retrystack finds that stack with the right file:line for both layers and prints 6 with max_retries=2 (eval/t1a). It also finds loki's index-gateway failover loop (eval/t1c), but loki was used during development, so that isn't an independent test.
  • Docker harness with real Envoy and real libraries, predictions committed before measuring: 17 measured edges, 15 exact, 2 over-predictions (both flagged), 0 upper-bound violations, 0 misses, 4/4 false-positive controls.
  • Against existing tools on the same inputs: meshscan flags 6 of 10 VirtualServices with no numbers and misses the 3-layer case. istioctl analyze reports nothing. The best single-layer count is below the measured count on 8 of 17 edges.
  • Precision on real repos the tool wasn't tuned on (first sweep): 3/3 correct on the two repos inside the memory budget, but only 9/40 (22.5%) on large repos, and those 9 are 3 distinct retry loops. The biggest source of false positives is event and worker loops that log an error and carry on.
  • Held-out sweep (10 more repos, picked by a fixed rule, labelled by two independent labellers): only 3 nested findings; 2 correct (kappa 1.0). Neither correct finding had every layer bounded, so the multiplication itself is still checked only in the Docker harness. The labellers also found an under-count by one (a first attempt before a failover loop) and an over-count (a retryablehttp client configured through a helper).

How it works

  1. Loads the whole Go module (go/packages), builds SSA and a VTA call graph.
  2. Finds natural loops and marks a loop as a retry region when an err check on a call sends control back to the loop header, and either success leaves the loop (retry or failover) or the call's inputs don't change per iteration. Pagination and one-request-per-item loops aren't retries.
  3. Reads the bound from a counter exit that runs on every trip (i < N, i <= N, a test after the call, range offsets). Values resolve through constants, parameters at call sites, struct fields and config-tagged fields (json, yaml, …; reported as config-driven, with the defaults seen in code).
  4. A retry wrapper (a loop around a func parameter, like RetryDo(ctx, cfg, fn), or a retry-library call) is anchored at each call site, with the bound resolved from that call's arguments.
  5. Walks from every loop body to outbound calls, skipping go and defer, at most 6 hops. Library defaults are layers too.
  6. With a routes file, adds the Envoy route or Istio VirtualService layer for the call's host. Retries multiply per failure class (connect, 503, other 5xx, timeout). Code layers count as retrying every error.

Compared with other tools

tool what it does what it doesn't do
meshscan 8 Istio checks one retry check, "retries without timeout" on one VirtualService; no numbers, no code layers
istioctl analyze, Kiali validations Istio config validation no rule about retries or timeouts
thunderstruck LLM-based Claude Code plugin; finds stacked retries in one code path no config, no library defaults, no mesh + code composition; detectors for TS/JS/Python/Java only
WASABI (SOSP '24) retry bugs inside one Java codebase doesn't compose layers
Envoy/Istio/Linkerd retry budgets, AWS SDK retry quota cap retries at runtime mitigations, not analysis; nothing tells you which calls lack them
tracing, chaos tools (Gremlin, Steadybit, Filibuster) show amplification during an incident or an experiment normal-load traces show 0 retries; you have to know where to inject

retrystack fills a narrow gap: it inventories retry layers across app code, library defaults and mesh config, composes them along each outbound call, and prints a worst-case count per call before an incident.

Real incidents where stacked retries were the problem:

  • GitHub, 2026-08-17, 7 h 47 m outage. A client retry loop amplified Copilot Token Service traffic about 10× (7-9k → 70-100k RPS). The mitigation included "temporarily reducing gateway retries", and the follow-up is "consistent retry limits, retry budgets … across service-to-service interactions". GitHub, The Register. The retry bug there was in VS Code, a desktop client, which a scan of GitHub's own services wouldn't have seen.
  • goclaw #254 (2026-06-09): a YAML-driven chain loop wraps a hard-coded RetryDo{Attempts: 3}; 6-15 minute hangs in production. issue
  • grafana/loki #24051 (2026-08-18): the index-gateway poolDo walks every replica (maxRetries = -1 on six of seven RPCs) while the pool is shedding load. issue
  • arXiv 2608.25403 (Aug 2026): across 113 retry configurations in Python microservices, 60.9% had no backoff, 1 had jitter, and "no project coordinates retry decisions across a service boundary". paper

Limitations

  • Go only. Gateway API HTTPRoute, gRPC service config, Linkerd, nginx and HAProxy retry layers aren't parsed.
  • One edge at a time. A→B and B→C are reported separately; the tool doesn't multiply across service hops.
  • Upper bound, sometimes loose. Retry limits carried in a context value (goclaw's actual fix) are shown as conditional-on-context but still counted. Timeouts that cut a retry sequence short aren't subtracted (harness 12b: predicted 3, measured 2).
  • Every error counts as retryable. IsRetryableError-style filters and retry.RetryIf aren't read.
  • Known misses: loops that ignore err and re-poll on a status field; retry libraries not in the table (grpc-go retry policy, SDKs that retry internally, like openai-go); hosts built from runtime config (reported as unresolved and matched to the worst route).
  • Event loops can look like retries. for { select { … } } loops that log an error and continue pass the retry test. A goto retry cycle is reported twice: once from its header and once from the event loop inside it.
  • Over-approximation. Interface and func-value calls can connect a retry loop to calls it never makes on that request. Every such edge is listed under assumes:.
  • Build it with a new enough Go. A retrystack built with Go 1.26 can't load code that needs Go 1.27. cgo packages load only where a C compiler is available.
  • Memory. Whole-program SSA + VTA: goclaw 4.7 GB and ~50 s, loki 11.4 GB, consul 22 GB. Most large repos need more than 8 GB. go.work multi-module repos (etcd) load only a few packages.
  • Determinism needs one P. Parallel loading made findings vary between runs, so the tool pins GOMAXPROCS=1.

Known bugs, not fixed yet. Each has an input that shows it:

  • A call result made inside the loop from invariant values counts as invariant (job := q.Pop()). Treating it as varying would break req, _ := http.NewRequest(...) inside a retry loop, which is far more common.
  • A summary can be memoized while one of its callers is still being computed, so the result can depend on visit order. GOMAXPROCS=1 hides this. It doesn't fix it.
  • Any select in a loop marks it as having backoff, so no-backoff is missed on loops that select on a channel with no timer.
  • A count-down loop from a non-constant start (for n := cfg.Retries; n > 0; n--) gets no bound from its counter and is reported as unbounded.
  • Past 64 summaries per function, more are dropped without a warning.
  • A first attempt made just before a failover loop isn't counted, so the loop's count is one short (kubevela addon.go:1098 then :1112). That's an under-count.
  • A retryablehttp client built by a helper (ResilientClientWithMaxRetry(0)) isn't followed; the tool uses the largest RetryMax seen anywhere, which over-counts.
  • The printed anchor is the position of the loop's err value, which can be a line or more away from the for statement.
  • Periodic re-runs, and outer loops that run different work each time, can't be told apart from retries by the current test.

Design choices that differ from the first plan (see research/design.md):

  • Failover loops (success leaves the loop, a different target each try) count as retries. This was added to catch loki, which makes loki a tuning target.
  • Counters with offsets are read; exits that don't run on every trip are ignored.
  • Fallbacks where VTA saw no types: promoted-method wrappers, callback parameters traced through call sites, CHA for empty interface calls. All are marked in the output.
  • For the CI gate, an unknown count uses its largest seen default rather than 1. It's still flagged unresolved.

FAQ

What is a retry storm? A retry storm is when retries add load to a service that's already failing, so it fails harder. It gets much worse when several layers each retry: every layer multiplies the load on the one below.

How many retries are too many? There's no universal number. The Google SRE book ("Handling Overload") says requests "should only be retried at the layer immediately above the layer that is rejecting them", with at most three attempts per request and a per-client retry budget of 10%. retrystack tells you the product per call, so you can set a CI limit with -max-attempts and see which calls go over it.

Does it work with Istio or Envoy retries? Yes, with a routes file. It reads Envoy static config and Istio VirtualServices, including Istio's default retry policy when a VirtualService doesn't set one.

Does it run my code or need a cluster? No. It reads source code and config files. The Docker harness in harness/ is only for checking the tool's own predictions against real Envoy.

Why not use a retry budget instead? Use one. Budgets cap retries at runtime. retrystack tells you which calls need one, and how bad it gets without it.

Is the number exact? It's an upper bound over the layers the tool detects. In the Docker harness it was exact on 15 of 17 edges and never below the measured count. On real code, precision depends heavily on the repo (see RESULTS.md).

Contributing

Issues and pull requests are welcome, especially:

  • a retry stack it missed or got wrong (a minimal Go snippet is ideal),
  • another retry library or mesh layer,
  • ways to lower memory on large repos.

Run the tests with go test ./.... The retry-library tests download the real libraries pinned in internal/goscan/testdata/libs.

Repository layout

cmd/retrystack       CLI
internal/goscan      loops, retry regions, bounds, call-graph walk, outbound calls, retry libraries
internal/mesh        Envoy static routes, Istio VirtualServices, routes file
internal/model       attempt arithmetic, layers, findings, flags
harness/             Docker harness: scenarios, predictions, results, scorer
eval/                goclaw (t1a, t1b), loki (t1c), sweeps, labels, comparisons, determinism
research/            design and test plan, written before the build

License

MIT

Directories

Path Synopsis
cmd
retrystack command
Command retrystack lists stacked retry layers per outbound call and multiplies them into a worst-case attempt count.
Command retrystack lists stacked retry layers per outbound call and multiplies them into a worst-case attempt count.
internal
goscan
Package goscan finds retry layers in Go code and follows them through the call graph to the calls that leave the process.
Package goscan finds retry layers in Go code and follows them through the call graph to the calls that leave the process.
mesh
Package mesh turns Envoy static route config and Istio VirtualServices into retry layers, and attaches them to outbound calls by URL.
Package mesh turns Envoy static route config and Istio VirtualServices into retry layers, and attaches them to outbound calls by URL.
model
Package model holds the attempt arithmetic and the report types.
Package model holds the attempt arithmetic and the report types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL