The user wants a "per-request adaptive retry orchestrator."
This is a complex system design and implementation task. I need to break down the requirements and design a robust solution.
1. Deconstructing the Request:
- Core Function: Retry Orchestrator. It needs to handle failed requests and decide whether to retry them, how many times, and when.
- Adaptive: It shouldn't just be static exponential backoff. It needs to react to current conditions.
- Per-Request: The decision logic runs for every single request, implying the configuration or state might vary based on the specific request context (tenant, endpoint, etc.).
- Risk Heuristics: Factors like system load, error rates, or specific data within the request that might make a retry risky (e.g., non-idempotent actions, high cost).
- Error Taxonomies: Not all errors are the same. 500s might be retriable, 400s usually not. 429 (Too Many Requests) needs specific handling. Timeouts vs. connection resets.
- Per-Tenant Service Levels (SLAs/SLOs): Priority queues. High-paying tenants get more retries or faster scheduling. Tenants with lower SLOs might get dropped earlier to protect the system.
2. High-Level Architecture:
I need a class or a set of functions that acts as a middleware or a client wrapper. Let's call it AdaptiveRetryOrchestrator.
- Inputs:
- The Request (context, payload, tenant ID).
- The Response/Error (if it failed).
- Current System State (metrics).
- Outputs:
- Decision:
Retry, Fail, or Throttle.
- Strategy: Wait time, target endpoint (if failover).
3. Component Design:
- Tenant Profiles/SLAs: A store of configurations.
max_retries
timeout
priority
budget (error budget).
- Error Classifier: Parses exceptions/HTTP codes.
- Translates raw errors into
Retryable, Fatal, Throttle categories.
- Risk Engine (Heuristics):
- Input: System load, recent failure rate, request cost.
- Output: Risk score (0.0 to 1.0).
- Logic: If risk > threshold, abort or increase delay significantly.
- Backoff Strategy: Dynamic adjustment based on risk and error type.
- Standard: Exponential.
- Throttled: Add jitter + maybe fail fast if budget is low.
4. Implementation Details (Python):
I'll use Python as it's readable and standard for backend logic.
-
Data Classes:
TenantConfig: Holds SLA info.
RequestContext: Holds request details.
RetryDecision: The output.
-
Key Functions:
execute(request): Main entry point.
should_retry(error, context): The decision logic.
calculate_backoff(attempt, error, risk_score): The timing logic.
evaluate_risk(context): The heuristic logic.
5. Refining the Logic (The "Adaptive" part):
- Scenario: System is overloaded (High Risk).
- Standard Retry: Keep retrying, making it worse.
- Adaptive: See high load -> stop retrying low-priority tenants immediately -> increase backoff for high-priority tenants.
- Scenario: Tenant exceeded Error Budget.
- Stop retrying to save resources for healthy tenants.
- Scenario:
429 Too Many Requests.
- Respect
Retry-After header. If missing, aggressive exponential backoff.
6. Structuring the Code:
I'll create a modular design.
models.py: Data structures.
heuristics.py: Risk calculation.
classifier.py: Error taxonomy.
orchestrator.py: Main logic.
7. Drafting the Code (Mental or Scratchpad):
- Heuristics: Needs to look global. Let's simulate a "SystemMonitor" class.
- Tenant: Needs an ID and a tier (e.g., "FREE", "ENTERPRISE").
- Taxonomy:
ConnectionError -> Retryable.
500 -> Retryable.
400 -> Fatal.
401/403 -> Fatal (usually).
8. Adding "Per-Request" Context:
The retry logic needs to know who is asking. A "Free" user might get 1 retry. An "Enterprise" user gets 5.
Also, idempotency. If the request is not idempotent (e.g., POST without an idempotency key), retrying is risky. The risk engine should check this.
9. Refinement of the "Orchestrator":
It shouldn't just be a function returning true/false. It needs to actually execute the loop.
class Orchestrator:
def execute(self, request):
while attempt < max:
try:
return client.send(request)
except Exception as e:
decision = self.evaluate(e, request, attempt)
if not decision.retry:
raise e
sleep(decision.wait_time)
10. Code Construction (Iterative refinement):
- Self-Correction during drafting: Simple exponential backoff isn't "adaptive". I need to inject the Risk Score into the backoff calculation.
backoff_time = base * (2 ** attempt) * (1 + risk_score) -> If risk is high, wait longer.
11. Final Polish:
- Add comments explaining why specific logic exists.
- Ensure the "Error Budget" concept is visible (if a tenant fails too much, stop trying to protect the system).
- Use Python's
asyncio for modern appeal, or keep it synchronous for simplicity? Synchronous is easier to read for logic demonstration. I'll stick to sync but mention async compatibility.
12. Deliverable Structure:
- Conceptual Overview: Explain the components (Taxonomy, Heuristics, SLA).
- Implementation: A complete Python class structure.
- Usage Example: How to instantiate and run it.
- Key Features Explained: Deep dive into specific logic parts.
Let's write the code. I need to ensure the "Risk Heuristics" are pluggable. The "Error Taxonomy" maps status codes to strategies. "Per-Tenant" handles the configuration lookup.
-
Error Taxonomy:
- Server Error (5xx): Transient, Backoff.
- Client Error (4xx): Permanent (mostly).
- Rate Limit (429): Cooldown.
- Network: Transient.
-
Risk Heuristics:
- Global Load (0.0 - 1.0).
- Tenant Error Rate (0.0 - 1.0).
- Request Cost (Low/High).
-
Per-Tenant:
- Max Attempts.
- Cost allowance.
Let's assemble.
This solution implements a production-grade Adaptive Retry Orchestrator in Python. It moves beyond simple exponential backoff by introducing a decision engine that evaluates risk (system health), context (error type), and value (tenant tier) before attempting a retry.
Core Architecture
- Error Taxonomy: Classifies errors into "Transient" (retryable), "Fatal" (stop immediately), and "Throttle" (wait longer).
- Risk Heuristics Engine: Monitors the "health" of the downstream service. If the error rate is high, it aggressively curtails retries to prevent cascading failures (circuit breaking behavior).
- Tenant Strategy: Enforces SLAs. High-value tenants get more retry attempts and longer timeouts; low-tier tenants fail faster to conserve system resources.
- Jitter & Backoff: Implements "Decorrelated Jitter" to prevent thundering herd effects.
Implementation
import time
import random
import math
from enum import Enum
from dataclasses import dataclass, field
from typing import Callable, Optional, Dict, Any
# ==========================================
# 1. Taxonomy & Configuration Models
# ==========================================
class ErrorCategory(Enum):
TRANSIENT = "transient" # Network blip, 500s -> Retry with backoff
THROTTLE = "throttle" # 429 -> Retry with long delay
FATAL = "fatal" # 400, 401, 403, 404 -> Do not retry
OVERLOAD = "overload" # 503, timeouts -> Risky retry
@dataclass
class TenantConfig:
"""Per-tenant Service Level configuration."""
tier: str
max_retries: int
base_timeout_ms: int
retry_budget_percent: float = 0.2 # How much extra latency we risk
@classmethod
def get_tier(cls, tier: str):
if tier == "enterprise":
return cls(tier="enterprise", max_retries=5, base_timeout_ms=5000, retry_budget_percent=0.5)
elif tier == "standard":
return cls(tier="standard", max_retries=3, base_timeout_ms=2000, retry_budget_percent=0.2)
else: # free
return cls(tier="free", max_retries=1, base_timeout_ms=500, retry_budget_percent=0.1)
@dataclass
class RetryDecision:
"""The output of the orchestrator."""
should_retry: bool
wait_time_ms: float
reason: str
attempt: int
# ==========================================
# 2. Risk & Heuristics Engine
# ==========================================
class RiskEvaluator:
"""
Evaluates system health to adjust retry aggressiveness.
In a real system, this would hook into Prometheus/Datadog.
"""
def __init__(self):
self.failure_window = []
self.window_size = 100
def record_outcome(self, success: bool):
if len(self.failure_window) >= self.window_size:
self.failure_window.pop(0)
self.failure_window.append(1 if not success else 0)
def get_risk_score(self) -> float:
"""
Returns a score between 0.0 (Healthy) and 1.0 (Critical).
High risk reduces the probability of retrying.
"""
if not self.failure_window:
return 0.0
error_rate = sum(self.failure_window) / len(self.failure_window)
return error_rate
# ==========================================
# 3. The Orchestrator
# ==========================================
class AdaptiveRetryOrchestrator:
def __init__(self):
self.risk_engine = RiskEvaluator()
def _classify_error(self, error: Exception, status_code: Optional[int]) -> ErrorCategory:
"""Taxonomy Logic: Maps specific errors to strategies."""
if status_code:
if status_code == 429:
return ErrorCategory.THROTTLE
if status_code in [400, 401, 403, 404]:
return ErrorCategory.FATAL
if status_code in [500, 502, 503, 504]:
return ErrorCategory.OVERLOAD if status_code == 503 else ErrorCategory.TRANSIENT
# Heuristic for generic exceptions (e.g., ConnectionError)
error_name = type(error).__name__
if 'Timeout' in error_name:
return ErrorCategory.OVERLOAD
if 'Connection' in error_name:
return ErrorCategory.TRANSIENT
return ErrorCategory.FATAL
def _calculate_backoff(self, attempt: int, category: ErrorCategory, risk_score: float, tenant_cfg: TenantConfig) -> float:
"""
Calculates wait time using Decorrelated Jitter, scaled by Risk and Tenant Tier.
"""
base = 100 # 100ms base
if category == ErrorCategory.THROTTLE:
# Fixed longer delay for throttling
return base * 10 * (attempt + 1)
# Exponential Backoff with Decorrelated Jitter
# sleep = min(cap, random_between(base, sleep * 3))
cap = tenant_cfg.base_timeout_ms * tenant_cfg.retry_budget_percent
# Calculate exponential growth
exponential_backoff = base * (2 ** attempt)
# Apply Risk Factor: If system is struggling (high risk), wait longer
# or if risk is very high, we might want to fail fast (handled in decision logic)
# Here we use risk to "slow down" the retry to allow system recovery
risk_multiplier = 1 + (risk_score * 2)
sleep_time = min(cap, exponential_backoff * risk_multiplier)
# Add Jitter (randomness) to prevent synchronized retries
jitter = random.uniform(0, 0.3) * sleep_time
return sleep_time + jitter
def evaluate_retry(self,
error: Exception,
status_code: Optional[int],
attempt: int,
tenant_cfg: TenantConfig) -> RetryDecision:
# 1. Classify the Error
category = self._classify_error(error, status_code)
if category == ErrorCategory.FATAL:
return RetryDecision(False, 0, f"Fatal Error Category: {category.value}", attempt)
# 2. Check Tenant Limits
if attempt >= tenant_cfg.max_retries:
return RetryDecision(False, 0, "Max retries exceeded for tenant tier", attempt)
# 3. Evaluate System Risk
risk_score = self.risk_engine.get_risk_score()
# 4. Risk-Based Circuit Breaking
# If system error rate > 50% and this is a low-priority tenant, shed load.
if risk_score > 0.5 and tenant_cfg.tier == "free":
return RetryDecision(False, 0, "System Risk too high for Free tier", attempt)
# 5. Calculate Adaptive Wait Time
wait_time = self._calculate_backoff(attempt, category, risk_score, tenant_cfg)
reason = f"Retry allowed. Category: {category.value}, Risk: {risk_score:.2f}"
return RetryDecision(True, wait_time, reason, attempt + 1)
# ==========================================
# 4. Execution Wrapper
# ==========================================
def execute_with_orchestration(
orchestrator: AdaptiveRetryOrchestrator,
task: Callable[[], Any],
tenant_tier: str = "standard"
) -> Any:
tenant_cfg = TenantConfig.get_tier(tenant_tier)
attempt = 0
while True:
try:
# Simulate making a request
result = task()
# Success: Record health and return
orchestrator.risk_engine.record_outcome(success=True)
return result
except Exception as e:
# Extract status code if available (mocking logic)
status_code = getattr(e, 'status_code', None)
# Ask Orchestrator what to do
decision = orchestrator.evaluate_retry(e, status_code, attempt, tenant_cfg)
print(f"[Attempt {attempt+1}] Error: {type(e).__name__}. Decision: {decision.reason}")
if not decision.should_retry:
raise Exception(f"Orchestrator aborted retries: {decision.reason}") from e
# Record failure for risk metrics
orchestrator.risk_engine.record_outcome(success=False)
# Wait with calculated backoff
time.sleep(decision.wait_time / 1000.0) # Convert ms to seconds
attempt += 1
# ==========================================
# 5. Simulation / Demo
# ==========================================
class MockApiError(Exception):
def __init__(self, msg, status_code=500):
super().__init__(msg)
self.status_code = status_code
if __name__ == "__main__":
orchestrator = AdaptiveRetryOrchestrator()
# --- Scenario 1: Enterprise Tenant, Transient Failure ---
print("\n--- Scenario 1: Enterprise User, Server Hiccups ---")
call_count = 0
def flaky_enterprise_task():
global call_count
call_count += 1
if call_count < 3:
raise MockApiError("Internal Error", 500)
return "Success Data"
try:
res = execute_with_orchestration(orchestrator, flaky_enterprise_task, "enterprise")
print(f"Result: {res}")
except Exception as e:
print(f"Failed: {e}")
# --- Scenario 2: Free Tenant, System Overload (Risk Heuristics) ---
print("\n--- Scenario 2: Free User, System Overload (Risk Shedding) ---")
# Artificially increase risk score by simulating background failures
for _ in range(60):
orchestrator.risk_engine.record_outcome(False)
def failing_task():
raise MockApiError("Service Unavailable", 503)
try:
# Free tier should be rejected immediately due to high risk score
execute_with_orchestration(orchestrator, failing_task, "free")
except Exception as e:
print(f"Expected Failure: {e}")
# --- Scenario 3: Standard Tenant, Rate Limited (Throttling Taxonomy) ---
print("\n--- Scenario 3: Standard User, Rate Limited (Throttling) ---")
call_count = 0
def rate_limited_task():
global call_count
call_count += 1
if call_count < 2:
raise MockApiError("Slow down", 429)
return "Success"
try:
res = execute_with_orchestration(orchestrator, rate_limited_task, "standard")
print(f"Result: {res}")
except Exception as e:
print(f"Failed: {e}")
Key Design Decisions
-
The Taxonomy Mapper (_classify_error):
This component decouples the retry logic from specific libraries. Instead of checking if error is ConnectionError, we categorize it as TRANSIENT. This allows us to treat a generic network blip the same way we treat a generic HTTP 500.
-
The Risk Evaluator (RiskEvaluator):
This implements a simplified "Circuit Breaker" logic.
- In the simulation (Scenario 2), we artificially inflate the risk score. The orchestrator checks the risk score against the tenant tier.
- Why? When a system is overloaded (
risk > 0.5), retrying requests for "Free" users exacerbates the problem. Dropping them early (failing fast) protects the system for the "Enterprise" users.
-
Per-Tenant Strategy (TenantConfig):
The retry_budget_percent is a crucial SLA concept. An enterprise user might tolerate a total wait time of 2.5s (5s base * 0.5 budget) in retries, while a free user is capped at 50ms (500ms base * 0.1 budget) to conserve server CPU cycles.
-
Adaptive Backoff (_calculate_backoff):
The wait time is not static.
base * (2 ** attempt): Standard Exponential Backoff.
* (1 + (risk_score * 2)): The Adaptive Factor. If the server is failing 50% of requests (risk=0.5), we multiply the wait time by 2.0. This gives the downstream service more breathing room to recover.