Decorator Retry With Backoff

Apply retry with exponential backoff via a decorator for resilient function calls.

PythonResilience

Code

pythonsnippet
15 lines
import functools, time, random
def retry(max_attempts=3, base_delay=1):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise
                    delay = base_delay * 2**attempt + random.random()
                    time.sleep(delay)
        return wrapper
    return decorator

How the snippet works

Decorator Retry With Backoff keeps everything in the functions retry, decorator and wrapper.

Iteration happens inside for attempt in range(max_attempts) — everything outside it runs once. A delay is raised inside an except block, so it is conditional on that failure being handled in the first place.

Watch out for

  • The guard attempt == max_attempts - 1 short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def retry(max_attempts=3, base_delay=1)

The surface worth importing is retry; the helpers around it are private to the snippet.

Statements that matter

def wrapper(*args, **kwargs):
    for attempt in range(max_attempts):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            if attempt == max_attempts - 1:
                raise
            delay = base_delay * 2**attempt + random.random()
            time.sleep(delay)

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `delay` fires only while that failure type is already being handled, not on its own trigger.
Are there dependencies to manage?
No. There are no dependencies to declare or install. Every import resolves inside the standard library — `functools`. The file defines `retry`, `decorator`, `wrapper` at load time.