The user wants a design for a "safe retry library."
The key features requested are:
- Idempotency: Ensuring operations can be safely retried without unintended side effects.
- Budgets: Limiting the number of retries, total time spent, or other resource constraints.
- Backoffs: Strategies for waiting between retries (fixed, jitter, exponential).
I need to structure this response as a comprehensive design document or a library implementation guide. I'll likely choose a popular language like Python or Go for code examples, or perhaps a language-agnostic design pattern, but concrete code makes it much better. Python is generally very readable for design patterns. Let's stick to a generic but implementable design, perhaps using Python-like pseudocode or actual Python for the core logic.
Key Components to Design:
-
The Core Interface: How does the user interact with the library?
- A decorator?
- A context manager?
- A wrapper function/class?
- A
retry(operation, config) function is usually the most flexible.
-
Idempotency:
- Concept: The operation must produce the same result if called multiple times with the same input.
- Implementation:
- Client-side: Generating a unique Idempotency Key (e.g., UUID).
- Server-side interaction: Sending this key in headers (e.g.,
Idempotency-Key).
- Library role: Does the library enforce this? Or just provide hooks?
- Safe Design: The library should probably require or strongly encourage a key generation mechanism. It could also manage a cache of seen keys if the operation is local, but usually, "retry" implies network calls.
- Mechanism: Pass a
generate_idempotency_key callback.
-
Budgets (Constraints):
- Types of Budgets:
- Max attempts (Count).
- Max duration (Timeout/Deadline).
- Budget replenishment (Token bucket? - maybe too complex for a basic retry lib, stick to simple limits).
- Implementation: A
Budget class that tracks state.
- Interface:
budget.acquire() or budget.can_retry().
-
Backoffs (Wait Strategies):
- Types: Fixed, Linear, Exponential, Decorrelated Jitter.
- Jitter: Essential to prevent thundering herds. Randomization is key.
- Implementation: A strategy pattern.
BackoffStrategy.next_wait(attempt, error).
-
Error Handling:
- What errors trigger a retry? (Retryable vs. Fatal).
- User needs to provide a
retryable_predicate.
Structure of the Response:
- High-Level Architecture: Define the interfaces and how they fit together.
- Component Design:
- Backoff Strategies: Implement Exponential with Jitter.
- Budget System: Implement Time and Count budgets.
- Idempotency: Discuss the pattern (Client-side key vs Server-side enforcement).
- The Core Retry Loop: The logic that ties it all together.
- Usage Examples: Show how it looks to the developer.
- Advanced Considerations: Logging, Tracing, Circuit Breaking (mentioning it as a separate concern).
Refining the Idempotency Part:
This is the trickiest part of a retry library.
- If it's a generic library, it can't know how to make the underlying request idempotent (e.g., adding a header).
- Approach: The library should accept a
request_mutator or hook that is called before the attempt, allowing the injection of the idempotency key. Or simpler, the library manages the key generation and passes it to the execution function.
- Safe Design: Ideally, the library should default to requiring an idempotency key for non-GET requests if it were an HTTP client, but as a generic library, it should simply allow the user to attach context.
Refining the Budget Part:
- A "Budget" isn't just a count. It's a resource. A
CompositeBudget could combine a max retry count and a global deadline.
- Deadline propagation: If the context has a deadline, the retry loop must respect it.
Drafting the Code (Mental or Scratchpad):
class RetryPolicy:
def __init__(self, backoff, budget, retry_on):
...
def retry(policy, func, *args):
while policy.budget.allow():
try:
return func(*args)
except Exception as e:
if not policy.retry_on(e): raise
sleep(policy.backoff.wait())
Adding Idempotency:
How do we inject the key?
Maybe the func signature should be func(context).
context contains the idempotency_key.
The library generates the key.
Let's structure the design into:
- Interfaces (Types): Define the contract.
- Strategies: The pluggable logic for backoff and budgets.
- The Engine: The loop.
- Idempotency: How to handle the key.
Self-Correction during drafting: A "Budget" usually implies something that runs out over time (like a monthly error budget). In a retry context, it's usually "Retry Limits" (MaxAttempts, Timeout). I will stick to the term "Budget" as requested, but implement it as "Constraints".
Safety Features to emphasize:
- Jitter: Don't just do
2^n.
- Circuit Breaking: Mention this is distinct but related.
- Deadlines: Use monotonic clocks.
- Safe Threading: If the policy is shared, state needs to be managed carefully (or stateless). The
Budget is the stateful part.
Let's write the response. I will use Python for the examples because it is pseudocode-friendly but executable.
Outline:
- Philosophy: "Safe by Default" (Jitter on, limits on).
- Interface Design: The
Retryer.
- Backoff Strategy:
ExponentialBackoff with Jitter.
- Budget/Constraint:
TimeBudget, CountBudget.
- Idempotency:
IdempotencyKey generation and injection.
- Implementation: The full code.
Detailed thought on Idempotency in the code:
The library should generate a UUID. It should pass this UUID to the function being retried so the function can use it (e.g., as an HTTP header). This ensures the same key is used for all attempts of the same logical request.
Detailed thought on Budgets:
A composite pattern is best. Budgets = [MaxRetries(3), Timeout(10s)]. Check all budgets before retrying.
Detailed thought on Exceptions:
Don't catch Exception. Catch specific base classes or use a predicate is_retryable.
Let's assemble.
Designing a robust retry library requires shifting from a simple "loop with sleep" to a Resilience System. A safe retry library must protect the system from overwhelming itself (thundering herd) and the downstream service from cascading failures.
Here is a design specification for a library named "Resilient-Retry", implemented here in Python-like pseudocode/structures, covering Architecture, Idempotency, Budgets, and Backoffs.
1. Core Architecture
The library should act as a higher-order function (wrapper) that intercepts function calls. It relies on three pillars: Context, Strategy, and Budget.
The Interfaces
class RetryResult(Enum):
SUCCESS = auto()
RETRY = auto()
FAILURE = auto()
class RetryPolicy:
def should_retry(self, exception: Exception, attempt: int) -> bool:
raise NotImplementedError
class BackoffStrategy:
def wait_time(self, attempt: int) -> float:
raise NotImplementedError
class Budget:
def record_attempt(self, result: RetryResult):
raise NotImplementedError
def is_exhausted(self) -> bool:
raise NotImplementedError
2. Idempotency: The Safety Catch
Retrying a non-idempotent operation (like charging a credit card) is dangerous. The library must enforce that the user explicitly opts-in to safety mechanisms or acknowledges idempotency.
The Design Pattern: Idempotency Keys
The library should not just blindly retry. It should attach an Idempotency Key to the request context.
- Auto-Generation: If configured, the library generates a UUID for the transaction scope.
- Dependency Injection: This key is passed to the underlying function arguments.
class RetryContext:
attempt: int
idempotency_key: str # Unique ID for this specific logical operation
metadata: dict
Implementation Detail:
When wrapping a function, the library allows the user to map the idempotency_key to a function argument.
@retry(idempotency_arg="request_id")
def charge_card(amount: int, request_id: str):
# If this retries, request_id remains the same
pass
3. Budgets: Stopping the Bleed
A "Budget" prevents the retry mechanism from keeping a partially failed system alive artificially, which wastes resources that could be used for new requests.
Types of Budgets
- Count Budget: Simple max attempts (e.g., "Try 3 times").
- Time Budget (Deadline): Fail if the total operation time exceeds T (e.g., "Give up after 5 seconds").
- Error Budget (Circuit Breaker Lite): If the global success rate drops below a threshold, stop retrying entirely.
Stateless vs. Stateful:
- Stateless:
max_retries=3 (Standard).
- Stateful:
TokenBucket (Advanced). If the bucket is empty, retries are denied immediately without hitting the network.
class CompositeBudget(Budget):
"""Combines Max Attempts and Deadline"""
def __init__(self, max_retries: int, timeout_seconds: float):
self.max_retries = max_retries
self.deadline = time.now() + timeout_seconds
def is_exhausted(self) -> bool:
return self.current_attempt > self.max_retries or time.now() > self.deadline
4. Backoffs: The Rhythm
Never use time.sleep(n). A fixed interval causes "thundering herds" where all clients retry simultaneously.
Safe Strategies
- Exponential Backoff: Wait 2n seconds.
- Jitter (De-correlation): Add randomness.
- Full Jitter:
random(0, base * 2^attempt)
- Equal Jitter:
(base * 2^attempt / 2) + random(0, base * 2^attempt / 2) (Prevents clumping but ensures some wait time).
The Safe Backoff Implementation
class SafeExponentialBackoff(BackoffStrategy):
def __init__(self, base=0.1, cap=60.0, jitter=True):
self.base = base
self.cap = cap
self.jitter = jitter
def wait_time(self, attempt: int) -> float:
# Calculation: min(cap, base * 2 ** attempt)
sleep_time = min(self.cap, self.base * (2 ** attempt))
if self.jitter:
# "Full Jitter" strategy
sleep_time = random.uniform(0, sleep_time)
return sleep_time
5. The "Safe Retry" Orchestrator
This brings it all together. The Orchestrator manages the flow, inspects the budget, calculates sleep times, and injects idempotency.
Pseudocode Implementation
def safe_retry(
func,
policy: RetryPolicy,
budget: Budget,
backoff: BackoffStrategy,
idempotency_generator: Callable
):
def wrapper(*args, **kwargs):
# 1. Generate Idempotency Context
context = RetryContext(
attempt=0,
idempotency_key=idempotency_generator()
)
while True:
# 2. Check Budget BEFORE execution
if budget.is_exhausted():
raise BudgetExhaustedException("Retry budget depleted")
try:
# Inject idempotency key if the function signature expects it
result = func(*args, **kwargs, __retry_context=context)
# 3. Handle Success
budget.record_attempt(RetryResult.SUCCESS)
return result
except Exception as e:
# 4. Classify Exception
if not policy.should_retry(e, context.attempt):
raise e # Non-retryable error (e.g., 403 Forbidden)
# 5. Calculate Backoff
wait = backoff.wait_time(context.attempt)
# 6. Record Attempt in Budget
budget.record_attempt(RetryResult.RETRY)
context.attempt += 1
# 7. Sleep (Respect Intterupts)
time.sleep(wait)
return wrapper
6. Advanced Safety: Classifying Errors
Not all errors should be retried. Retrying a 401 Unauthorized or 400 Bad Request is futile and wastes budget.
The Policy Layer:
class HttpRetryPolicy(RetryPolicy):
RETRYABLE_STATUS_CODES = {408, 429, 500, 502, 503, 504}
def should_retry(self, exception: Exception, attempt: int) -> bool:
# 1. Network level errors (SocketTimeout) -> Retry
if isinstance(exception, NetworkError):
return True
# 2. HTTP Errors -> Check Code
if isinstance(exception, HttpError):
return exception.status_code in self.RETRYABLE_STATUS_CODES
# 3. Everything else (Bug, Validation) -> Fail fast
return False
Summary of Configuration
A fully safe call would look like this:
# Configuration
policy = HttpRetryPolicy()
budget = CompositeBudget(max_retries=5, timeout_seconds=30.0)
backoff = SafeExponentialBackoff(base=0.5, jitter=True)
# Usage
@retry(policy=policy, budget=budget, backoff=backoff)
def fetch_external_data(url, __retry_context=None):
# Logic to use __retry_context.idempotency_key as a header
return requests.get(url)