Python

Retry Decorator with Exponential Backoff

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generic retry decorator: attempts × base delay, exponential ramp, random jitter. Filter retryable exceptions via the `on` tuple so logical errors aren't retried.
Python
Raw
import functools
import random
import time

def retry(attempts: int = 3, base: float = 0.2, on: tuple[type[BaseException], ...] = (Exception,)):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for i in range(1, attempts + 1):
                try:
                    return fn(*args, **kwargs)
                except on as e:
                    if i == attempts:
                        raise
                    delay = base * (2 ** (i - 1))
                    time.sleep(delay + random.random() * delay)
        return wrapper
    return decorator

@retry(attempts=5, base=0.5, on=(ConnectionError, TimeoutError))
def fetch():
    import requests
    return requests.get("https://flaky.api/data", timeout=5).json()
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.