Async Retry with Exponential Backoff
Description
Calls to a model server fail now and then with transient errors. Wrap any async call in a retry helper that backs off exponentially between attempts.
class AsyncRetry:
def __init__(self, max_retries: int, base_delay: float, max_delay: float): ...
async def run(self, fn) -> object: ...fn is a zero-argument function that returns a coroutine, such as lambda: client.generate(prompt).
Rules
run(fn)awaitsfn(). If it returns, return its result immediately, even when the result isNoneor falsy.- If it raises an
Exception, sleep and try again.max_retriescounts retries after the first attempt, sofnruns at mostmax_retries + 1times. - The delay before retry
k(1-based) ismin(max_delay, base_delay * 2 ** (k - 1)). Withbase_delay=0.1and a large cap that is 0.1, 0.2, 0.4, ... - When every attempt fails, re-raise the exception from the last attempt, unchanged.
- Cancellation is not a failure. If the caller cancels
run, whether duringfn()or during a backoff sleep, theCancelledErrormust propagate at once and no further attempts are made. - The constructor raises
ValueErrorwhenmax_retries < 0,base_delay <= 0ormax_delay <= 0. - One
AsyncRetryinstance can serve many concurrentruncalls. Each call has its own attempt count and delays.
Example
calls = 0
async def flaky():
global calls
calls += 1
if calls < 3:
raise RuntimeError("temporary")
return "ok"
retry = AsyncRetry(max_retries=3, base_delay=0.01, max_delay=0.1)
await retry.run(flaky) # "ok" after sleeping 0.01 then 0.02
calls # 3Constraints
0 <= max_retries <= 20- Do not start background tasks. All work happens inside the awaiting
runcall.
Solution
Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.Reveal solution
Approach
Loop over max_retries + 1 attempts. Return as soon as fn() returns. On an Exception, re-raise with a bare raise if this was the last attempt, otherwise sleep min(max_delay, base_delay * 2 ** attempt) and loop.
Catch Exception, not BaseException. asyncio.CancelledError has been a BaseException since Python 3.8, so cancellation flows straight through both the call and the sleep without any special handling. A bare raise keeps the original exception and traceback, so the caller sees exactly what the last attempt raised.
Complexity
O(max_retries) attempts and O(1) state per call. Total wall time is bounded by the sum of the capped delays plus the time spent in fn.
Pitfalls
except BaseExceptionor a bareexcept:. Both swallowCancelledError, so a cancelled caller keeps retrying.- Off-by-one on attempts.
max_retries=2means three calls, not two. - Sleeping after the final failure. That only delays the error.
- Raising the first exception, or wrapping it in a new one. Callers branch on the real error type.
- Storing the attempt counter on
self. Concurrentruncalls then share one counter.
Follow-ups interviewers ask
- Add jitter. With many clients retrying in lockstep, "full jitter" (
random.uniform(0, delay)) spreads the load on the recovering server. - Only retry some errors. Take a predicate or a tuple of retryable types, and fail fast on a 400-style error that will never succeed.
- Put an overall deadline on the whole retry loop, not just per attempt.
asyncio.timeout()aroundrundoes it, or cap the next sleep at the remaining budget. - Retry budgets. If 20% of recent calls are already retries, stop retrying so you don't amplify an outage.
Reference solution
import asyncio
class AsyncRetry:
def __init__(self, max_retries: int, base_delay: float, max_delay: float):
if max_retries < 0 or base_delay <= 0 or max_delay <= 0:
raise ValueError("max_retries must be >= 0 and delays must be > 0")
self.max_retries = max_retries
self.base_delay = base_delay
self.max_delay = max_delay
async def run(self, fn):
for attempt in range(self.max_retries + 1):
try:
return await fn()
except Exception:
# CancelledError is a BaseException, so cancellation never lands here.
if attempt == self.max_retries:
raise
await asyncio.sleep(min(self.max_delay, self.base_delay * 2 ** attempt))Notes
import asyncio
class AsyncRetry:
def __init__(self, max_retries: int, base_delay: float, max_delay: float):
"""
max_retries: retries after the first attempt (>= 0)
base_delay: delay before the first retry, in seconds (> 0)
max_delay: cap on any single delay, in seconds (> 0)
Raise ValueError on invalid arguments.
"""
raise NotImplementedError
async def run(self, fn):
"""
Await fn() with exponential backoff between failed attempts.
Return the first successful result. Re-raise the last exception when retries run out.
"""
raise NotImplementedErrorRun checks the 2 example tests. Submit runs all 14 and marks the problem solved when they pass.