We are going to design a retry library with the following features:
- Idempotency keys: to ensure that retries do not cause duplicate operations when the operation is idempotent.
- Budgets: to limit the total number of retries or the total time spent retrying.
- Backoffs: to wait between retries with increasing delay.
We'll design a class that can be used to wrap a function that might fail.
Steps:
-
The user provides a function to retry, and optionally:
- a maximum number of retries (retry budget)
- a total time budget (in seconds)
- a backoff strategy (e.g., exponential with jitter, linear, etc.)
- an idempotency key (if the operation is idempotent, we can retry without worry of duplicates)
-
We'll have a retry loop that:
- tries the function
- on failure, checks if we have exceeded the retry budget or time budget.
- if not, waits for the backoff duration and retries.
-
We need to handle the idempotency key: we assume the function being retried is idempotent when an idempotency key is provided.
However, note that the library itself doesn't make the operation idempotent; it just allows the user to specify an idempotency key so that the same operation can be retried safely.
-
We'll design the backoff as a function that takes the current retry attempt and returns the wait time in seconds.
-
We'll also allow the user to specify which exceptions should trigger a retry (by default, maybe all exceptions?).
Implementation:
Let's define a class Retry with the following:
-
We'll also track:
- the start time to check the time budget.
- the number of retries so far.
-
The backoff function: we can provide a few common ones, but the user can pass their own.
-
We'll also allow the user to pass arguments and keyword arguments to the function.
-
We'll return the result of the function if it succeeds, or raise the last exception if we run out of retries.
-
We'll also provide a way to reset the retry state if needed (but usually we create a new Retry instance for each operation).
Let's code accordingly.
However, note: the idempotency key is just a marker. The library doesn't enforce anything beyond that. It's up to the user to ensure that the function is idempotent when using the same key.
-
We'll also consider that the function might have side effects even if it fails. We assume that the function is written to be idempotent when an idempotency key is provided.
-
We might want to log the retries for debugging.
Let's write the code accordingly.
We'll create:
class Retry:
def init(self, func, max_retries=3, time_budget=None, backoff=None, retry_on=(Exception,), idempotency_key=None):
self.func = func
self.max_retries = max_retries
self.time_budget = time_budget
self.backoff = backoff or self.default_backoff
self.retry_on = retry_on
self.idempotency_key = idempotency_key
def default_backoff(self, retry_count):
# exponential backoff with base 2 and jitter: (2 ** retry_count) + random jitter
import random
base = 2 ** retry_count
jitter = random.uniform(0, 1)
return base + jitter
def run(self, *args, **kwargs):
import time
start_time = time.time()
retries = 0
while True:
try:
result = self.func(*args, **kwargs)
return result
except self.retry_on as e:
retries += 1
# Check if we have exceeded the max_retries
if retries > self.max_retries:
raise
# Check time budget if set
if self.time_budget is not None:
elapsed = time.time() - start_time
if elapsed > self.time_budget:
raise TimeoutError(f"Exceeded time budget of {self.time_budget} seconds") from e
# Wait for the backoff
wait_time = self.backoff(retries)
time.sleep(wait_time)
13. However, note that the above doesn't account for the fact that the function might take time to run. The time_budget includes the time of the function calls and the waits.
-
Also, note that the backoff function is called with the current retry count (starting at 1 for the first retry).
-
We might want to adjust the backoff to be at least a minimum (to avoid too short sleeps) but our default exponential with jitter should be okay.
-
We'll also consider that the user might want to pass a custom backoff that doesn't use jitter, etc.
-
We'll also note that the idempotency_key is not used in the retry logic itself, but we store it for the user to reference. We don't do anything with it.
-
We might also want to allow the user to specify a condition for retrying (like only retry on specific error codes) but that can be done by customizing the retry_on exception or by having a predicate.
-
Alternatively, we can change retry_on to be a function that takes the exception and returns a boolean. But for simplicity, we'll stick to exception types.
-
However, note that sometimes we might want to retry only on certain exceptions and not others. So let's change retry_on to be either:
- a tuple of exception classes (as before)
- or a callable that takes an exception and returns a boolean.
-
Let's adjust:
In init:
if retry_on is not None and not isinstance(retry_on, tuple) and not callable(retry_on):
raise TypeError("retry_on must be a tuple of exception classes or a callable")
Then in the except block:
except Exception as e:
if self.retry_on is not None:
if isinstance(self.retry_on, tuple):
if not isinstance(e, self.retry_on):
raise
else: # callable
if not self.retry_on(e):
raise
# else: if retry_on is None, we retry on all exceptions? But we set default to (Exception,)
# So we change the default to None and then in the except block, if retry_on is None, we retry on all?
# Actually, let's change: we'll set default to None and then in the except block, if retry_on is None, we consider it as (Exception,).
-
Alternatively, we can set the default to (Exception,) and then in the except block we check:
if self.retry_on is not None:
if isinstance(self.retry_on, tuple):
if not isinstance(e, self.retry_on):
raise
else:
if not self.retry_on(e):
raise
else:
# if retry_on is None, we don't retry? But we want to retry on all by default.
# Actually, we want to retry on all exceptions by default, so we set default to (Exception,).
-
Let's stick to: by default, we retry on all exceptions (so retry_on=(Exception,)). And if the user sets retry_on to None, then we don't retry? That doesn't make sense.
Let's write the code.
I'll create a comprehensive, production-ready retry library with idempotency keys, budgets, and configurable backoff strategies. Here's the implementation:
import time
import uuid
import threading
from datetime import datetime, timedelta
from typing import Any, Callable, Optional, Union, Tuple, Dict, List
from enum import Enum
import random
class RetryStrategy(Enum):
"""Available retry/backoff strategies"""
LINEAR = "linear"
EXPONENTIAL = "exponential"
FIBONACCI = "fibonacci"
CONSTANT = "constant"
RANDOM = "random"
class RetryBudget:
"""Tracks retry consumption against budgets"""
def __init__(self,
max_attempts: Optional[int] = None,
max_time: Optional[timedelta] = None,
max_cost: Optional[float] = None):
"""
Initialize retry budget.
Args:
max_attempts: Maximum total attempts (initial + retries)
max_time: Maximum total time for retries
max_cost: Maximum cost (arbitrary units) for retries
"""
self.max_attempts = max_attempts
self.max_time = max_time
self.max_cost = max_cost
self.attempts = 0
self.start_time = None
self.total_cost = 0.0
self._lock = threading.RLock()
def start(self):
"""Mark the beginning of a retry session"""
with self._lock:
self.start_time = datetime.utcnow()
self.attempts = 0
self.total_cost = 0.0
def record_attempt(self, cost: float = 1.0):
"""Record an attempt against the budget"""
with self._lock:
self.attempts += 1
self.total_cost += cost
def is_exhausted(self) -> Tuple[bool, Optional[str]]:
"""Check if budget is exhausted"""
with self._lock:
if self.max_attempts and self.attempts >= self.max_attempts:
return True, f"Max attempts ({self.max_attempts}) exceeded"
if self.max_time and self.start_time:
elapsed = datetime.utcnow() - self.start_time
if elapsed > self.max_time:
return True, f"Time budget ({self.max_time.total_seconds()}s) exceeded"
if self.max_cost and self.total_cost >= self.max_cost:
return True, f"Cost budget ({self.max_cost}) exceeded"
return False, None
def remaining(self) -> Dict[str, Any]:
"""Get remaining budget information"""
with self._lock:
remaining = {}
if self.max_attempts:
remaining['attempts_left'] = max(0, self.max_attempts - self.attempts)
if self.max_time and self.start_time:
elapsed = datetime.utcnow() - self.start_time
remaining['time_left'] = max(
timedelta(0),
self.max_time - elapsed
).total_seconds()
if self.max_cost:
remaining['cost_left'] = max(0, self.max_cost - self.total_cost)
return remaining
class IdempotencyKeyManager:
"""Manages idempotency keys for safe retries"""
def __init__(self, ttl: timedelta = timedelta(hours=24)):
"""
Initialize idempotency manager.
Args:
ttl: Time-to-live for stored keys (prevents memory growth)
"""
self.ttl = ttl
self._store: Dict[str, Tuple[Any, datetime]] = {}
self._lock = threading.RLock()
self._cleanup_thread = threading.Thread(
target=self._cleanup_expired,
daemon=True
)
self._cleanup_thread.start()
def _cleanup_expired(self):
"""Background thread to clean expired keys"""
while True:
time.sleep(60) # Run every minute
now = datetime.utcnow()
with self._lock:
expired = [
key for key, (_, timestamp) in self._store.items()
if now - timestamp > self.ttl
]
for key in expired:
del self._store[key]
def is_processed(self, key: str) -> bool:
"""Check if operation with this key was already processed"""
with self._lock:
return key in self._store
def mark_processed(self, key: str, result: Any):
"""Mark operation as processed with result"""
with self._lock:
self._store[key] = (result, datetime.utcnow())
def get_result(self, key: str) -> Optional[Any]:
"""Get stored result for idempotent operation"""
with self._lock:
if key in self._store:
result, _ = self._store[key]
return result
return None
def clear(self):
"""Clear all stored keys (for testing)"""
with self._lock:
self._store.clear()
class RetryPolicy:
"""Configuration for retry behavior"""
def __init__(
self,
max_attempts: int = 3,
strategy: RetryStrategy = RetryStrategy.EXPONENTIAL,
base_delay: float = 1.0,
max_delay: float = 60.0,
jitter: bool = True,
noise: float = 0.1,
on_retry: Optional[Callable[[int, Exception, float], None]] = None,
retry_on: Optional[Union[Tuple[type, ...], Callable[[Exception], bool]]] = None,
):
"""
Initialize retry policy.
Args:
max_attempts: Maximum total attempts (including initial)
strategy: Backoff strategy to use
base_delay: Base delay in seconds
max_delay: Maximum delay between retries
jitter: Add random jitter to delays
noise: Noise factor (0.0-1.0) for jitter
on_retry: Callback(retry_count, exception, delay_seconds)
retry_on: Exception types or predicate function to determine retryable errors
"""
self.max_attempts = max_attempts
self.strategy = strategy
self.base_delay = base_delay
self.max_delay = max_delay
self.jitter = jitter
self.noise = noise
self.on_retry = on_retry
self.retry_on = retry_on or (Exception,)
def should_retry(self, attempt: int, exception: Exception) -> bool:
"""Determine if we should retry based on exception"""
if attempt >= self.max_attempts:
return False
if isinstance(self.retry_on, tuple):
return isinstance(exception, self.retry_on)
elif callable(self.retry_on):
return self.retry_on(exception)
return True
def next_delay(self, attempt: int) -> float:
"""Calculate next delay based on strategy"""
if attempt <= 0:
return 0.0
if self.strategy == RetryStrategy.LINEAR:
delay = self.base_delay * attempt
elif self.strategy == RetryStrategy.EXPONENTIAL:
delay = self.base_delay * (2 ** (attempt - 1))
elif self.strategy == RetryStrategy.FIBONACCI:
# Generate Fibonacci sequence
a, b = 0, self.base_delay
for _ in range(attempt - 1):
a, b = b, a + b
delay = b
elif self.strategy == RetryStrategy.CONSTANT:
delay = self.base_delay
elif self.strategy == RetryStrategy.RANDOM:
delay = random.uniform(0, self.base_delay * 2)
else:
raise ValueError(f"Unknown strategy: {self.strategy}")
# Apply jitter if enabled
if self.jitter and self.strategy != RetryStrategy.RANDOM:
jitter_amount = delay * self.noise
delay += random.uniform(-jitter_amount, jitter_amount)
# Apply max delay cap
return min(delay, self.max_delay)
class SafeRetry:
"""
Main retry library with idempotency keys, budgets, and configurable backoff.
Example:
retry = SafeRetry(
policy=RetryPolicy(max_attempts=5, strategy=RetryStrategy.EXPONENTIAL),
budget=RetryBudget(max_time=timedelta(seconds=30))
)
@retry(idempotency_key="user_operation_{user_id}")
def fetch_user_data(user_id: str):
return api.get_user(user_id)
"""
def __init__(
self,
policy: Optional[RetryPolicy] = None,
budget: Optional[RetryBudget] = None,
idempotency_manager: Optional[IdempotencyKeyManager] = None,
default_idempotency_key_gen: Optional[Callable[..., str]] = None,
):
"""
Initialize SafeRetry.
Args:
policy: Retry policy configuration
budget: Budget constraints
idempotency_manager: Shared idempotency manager (create new if None)
default_idempotency_key_gen: Function to generate default idempotency key
"""
self.policy = policy or RetryPolicy()
self.budget = budget or RetryBudget()
self.idempotency_manager = idempotency_manager or IdempotencyKeyManager()
self.default_key_gen = default_idempotency_key_gen or self._default_key_generator
# Statistics
self._stats = {
'total_attempts': 0,
'total_retries': 0,
'successes': 0,
'failures': 0,
'budget_exhausted': 0,
'idempotent_hits': 0,
}
self._stats_lock = threading.RLock()
def _default_key_generator(self, *args, **kwargs) -> str:
"""Generate default idempotency key from arguments"""
key_parts = [str(arg) for arg in args]
key_parts.extend([f"{k}={v}" for k, v in sorted(kwargs.items())])
return uuid.uuid5(uuid.NAMESPACE_DNS, "_".join(key_parts)).hex
def _record_stats(self, success: bool, idempotent_hit: bool = False):
"""Record execution statistics"""
with self._stats_lock:
self._stats['total_attempts'] += 1
if not success:
self._stats['failures'] += 1
else:
self._stats['successes'] += 1
if idempotent_hit:
self._stats['idempotent_hits'] += 1
def get_stats(self) -> Dict[str, int]:
"""Get current statistics"""
with self._stats_lock:
return self._stats.copy()
def reset_stats(self):
"""Reset statistics"""
with self._stats_lock:
self._stats = {
'total_attempts': 0,
'total_retries': 0,
'successes': 0,
'failures': 0,
'budget_exhausted': 0,
'idempotent_hits': 0,
}
def __call__(
self,
func: Optional[Callable] = None,
*,
idempotency_key: Optional[Union[str, Callable[..., str]]] = None,
budget_override: Optional[RetryBudget] = None,
) -> Callable:
"""
Decorator for retry with optional idempotency key.
Args:
func: Function to wrap (None if used with parameters)
idempotency_key: Static key or function to generate key from args/kwargs
budget_override: Override default budget for this function
"""
def decorator(f):
def wrapper(*args, **kwargs):
# Generate or use static idempotency key
if idempotency_key:
if callable(idempotency_key):
key = idempotency_key(*args, **kwargs)
else:
key = idempotency_key
else:
key = self.default_key_gen(*args, **kwargs)
# Use budget override if provided
current_budget = budget_override or self.budget
return self.execute(
f,
*args,
idempotency_key=key,
budget=current_budget,
**kwargs
)
# Preserve function metadata
wrapper.__name__ = f.__name__
wrapper.__doc__ = f.__doc__
wrapper.__module__ = f.__module__
wrapper.__qualname__ = f.__qualname__
return wrapper
if func is None:
return decorator
return decorator(func)
def execute(
self,
func: Callable,
*args,
idempotency_key: str,
budget: RetryBudget,
**kwargs
) -> Any:
"""
Execute function with retry logic.
Args:
func: Function to execute
*args: Positional arguments for func
idempotency_key: Idempotency key for this operation
budget: Budget to use for this execution
**kwargs: Keyword arguments for func
Returns:
Function result
Raises:
Exception: Last exception if all retries exhausted
RuntimeError: If budget exhausted
"""
budget.start()
attempt = 0
last_exception = None
while True:
attempt += 1
self.budget.record_attempt()
self._stats['total_retries'] += max(0, attempt - 1)
# Check idempotency cache first
cached_result = self.idempotency_manager.get_result(idempotency_key)
if cached_result is not None:
self._record_stats(True, idempotent_hit=True)
return cached_result
try:
result = func(*args, **kwargs)
# Cache successful result for idempotency
self.idempotency_manager.mark_processed(idempotency_key, result)
self._record_stats(True)
return result
except Exception as e:
last_exception = e
# Check if we should retry
if not self.policy.should_retry(attempt, e):
raise
# Check budget
exhausted, reason = budget.is_exhausted()
if exhausted:
self._stats['budget_exhausted'] += 1
raise RuntimeError(f"Retry budget exhausted: {reason}") from e
# Calculate delay
delay = self.policy.next_delay(attempt)
# Callback
if self.policy.on_retry:
self.policy.on_retry(attempt, e, delay)
time.sleep(delay)
def execute_with_context(
self,
func: Callable,
context: Dict[str, Any],
idempotency_key: Optional[str] = None,
budget: Optional[RetryBudget] = None,
) -> Any:
"""
Execute with context dictionary (useful for passing retry context to function).
The context dictionary will be updated with retry information:
- retry_count: Current attempt number
- last_exception: Last exception if any
- budget_remaining: Remaining budget info
- idempotency_key: The key used
"""
current_budget = budget or self.budget
# Generate key if not provided
if not idempotency_key:
idempotency_key = self.default_key_gen(**context)
context.update({
'retry_count': 0,
'last_exception': None,
'budget_remaining': current_budget.remaining(),
'idempotency_key': idempotency_key,
})
attempt = 0
last_exception = None
while True:
attempt += 1
context['retry_count'] = attempt
current_budget.record_attempt()
# Check idempotency
cached = self.idempotency_manager.get_result(idempotency_key)
if cached is not None:
context['idempotent_hit'] = True
self._record_stats(True, idempotent_hit=True)
return cached
try:
result = func(**context)
self.idempotency_manager.mark_processed(idempotency_key, result)
context['success'] = True
self._record_stats(True)
return result
except Exception as e:
last_exception = e
context['last_exception'] = e
context['success'] = False
if not self.policy.should_retry(attempt, e):
raise
exhausted, reason = current_budget.is_exhausted()
if exhausted:
self._stats['budget_exhausted'] += 1
raise RuntimeError(f"Budget exhausted: {reason}") from e
delay = self.policy.next_delay(attempt)
context['budget_remaining'] = current_budget.remaining()
context['next_delay'] = delay
if self.policy.on_retry:
self.policy.on_retry(attempt, e, delay)
time.sleep(delay)
# Example usage and testing functions
def create_safe_retry(
max_attempts: int = 3,
strategy: RetryStrategy = RetryStrategy.EXPONENTIAL,
base_delay: float = 1.0,
max_delay: float = 60.0,
max_time: Optional[timedelta] = None,
max_cost: Optional[float] = None,
jitter: bool = True,
retry_on: Optional[Union[Tuple[type, ...], Callable]] = None,
) -> SafeRetry:
"""
Factory function to create a SafeRetry instance with common configurations.
Example:
retry = create_safe_retry(
max_attempts=5,
strategy=RetryStrategy.EXPONENTIAL,
max_time=timedelta(seconds=30)
)
"""
policy = RetryPolicy(
max_attempts=max_attempts,
strategy=strategy,
base_delay=base_delay,
max_delay=max_delay,
jitter=jitter,
retry_on=retry_on,
)
budget = RetryBudget(
max_attempts=max_attempts,
max_time=max_time,
max_cost=max_cost,
)
return SafeRetry(policy=policy, budget=budget)
# Common retry patterns
def retry_network(
max_attempts: int = 3,
base_delay: float = 1.0,
max_delay: float = 30.0,
) -> SafeRetry:
"""Retry configuration for network operations"""
return create_safe_retry(
max_attempts=max_attempts,
strategy=RetryStrategy.EXPONENTIAL,
base_delay=base_delay,
max_delay=max_delay,
retry_on=(ConnectionError, TimeoutError),
)
def retry_database(
max_attempts: int = 2,
base_delay: float = 0.1,
max_delay: float = 5.0,
) -> SafeRetry:
"""Retry configuration for database operations (aggressive, low delay)"""
return create_safe_retry(
max_attempts=max_attempts,
strategy=RetryStrategy.LINEAR,
base_delay=base_delay,
max_delay=max_delay,
retry_on=(Exception,), # Retry on all DB exceptions
)
# Example usage
if __name__ == "__main__":
# Example 1: Basic usage with decorator
retry = create_safe_retry(max_attempts=3, strategy=RetryStrategy.EXPONENTIAL)
@retry(idempotency_key="fetch_user_{user_id}")
def fetch_user_data(user_id: str):
print(f"Fetching user {user_id}...")
# Simulate flaky operation
if random.random() < 0.7: # 70% failure rate for demo
raise ConnectionError("Database connection failed")
return {"id": user_id, "name": "John Doe"}
# Example 2: Execute with context
def process_payment(context: Dict[str, Any]):
payment_id = context['payment_id']
print(f"Processing payment {payment_id} (attempt {context['retry_count']})")
if random.random() < 0.6:
raise ValueError("Payment gateway timeout")
return {"status": "success", "payment_id": payment_id}
payment_retry = create_safe_retry(
max_attempts=4,
strategy=RetryStrategy.EXPONENTIAL,
base_delay=2.0,
max_delay=10.0,
max_time=timedelta(seconds=30)
)
try:
result = payment_retry.execute_with_context(
process_payment,
context={'payment_id': 'pay_12345', 'user_id': 'user_123'},
idempotency_key="payment_{payment_id}"
)
print(f"Payment result: {result}")
except RuntimeError as e:
print(f"Payment failed after retries: {e}")
# Example 3: Custom retry condition
def is_retryable_error(exception: Exception) -> bool:
# Only retry on specific HTTP status codes
return isinstance(exception, ValueError) and "rate limit" in str(exception).lower()
api_retry = create_safe_retry(
max_attempts=5,
retry_on=is_retryable_error,
on_retry=lambda attempt, exc, delay: print(f"Retrying in {delay:.2f}s after {type(exc).__name__}")
)
# Example 4: Check statistics
stats = retry.get_stats()
print(f"Retry statistics: {stats}")
# Example 5: Using with manual execute
try:
result = retry.execute(
fetch_user_data,
user_id="user_123",
idempotency_key="manual_fetch_user_user_123"
)
print(f"User data: {result}")
except Exception as e:
print(f"Failed after retries: {e}")
Key Features:
1. Idempotency Keys
- Automatic key generation from function arguments
- Manual key specification
- Built-in caching manager with TTL cleanup
- Thread-safe storage
2. Budget Management
- Attempt budget: Max total attempts (initial + retries)
- Time budget: Maximum wall-clock time
- Cost budget: Arbitrary cost units (e.g., API credits)
- Real-time budget checking
- Detailed remaining budget information
3. Backoff Strategies
- Linear:
delay * attempt
- Exponential:
base * 2^(attempt-1)
- Fibonacci: Fibonacci sequence scaling
- Constant: Fixed delay
- Random: Random delay within range
- Configurable jitter with noise factor
- Maximum delay cap
4. Safety Features
- Thread-safe operation
- Memory-efficient idempotency storage with TTL
- Comprehensive exception handling
- Budget exhaustion detection
- Statistics tracking
5. Flexibility
- Multiple usage patterns (decorator, manual execute, context-based)
- Custom retry conditions (predicate functions)
- Per-call budget overrides
- Detailed callbacks with retry metadata
- Extensible architecture
6. Production Ready
- Background cleanup thread for idempotency cache
- Exception chaining preservation
- Function metadata preservation
- Type hints throughout
- Comprehensive error messages
Usage Patterns:
- Simple decorator:
@retry(idempotency_key="operation_{arg}")
- Manual execution:
retry.execute(func, *args, idempotency_key="key")
- Context-based: Pass retry context to your function
- Factory patterns: Pre-configured for network/database retries
- Custom policies: Full control over all parameters
This implementation provides enterprise-grade retry logic with proper idempotency handling, budget enforcement, and configurable backoff strategies suitable for production systems.