Exponential backoff is a retry strategy that waits longer after each failed attempt, typically base * 2 ** attempt seconds capped at a maximum, so a struggling service gets time to recover instead of a flood of immediate retries. Adding jitter, a random part of each delay, stops many clients that failed together from retrying together. A correct retry helper also needs three limits that are easy to forget: it retries only errors that are transient, it stops after a fixed number of attempts or a deadline, and it never treats cancellation as a failure. In Python 3.12 all of this fits in about 25 lines of standard library code with asyncio.sleep, random.uniform and asyncio.timeout.
This guide builds that helper step by step, shows why jitter matters with a simulation, and covers the follow-ups an interviewer asks once the loop works. Every snippet is complete and runs on Python 3.12 or newer.
The delay schedule
The delay before retry k (counting from 0) is min(cap, base * 2 ** k). With base=0.1 and cap=2.0, that is 0.1, 0.2, 0.4, 0.8, 1.6, 2.0, 2.0 and so on. The cap matters because the uncapped sequence passes a minute after ten retries.
def backoff_delays(base: float, cap: float, retries: int) -> list[float]:
return [min(cap, base * 2**k) for k in range(retries)]
print(backoff_delays(base=0.1, cap=2.0, retries=7))
# [0.1, 0.2, 0.4, 0.8, 1.6, 2.0, 2.0]Count attempts and retries carefully, because interview specs word this differently. "max_retries=3" usually means up to four calls in total: the first attempt plus three retries. "attempts=3" means three calls. Restate the spec before you write the loop.
A synchronous retry first
The shape is the same with or without asyncio. Try, catch only the retryable errors, sleep, try again, and re-raise the last error when attempts run out.
import time
def retry(fn, *, attempts: int, base: float, cap: float, retry_on=(ConnectionError, TimeoutError)):
for attempt in range(attempts):
try:
return fn()
except retry_on:
if attempt == attempts - 1:
raise
time.sleep(min(cap, base * 2**attempt))
calls = 0
def flaky() -> str:
global calls
calls += 1
if calls < 3:
raise ConnectionError("reset by peer")
return "ok"
print(retry(flaky, attempts=5, base=0.01, cap=0.1), calls) # ok 3Three details carry the marks. The bare raise re-raises the original exception with its traceback, rather than wrapping it in a new one. There is no sleep after the last failure, which would only delay the error. And retry_on is a tuple of exception types, so a ValueError from a bug in fn fails immediately instead of being retried five times.
The asyncio version with jitter
In async code the sleep must be await asyncio.sleep(...). time.sleep would freeze every other task on the event loop. Full jitter picks each delay uniformly between 0 and the exponential value, which spreads retries out the most.
import asyncio
import random
async def retry_async(
fn,
*,
attempts: int = 5,
base: float = 0.1,
cap: float = 5.0,
retry_on: tuple[type[Exception], ...] = (ConnectionError, TimeoutError),
):
for attempt in range(attempts):
try:
return await fn()
except retry_on:
if attempt == attempts - 1:
raise
await asyncio.sleep(random.uniform(0, min(cap, base * 2**attempt)))
calls = 0
async def flaky_call() -> dict:
global calls
calls += 1
await asyncio.sleep(0.001)
if calls < 4:
raise ConnectionError("upstream reset")
return {"status": "ok", "attempts": calls}
print(asyncio.run(retry_async(flaky_call, base=0.01)))
# {'status': 'ok', 'attempts': 4}fn is a function that returns a new coroutine, such as lambda: client.get(url), not a coroutine object. A coroutine can be awaited only once, so passing client.get(url) directly fails on the second attempt with RuntimeError: cannot reuse already awaited coroutine. That mistake shows up in a lot of first drafts.
Cancellation is not a failure
asyncio.CancelledError subclasses BaseException, not Exception, since Python 3.8. So except Exception and except (ConnectionError, TimeoutError) both let it pass, and a cancelled caller stops at once, whether it was inside fn() or inside the backoff sleep. The bug is a bare except: or except BaseException:, which catches the cancellation and retries it.
import asyncio
async def broken_retry(fn, attempts: int):
for attempt in range(attempts):
try:
return await fn()
except BaseException:
await asyncio.sleep(0.01)
async def fixed_retry(fn, attempts: int):
for attempt in range(attempts):
try:
return await fn()
except Exception:
if attempt == attempts - 1:
raise
await asyncio.sleep(0.01)
async def slow() -> None:
await asyncio.sleep(10)
async def main() -> None:
for retry in (broken_retry, fixed_retry):
task = asyncio.create_task(retry(slow, attempts=3))
await asyncio.sleep(0.01)
task.cancel()
await asyncio.sleep(0.05)
print(retry.__name__, "done:", task.done())
task.cancel()
await asyncio.gather(task, return_exceptions=True)
asyncio.run(main())
# broken_retry done: False
# fixed_retry done: TrueThe broken version swallowed the cancel and started another ten-second attempt. Anything that relies on cancellation, including asyncio.timeout, TaskGroup and server shutdown, now hangs on this call.
One deadline for the whole call
A per-attempt timeout does not bound the call. Five attempts with wait_for(fn(), 2) each, plus backoff, can take well over ten seconds. Callers think in deadlines, so wrap the whole loop in one asyncio.timeout, and optionally keep a shorter per-attempt timeout inside it so one hung attempt doesn't eat the whole budget.
import asyncio
import time
async def call_with_deadline(fn, *, deadline: float, per_attempt: float, attempts: int = 10):
async with asyncio.timeout(deadline):
for attempt in range(attempts):
try:
async with asyncio.timeout(per_attempt):
return await fn()
except (ConnectionError, TimeoutError):
if attempt == attempts - 1:
raise
await asyncio.sleep(min(0.2, 0.02 * 2**attempt))
async def hangs() -> str:
await asyncio.sleep(10)
return "never"
async def main() -> None:
start = time.monotonic()
try:
await call_with_deadline(hangs, deadline=0.3, per_attempt=0.1)
except TimeoutError:
print(f"gave up after {time.monotonic() - start:.1f}s") # about 0.3s
asyncio.run(main())The inner timeout raises TimeoutError, which the loop treats as retryable. When the outer deadline expires, the outer asyncio.timeout turns the cancellation into its own TimeoutError at the outer async with, so the loop does not retry it. Nesting the two is safe because each asyncio.timeout only converts the cancellation it caused.
Why jitter matters
When a dependency blips, every client fails at the same instant. Without jitter they all retry at exactly t + 0.1, then t + 0.3, then t + 0.7, and each retry wave hits the recovering service as hard as the original spike. The simulation below counts how many of 1,000 clients retry in the busiest 100 ms bucket, with a 1 second base delay.
import random
from collections import Counter
random.seed(7)
BASE, CAP, CLIENTS, RETRIES = 1.0, 20.0, 1000, 4
def peak_load(delay_fn) -> int:
buckets: Counter[int] = Counter()
for _ in range(CLIENTS):
t = 0.0
for k in range(RETRIES):
t += delay_fn(k)
buckets[int(t / 0.1)] += 1
return max(buckets.values())
strategies = {
"no jitter": lambda k: min(CAP, BASE * 2**k),
"equal jitter": lambda k: (d := min(CAP, BASE * 2**k)) / 2 + random.uniform(0, d / 2),
"full jitter": lambda k: random.uniform(0, min(CAP, BASE * 2**k)),
}
for name, fn in strategies.items():
print(f"{name:12} peak={peak_load(fn)}")
# no jitter peak=1000
# equal jitter peak=216
# full jitter peak=166Without jitter all 1,000 clients land in the same 100 ms bucket on every retry. Equal jitter cuts the peak to about a fifth and full jitter to about a sixth. Full jitter spreads load the most but sometimes retries almost immediately. Equal jitter keeps at least half of the exponential delay, which guarantees some backoff. Either is a good answer in an interview. No jitter is not.
A third variant, decorrelated jitter, picks each delay from uniform(base, previous_delay * 3) capped at cap. It needs the previous delay as state, so it fits a loop more naturally than a formula.
Testing retries without sleeping
Real sleeps make tests slow and flaky. Pass the sleep function in, record the delays, and assert on the schedule.
import asyncio
async def retry_with(fn, *, attempts: int, base: float, cap: float, sleep=asyncio.sleep):
for attempt in range(attempts):
try:
return await fn()
except ConnectionError:
if attempt == attempts - 1:
raise
await sleep(min(cap, base * 2**attempt))
async def test_schedule_and_last_error() -> None:
delays: list[float] = []
async def fake_sleep(seconds: float) -> None:
delays.append(seconds)
errors = iter([ConnectionError("a"), ConnectionError("b"), ConnectionError("c")])
async def always_fails() -> None:
raise next(errors)
try:
await retry_with(always_fails, attempts=3, base=1, cap=1.5, sleep=fake_sleep)
except ConnectionError as exc:
assert str(exc) == "c", "re-raises the last error"
assert delays == [1, 1.5], f"two sleeps, capped: {delays}"
print("ok", delays) # ok [1, 1.5]
asyncio.run(test_schedule_and_last_error())The same idea works for jitter. Inject a random.Random(seed) instance, or a function that returns the jitter fraction, and the test becomes deterministic.
Follow-ups interviewers ask
Which errors should be retried?
Retry errors that might succeed on a second try: connection resets, timeouts, HTTP 429, 502, 503 and 504. Don't retry 400, 401, 403, 404 or 422, or a bug in your own code. When the server sends Retry-After, wait at least that long instead of your computed delay. A clean design takes a predicate, should_retry(exc) -> bool, instead of a fixed tuple, because HTTP libraries raise one exception class for every status code.
Is the operation safe to retry?
A timed-out request may have succeeded on the server. Retrying a GET is harmless. Retrying "charge this card" can charge it twice. The standard answer is an idempotency key: the client generates a unique id per logical operation and sends it on every attempt, and the server stores the result per key and returns it on repeats.
Retry storms
Retries multiply across layers. If the browser, the API gateway and the backend each try three times, one user click can become 27 calls to the database during an outage. Retry at one layer, usually the one closest to the failing dependency, and give the service a retry budget, for example retries may add at most 10% to normal traffic. A circuit breaker is the next step. It stops calling a dependency that is clearly down, so the retries stop too.
Don't hold resources while you wait
If the call runs under a semaphore or a connection pool slot, release it before the backoff sleep. A retry loop that sleeps while holding one of ten permits makes the whole service slower during exactly the incident you are retrying through.
Should you use a library?
In production, tenacity and backoff handle the decorator, logging and stop conditions well. In an interview you write the loop yourself and then mention the library. Knowing what the library does, retry predicate, stop condition, wait strategy, before-sleep hook, shows you understand the parts.
Common mistakes
- Catching
BaseExceptionor using a bareexcept:. It swallowsCancelledErrorandKeyboardInterrupt. - Retrying every exception. A
TypeErrorwill fail the same way five times. - Sleeping after the final attempt. The caller waits for nothing.
- Raising a new exception and losing the original. Use a bare
raise, orraise RetryError(...) from excif the spec wants a wrapper. - Passing a coroutine object instead of a factory. A coroutine can only be awaited once.
time.sleepin async code. It blocks the event loop for every task.- No jitter. Synchronised clients turn one failure into repeated spikes.
- A timeout per attempt but no overall deadline. The total time is attempts times timeout plus the backoff.
Practise it
The Async Retry with Exponential Backoff problem asks for a reusable retry class with capped exponential delays, last-error re-raise and correct cancellation, and its hidden tests check the exact schedule and that a cancel during the backoff sleep stops at once. Budget 20 minutes.
- 20Dynamic Request Batcherhard
Group concurrent inference requests into batches that flush when full or when the oldest request has waited long enough, with cancellation and drain.
- 21Async TTL Cache with Request Coalescingmedium
Build an asyncio cache whose entries expire after a TTL, where concurrent misses for the same key share one fetch that survives caller cancellation.
- 22Async Retry with Exponential Backoffmedium
Retry a failing coroutine with capped exponential backoff, re-raise the last error, and never swallow cancellation.
- 25Async Request Deduplicatorhard
Collapse concurrent fetches for the same key into one shared call, with per-caller timeouts that never cancel the shared work.
The retries and cancellation topic pages collect related problems. Retries pair with the circuit breaker guide, and the asyncio interview guide covers timeouts and cancellation in more depth.
Frequently asked questions
What is exponential backoff?
A retry strategy that waits longer after each failure, usually base * 2 ** attempt seconds capped at a maximum. With base 0.1 and a cap of 2 the delays are 0.1, 0.2, 0.4, 0.8, 1.6, 2.0 and so on, which gives a struggling service time to recover.
Why add jitter to exponential backoff?
Clients that failed at the same moment would otherwise retry at the same moments too, so every retry wave hits the recovering service as hard as the original spike. Jitter randomises each delay, for example uniform(0, delay), which spreads the retries out.
How do I retry an async function in Python?
Loop over the attempts, await a fresh coroutine from a factory such as lambda: client.get(url) on each pass, catch only the retryable exception types, await asyncio.sleep with the backoff delay, and re-raise the last error after the final attempt. Never use time.sleep inside a coroutine.
Should a retry loop catch asyncio.CancelledError?
No. CancelledError subclasses BaseException, so except Exception lets it through, which is what you want. A bare except or except BaseException catches the cancellation and retries it, which breaks task.cancel(), asyncio.timeout and TaskGroup.
Which errors should be retried?
Transient ones: connection resets, timeouts and HTTP 429, 502, 503 and 504. Do not retry client errors such as 400, 401, 403 or 404, or exceptions caused by bugs. Honour a Retry-After header when the server sends one.
How many times should you retry?
Usually three to five attempts, bounded by an overall deadline the caller cares about. Retry at one layer of the stack only, because retries at every layer multiply into a storm during an outage.