Retry Decorator with Exponential Backoff

medium
Unit 2 · Decorators0/3 to milestone

LLM and web APIs fail transiently with timeouts, rate limits and 503s. The standard fix is to retry with exponential backoff: wait 1s, then 2s, then 4s…

Implement a decorator factory retry(times=3, exceptions=(Exception,), base_delay=1.0, sleep=time.sleep):

  • Call the wrapped function up to times times in total.
  • If it raises one of exceptions, call sleep(base_delay * 2 ** attempt) (attempt = 0, 1, 2…) and try again.
  • If the last attempt fails, re-raise that exception, without sleeping after it.
  • Exceptions not in exceptions propagate immediately, with no retry.
  • Return the function's result as soon as a call succeeds.
  • Preserve the wrapped function's name and docstring (functools.wraps).

sleep is a parameter so tests can pass a fake one instead of actually waiting.

Example

@retry(times=3, exceptions=(TimeoutError,), base_delay=0.5)
def call_api(): ...
# on two timeouts then success: sleeps 0.5, then 1.0, then returns
#decorators#apis#reliability3 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Retry Decorator with Exponential Backoff · TechGradify