Decorator Retry With Backoff

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

PythonResilience

Code

snippet
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