Skip to content

< all problems100 · Level 08, Production

Retry With Backoff Behind a Circuit Breaker

hard · implement · Production

The model API returned 429s for ten minutes. Every agent worker retried at once, in a tight loop, and turned a rate limit into an outage. Implement call_with_retry(fn, clock, policy, breaker=None) and the Breaker it can sit behind.

fn() makes the call. It returns a value, or raises RateLimited (with an optional retry_after), Unavailable, or something else. clock.sleep(seconds) waits; clock.now is the time. policy has base, cap and max_attempts. jitter(attempt) is provided and deterministic.

  1. Return fn()'s value on success.
  2. On RateLimited or Unavailable, after attempt n (counting from 0) sleep min(cap, base * 2 ** n) + jitter(n). When the error carries retry_after, sleep that instead if it is longer. Then call again, up to max_attempts calls in total; when the last one fails, raise its error.
  3. Any other exception is raised at once, with no retry.
  4. With a breaker: before each call, if breaker.allow(clock.now) is False, raise CircuitOpen without calling fn. Report every outcome with record_success() or record_failure(clock.now).

Breaker(threshold, cooldown): closed to start; threshold consecutive failures open it at that time; while open, allow is False until cooldown has passed; then it is half open and allows exactly one trial call. A success closes it and clears the count; a failure opens it again from that time.

Backoff protects the provider from you. The breaker protects you from a provider that is down: a call you do not make is the fastest call there is.