The user wants a "safe retry library" with specific features:
Idempotency Keys: To ensure that an operation can be retried without causing duplicate side effects.
Budgets: To limit the number of retries, total time spent, or perhaps cost (though usually time/count in software contexts).
Backoffs: To wait between retries (e.g., exponential backoff) to avoid overwhelming the target.
This sounds like a Python library design request. I need to structure the response as a guide to building or using such a library, or perhaps providing a code implementation. Given the phrasing "Build a...", a code implementation with an explanation is best.
Core Components:
Idempotency:
How to implement? Usually, it requires a persistent store (Redis, SQL DB) to log the key and the status/result.
Since this is a "library" example, I should abstract the storage. I'll define an IdempotencyStore interface (Protocol/ABC) and provide an in-memory implementation for demonstration.
The flow: Generate key -> Check store -> If exists, return cached result -> If not, execute -> Save result.
Retry Logic (The "Retry" part):
Need a decorator or a context manager. A decorator is standard for this.
Needs to catch specific exceptions.
Needs to determine if an error is retriable.
Backoff Strategies:
Fixed: Sleep X.
Linear: Sleep attempt×X.
Exponential: Sleep base×2attempt±jitter.
Jitter is crucial to avoid thundering herds.
Budgets:
Max retries (count budget).
Timeout (time budget).
Drafting the Architecture:
BackoffStrategy: Class/Function to calculate sleep time.
Budget: Class to track limits.
IdempotencyStore: Interface for storing state.
RetryPolicy: The main class combining these.
Refining the Idempotency Aspect:
Implementing true idempotency inside a generic retry decorator is tricky because the decorator doesn't know how to save the state of the specific function call (arguments, return value serialization) or how to generate the key from arguments.
Solution: The decorator should take a key_extractor function (to derive the key from args/kwargs) and use the injected store.
Refining the Implementation Steps:
Define Exceptions: Custom exceptions for budget exceeded or non-retriable errors.
Backoff: Implement ExponentialBackoff with jitter.
Budget: A simple class checking time and count.
Storage: A mock Redis/Dict store.
The Main Decorator/Wrapper: This is the meat of the answer.
Code Structure (Python):
python
import time
import random
import functools
from abc import ABC, abstractmethod
# 1. Backoff Strategies
class Backoff(ABC):
@abstractmethod
def sleep(self, attempt): pass
class ExponentialBackoff(Backoff):
# implementation with jitter
# 2. Budgets
class Budget:
def __init__(self, max_retries, timeout):
# ...
def check(self):
# raise exception if exceeded
# 3. Idempotency Store
class IdempotencyStore(ABC):
@abstractmethod
def get(self, key): pass
@abstractmethod
def set(self, key, value): pass
# 4. The Logic
def safe_retry(store, backoff, budget, key_func):
def decorator(func):
def wrapper(*args, **kwargs):
# Extract key
key = key_func(*args, **kwargs)
# Check idempotency
cached = store.get(key)
if cached: return cached
# Retry loop
while True:
try:
result = func(*args, **kwargs)
store.set(key, result)
return result
except Exception as e:
if not is_retriable(e): raise
budget.consume()
backoff.sleep()
Edge Cases to Consider:
Partial Failure: What if the function runs but fails to save to the idempotency store? (The "Out of Band" problem). For a simple library, we assume atomic execution or best-effort. A robust implementation usually requires the function to yield a result that is then saved. But if the network dies after execution but before saving, the next retry runs the logic again. This is the hard part of idempotency.
Mitigation: The idempotency check should ideally happen inside the function logic if strong guarantees are needed, OR the library manages the transaction.
For this prompt, I will stick to a clean library pattern: "Run -> If success, Save -> Return". If save fails, we re-raise. This is standard for generic Python decorators.
Key Generation: Users often forget to provide a unique key. I should provide a default or force them to provide one. A key_builder argument is best.
Let's polish the features:
Decorators are Pythonic.
Context managers are also nice for block-level retries. I'll focus on the Decorator as it's the most common "library" approach.
Plan:
Define the Backoff strategy (Exponential + Jitter).
Define the Budget mechanism (Time & Count).
Define the IdempotencyStore (Abstract + In-Memory implementation).
Create the retry decorator that integrates all three.
Provide a usage example.
Self-Correction during thought process:
User asked for "Idempotency Keys". This implies the library must handle the state of previous runs.
Crucial detail: The idempotency store needs to be thread-safe (or handle concurrency) if it's a real library, but for a code example, a standard dict is fine (maybe with a lock).
Let's write the code. I'll use tenacity as a reference for "good design" but implement from scratch to show how it works, as requested to "Build" it.
Final Code Components:
RetryBudget: Tracks limits.
BackoffStrategy: Calculates wait times.
IdempotencyStore: Interface + InMemoryStore.
safe_retry: The decorator factory.
Let's verify the "Safety" aspect.
Safety = Don't retry non-retriable errors.
Safety = Don't hang forever (Budget).
Safety = Don't double-charge the credit card (Idempotency).
Safety = Don't DDOS the server (Backoff/Jitter).
I will produce a comprehensive Python module code block and explain the components.
Structure of the response:
High-Level Design: Brief explanation of the three pillars (Idempotency, Budget, Backoff).
The Implementation: Complete, copy-pasteable Python code.
Usage Example: Demonstrating how to use the library.
Production Considerations: Mentioning Redis, serializing args, and distributed locks.
Refining the Idempotency Key generation:
The user might want to pass specific args as the key. I'll use a key_generator callable in the decorator arguments.
Refining the "Safe" aspect:
If the Idempotency Store fails, what happens? Usually, you want to fail safe (don't execute if you can't guarantee idempotency? Or execute without caching?). I'll assume "Execute and try to save" is the standard approach for a library, but log the storage failure.
Let's stick to Python's functools, time, and random.
(Self-Correction on Idempotency logic):
If store.get(key) returns a result, we return it immediately.
If not, we run the function.
If the function succeeds, we store.set(key, result).
Wait, what if the function is running in another thread right now?
Advanced: Need a lock/semaphore in the store (set_if_not_exists).
Simple version: Just check-get. For a basic library tutorial, the race condition is acceptable to gloss over, but I will add a note about atomicity (Redis SETNX) in the "Production Considerations".
Let's generate the response.
Building a production-grade retry library requires coordinating three distinct concepts:
Idempotency: Ensuring that retrying a failed operation (like a credit card charge) doesn't create duplicate side effects.
Backoff: Waiting intelligently between retries (e.g., Exponential Backoff with Jitter) to avoid hammering a recovering service.
Budgets: Stopping retries after a certain time or attempt count to prevent "zombie" processes.
Below is a complete, type-hinted Python implementation.
The Architecture
We will define:
IdempotencyStore: An abstract storage for request keys (implementations could use Redis, SQL, or Memory).
BackoffStrategy: Logic for wait times.
RetryBudget: Logic for limits.
safe_retry: The decorator that ties it all together.
The Implementation
python
Key Design Features Explained
1. The Key Generator (key_generator)
You cannot rely on Python's args alone to detect duplicates because objects change. In this library, we force the user to provide a function that extracts a unique key (e.g., req-user_123-charge) from the function arguments.
If the key exists in the Store: The library returns the cached result immediately. The function logic is never called.
If the key is missing: The library acquires a lock (marking it "PROCESSING"), runs the function, caches the result, and releases the lock.
2. Exponential Backoff with Jitter
The ExponentialBackoff class implements the "Decorrelated Jitter" strategy.
Exponential: It doubles the wait time (2n) with every failure.
Jitter: It adds randomness. This prevents the "Thundering Herd" problem—if 100 clients fail at the same time, without jitter, they would all retry exactly 1 second later, crashing the server again. Jitter spreads them out.
3. Budget Constraints
The RetryBudget acts as the circuit breaker.
Max Attempts: Hard limit on retries (e.g., don't retry more than 5 times).
Timeout: Global time limit (e.g., "give up if the whole process takes longer than 10 seconds"). This prevents a retry loop from running indefinitely if the backoff times get too large.
4. Safe Exception Handling
The retry_on parameter ensures we only retry transient errors (like ConnectionError or 503 Service Unavailable). If the function fails due to a ValueError (bad input) or 401 Unauthorized, the library raises immediately without wasting resources on retries.
import time
import random
import functools
import logging
from abc import ABC, abstractmethod
from typing import Callable, Any, Optional, Type, Tuple, List
# Configure basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("SafeRetry")
# --- 1. Idempotency Store ---
# Stores the state of a request key to ensure we don't double-execute.
class IdempotencyStore(ABC):
@abstractmethod
def lock_and_execute(self, key: str, action: Callable[[], Any], ttl_seconds: int) -> Any:
"""
Checks if key exists.
- If yes: return cached result or raise if in-progress.
- If no: lock, execute action, cache result, return result.
"""
pass
class InMemoryIdempotencyStore(IdempotencyStore):
"""
A simple in-memory implementation.
Warning: Not thread-safe without locks, not persistent across restarts.
Use Redis or a Database for production.
"""
def __init__(self):
self._store = {} # key -> (status, result, timestamp)
def lock_and_execute(self, key: str, action: Callable[[], Any], ttl_seconds: int) -> Any:
now = time.time()
# Check if key exists and is not expired
if key in self._store:
status, result, timestamp = self._store[key]
if now - timestamp < ttl_seconds:
if status == 'COMPLETED':
logger.info(f"Idempotency hit: Returning cached result for {key}")
return result
elif status == 'PROCESSING':
raise Exception(f"Concurrent request detected for key {key}")
# Lock (simulate)
logger.info(f"Locking idempotency key: {key}")
self._store[key] = ('PROCESSING', None, now)
try:
result = action()
self._store[key] = ('COMPLETED', result, now)
return result
except Exception as e:
# If execution fails, remove lock so it can be retried later
del self._store[key]
raise e
# --- 2. Backoff Strategy ---
class BackoffStrategy(ABC):
@abstractmethod
def get_wait_time(self, attempt: int) -> float:
pass
class ExponentialBackoff(BackoffStrategy):
"""
Wait time = base * (2 ^ attempt) + jitter
"""
def __init__(self, base: float = 1.0, max_wait: float = 60.0, jitter: bool = True):
self.base = base
self.max_wait = max_wait
self.jitter = jitter
def get_wait_time(self, attempt: int) -> float:
wait = self.base * (2 ** (attempt - 1))
wait = min(wait, self.max_wait)
if self.jitter:
# Full jitter strategy (random between 0 and wait)
wait = random.uniform(0, wait)
return wait
# --- 3. Retry Budget ---
class RetryBudget:
def __init__(self, max_attempts: int = 3, timeout_seconds: Optional[float] = None):
self.max_attempts = max_attempts
self.timeout_seconds = timeout_seconds
def is_exceeded(self, attempt: int, start_time: float) -> bool:
if attempt > self.max_attempts:
return True
if self.timeout_seconds:
if (time.time() - start_time) > self.timeout_seconds:
return True
return False
# --- 4. The Library Core ---
class SafeRetryError(Exception):
"""Raised when all retries are exhausted."""
def __init__(self, message, last_exception):
super().__init__(message)
self.last_exception = last_exception
def safe_retry(
store: IdempotencyStore,
key_generator: Callable[[Tuple, dict], str],
budget: RetryBudget = RetryBudget(),
backoff: BackoffStrategy = ExponentialBackoff(),
retry_on: List[Type[Exception]] = [Exception]
):
"""
Decorator to wrap functions with safe retry logic.
:param store: Where to save idempotency results.
:param key_generator: A function taking (args, kwargs) and returning a unique string key.
:param budget: Constraints on attempts/time.
:param backoff: Strategy for waiting.
:param retry_on: List of Exception classes to retry on.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 1. Generate Idempotency Key
# In a real app, you might pass the key explicitly in kwargs
idempotency_key = key_generator(args, kwargs)
# Define the execution logic
def execute_logic():
attempt = 1
start_time = time.time()
last_exception = None
while not budget.is_exceeded(attempt, start_time):
try:
logger.info(f"Attempt {attempt} for {func.__name__}")
return func(*args, **kwargs)
except Exception as e:
# Check if this exception is retriable
if not any(isinstance(e, exc_type) for exc_type in retry_on):
logger.warning(f"Non-retriable exception encountered: {e}")
raise e
logger.warning(f"Attempt {attempt} failed: {e}")
last_exception = e
attempt += 1
# Calculate backoff
if not budget.is_exceeded(attempt, start_time):
sleep_time = backoff.get_wait_time(attempt - 1)
logger.info(f"Sleeping for {sleep_time:.2f}s...")
time.sleep(sleep_time)
# If loop finishes, budget is exceeded
raise SafeRetryError(
f"Retry budget exceeded for {func.__name__}",
last_exception
)
# 2. Use Store to ensure safety
return store.lock_and_execute(
idempotency_key,
execute_logic,
ttl_seconds=3600 # Keep record for 1 hour
)
return wrapper
return decorator
# --- Usage Example ---
if __name__ == "__main__":
# Setup
my_store = InMemoryIdempotencyStore()
my_budget = RetryBudget(max_attempts=3, timeout_seconds=10.0)
my_backoff = ExponentialBackoff(base=0.5)
# A dummy 3rd party API call
call_count = 0
def generate_key(args, kwargs):
# Create a hash based on arguments to ensure uniqueness
user_id = args[0] if args else kwargs.get('user_id')
action = args[1] if len(args) > 1 else kwargs.get('action')
return f"req-{user_id}-{action}"
@safe_retry(
store=my_store,
key_generator=generate_key,
budget=my_budget,
backoff=my_backoff,
retry_on=[ConnectionError, TimeoutError] # Only retry specific errors
)
def process_payment(user_id: str, action: str, amount: float):
global call_count
call_count += 1
print(f"--- Processing Payment (Call #{call_count}) ---")
# Simulate a flaky service
if call_count < 3:
print("Service unavailable! Simulating ConnectionError...")
raise ConnectionError("Service temporarily unavailable")
print(f"Success! Charged ${amount}")
return {"status": "success", "receipt_id": "12345"}
# Run the example
try:
print("Request 1:")
result = process_payment("user_123", "charge", 50.0)
print(f"Result: {result}\n")
print("Request 2 (Duplicate - should use idempotency cache):")
# Resetting counter to prove it doesn't run the logic again
call_count = 0
result2 = process_payment("user_123", "charge", 50.0)
print(f"Result: {result2}")
except SafeRetryError as e:
print(f"Transaction Failed definitively: {e}")
except Exception as e:
print(f"Unexpected error: {e}")