Retry Decorator With Exponential Backoff And Jitter
A typed retry decorator that retries only transient failures, caps exponential backoff and adds jitter to avoid thundering herds.
Code
import random
import time
from functools import wraps
from typing import Callable, Tuple, Type, TypeVar
T = TypeVar("T")
class RetryConfigError(ValueError):
"""Raised when retry parameters are invalid."""
def retry(
max_attempts: int = 3,
base_delay_s: float = 0.1,
cap_s: float = 5.0,
jitter_ratio: float = 0.1,
retryable: Tuple[Type[BaseException], ...] = (Exception,),
sleep: Callable[[float], None] = time.sleep,
) -> Callable[[Callable[..., T]], Callable[..., T]]:
"""Return a decorator that retries transient failures with jittered backoff."""
if max_attempts < 1:
raise RetryConfigError("max_attempts must be >= 1")
if base_delay_s <= 0 or cap_s < base_delay_s:
raise RetryConfigError("base_delay_s must be > 0 and <= cap_s")
if not 0 <= jitter_ratio <= 1:
raise RetryConfigError("jitter_ratio must be within [0, 1]")
def decorator(fn: Callable[..., T]) -> Callable[..., T]:
@wraps(fn)
def wrapper(*args: object, **kwargs: object) -> T:
last_error: BaseException | None = None
for attempt in range(max_attempts):
try:
return fn(*args, **kwargs)
except retryable as exc:
last_error = exc
if attempt == max_attempts - 1:
break
delay = min(cap_s, base_delay_s * (2 ** attempt))
jitter = random.uniform(0, delay * jitter_ratio)
sleep(delay + jitter)
assert last_error is not None
raise last_error
return wrapper
return decoratorA single transient failure surfaces to the caller, while naive retries without jitter synchronize into a thundering herd.
Use case: Python engineers wrapping flaky network or database calls
Inputs / outputs
- Input: max attempts, base delay seconds, cap, jitter ratio, retryable exception types
- Output: the wrapped call result, or the last exception after exhausting attempts
Error conditions
- non-retryable exception raised (propagates immediately)
- all attempts exhausted
- invalid retry parameters
Approach
decorator wraps the call; retryable exceptions are caught; delay = min(cap, base * 2 ** attempt) plus uniform jitter; non-retryable exceptions propagate on the first raise.
Implementation
import random
import time
from functools import wraps
from typing import Callable, Tuple, Type, TypeVar
T = TypeVar("T")
class RetryConfigError(ValueError):
"""Raised when retry parameters are invalid."""
def retry(
max_attempts: int = 3,
base_delay_s: float = 0.1,
cap_s: float = 5.0,
jitter_ratio: float = 0.1,
retryable: Tuple[Type[BaseException], ...] = (Exception,),
sleep: Callable[[float], None] = time.sleep,
) -> Callable[[Callable[..., T]], Callable[..., T]]:
"""Return a decorator that retries transient failures with jittered backoff."""
if max_attempts < 1:
raise RetryConfigError("max_attempts must be >= 1")
if base_delay_s <= 0 or cap_s < base_delay_s:
raise RetryConfigError("base_delay_s must be > 0 and <= cap_s")
if not 0 <= jitter_ratio <= 1:
raise RetryConfigError("jitter_ratio must be within [0, 1]")
def decorator(fn: Callable[..., T]) -> Callable[..., T]:
@wraps(fn)
def wrapper(*args: object, **kwargs: object) -> T:
last_error: BaseException | None = None
for attempt in range(max_attempts):
try:
return fn(*args, **kwargs)
except retryable as exc:
last_error = exc
if attempt == max_attempts - 1:
break
delay = min(cap_s, base_delay_s * (2 ** attempt))
jitter = random.uniform(0, delay * jitter_ratio)
sleep(delay + jitter)
assert last_error is not None
raise last_error
return wrapper
return decorator
Verification tests
import unittest
from example import retry
class RetryTests(unittest.TestCase):
def test_retries_transient_failures_then_succeeds(self):
calls = []
@retry(max_attempts=3, base_delay_s=0.01, cap_s=1.0, sleep=lambda s: None)
def flaky():
calls.append(1)
if len(calls) < 3:
raise TimeoutError("transient")
return "ok"
self.assertEqual(flaky(), "ok")
self.assertEqual(len(calls), 3)
def test_does_not_retry_non_retryable_exceptions(self):
calls = []
@retry(max_attempts=3, base_delay_s=0.01, sleep=lambda s: None, retryable=(TimeoutError,))
def fatal():
calls.append(1)
raise ValueError("permanent")
with self.assertRaises(ValueError):
fatal()
self.assertEqual(len(calls), 1)
def test_caps_the_backoff_delay(self):
delays = []
@retry(max_attempts=4, base_delay_s=1.0, cap_s=2.0, jitter_ratio=0.0,
sleep=delays.append, retryable=(RuntimeError,))
def always_fails():
raise RuntimeError("down")
with self.assertRaises(RuntimeError):
always_fails()
self.assertEqual(delays, [1.0, 2.0, 2.0])
def test_rejects_invalid_parameters(self):
with self.assertRaises(ValueError):
retry(max_attempts=0)
with self.assertRaises(ValueError):
retry(base_delay_s=0)
with self.assertRaises(ValueError):
retry(jitter_ratio=2)
if __name__ == "__main__":
unittest.main()
Dependencies and running
No external dependencies (standard library only).
Runtime: python >= 3.9 Entry point: python example.py
Limitations and error handling
single-threaded synchronous only; no async support; jitter uses random module defaults.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.