Retry With Backoff Behind a Circuit Breaker
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.
- Return
fn()'s value on success. - On
RateLimitedorUnavailable, after attemptn(counting from 0) sleepmin(cap, base * 2 ** n) + jitter(n). When the error carriesretry_after, sleep that instead if it is longer. Then call again, up tomax_attemptscalls in total; when the last one fails, raise its error. - Any other exception is raised at once, with no retry.
- With a breaker: before each call, if
breaker.allow(clock.now)is False, raiseCircuitOpenwithout callingfn. Report every outcome withrecord_success()orrecord_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.