The user asks: "Build a per-request adaptive retry orchestrator that evaluates risk heuristics, error taxonomies, and per-tenant service-levels."
We need to produce a design (likely software design) and possibly implementation code for an adaptive retry orchestrator. The orchestrator should consider risk heuristics, error taxonomies, and per-tenant service-levels. It should be per-request, meaning it makes decisions for each request individually, perhaps adjusting retry behavior based on context.
We need to produce a thorough answer: architecture, components, algorithm, data structures, perhaps a sample implementation in a common language (like Python, Java, Go). Since the user said "Build", they might expect code. But it's ambiguous: could be design description. I'd produce both: a detailed design and code snippets.
We also need to consider: risk heuristics (maybe based on error type, request criticality, tenant importance, etc.), error taxonomies (classify errors into transient vs permanent, maybe with categories), per-tenant service-levels (e.g., different SLAs for different tenants, maybe premium tenants get more aggressive retries or less depending on risk). The orchestrator should adaptively decide: whether to retry, how many retries, backoff strategy, maybe circuit breaking.
The problem: We want to avoid overloading failing services, but also maximize success for critical requests.
We need to think about: request context (tenant ID, request priority, maybe time of day, etc.), historical data (success rates per tenant/service), risk score (maybe based on business impact of failure), error taxonomy (HTTP status codes, exception types). For each request, we could compute a retry policy: max retries, backoff multiplier, jitter, maybe whether to retry at all. Also could incorporate rate limiting, circuit breaking.
We need to design a system that can be integrated as a middleware or client library for making external service calls, or as a server-side proxy.
Let's outline:
-
Introduction: What is adaptive retry? Why per-request? Goals.
-
Key concepts:
- Error taxonomy: classification of errors (transient, permanent, rate-limited, etc.)
- Risk heuristics: metrics that quantify the risk of retrying (e.g., potential impact on system, tenant SLA, current system load, error rate trends)
- Per-tenant service-levels: SLAs or tiers (e.g., gold, silver, bronze) that define acceptable performance and penalties.
-
Architecture:
- Orchestrator component: intercepts requests, evaluates context, decides retry policy.
- Policy engine: uses rules or ML model to compute retry parameters.
- Data store: for storing tenant configurations, historical metrics, error taxonomies.
- Metrics collector: collects success/failure, latency, etc.
- Config manager: allows dynamic updates.
-
Workflow:
- Request comes in with tenant ID, endpoint, maybe priority.
- Orchestrator fetches tenant's service-level (SLA tier) and associated retry profile (maybe max retries, allowed backoff).
- It also looks up error taxonomy for the type of error (maybe from a mapping of error codes to categories). If the request fails, it classifies the error.
- It also computes risk heuristics: current error rate for that service, recent failures, tenant importance, time of day, maybe business impact.
- Combines these to adjust retry decisions: e.g., if error is transient and risk is low, increase retries; if risk high (e.g., many failures, high load), reduce retries or fail fast.
- Apply backoff strategy based on adjusted parameters.
- After max retries or success, report.
-
Implementation details:
- Data structures: TenantConfig (tier, retry limits, backoff factors), ErrorCategory (transient, permanent, etc.), ServiceMetrics (error rates, latency histograms).
- Decision algorithm: Could be rule-based: If errorCategory == transient and tenant.tier == premium then maxRetries = 5 else 2. Or more complex: riskScore = f(serviceErrorRate, tenantPriority, requestCriticality). Then maxRetries = baseMaxRetries * riskScore? Actually riskScore could be a probability of success? Hmm.
- Could use a machine learning model that predicts success probability of retry given features: error type, service, tenant tier, time, recent failure count, etc. Then set max attempts = 1 + floor(successProbability * something). But maybe simpler.
-
Sample code in Python:
- Define classes: RetryOrchestrator, TenantRegistry, MetricsCollector, ErrorTaxonomy.
- Orchestrate a request with retry loop, adjusting backoff.
- Use exponential backoff with jitter.
- Demonstrate usage.
-
Testing and evaluation: How to test? Simulate failures, measure success rates vs naive retry.
-
Considerations: Thread safety, performance, avoiding retry storms, coordinating retries across tenants (maybe using token bucket), circuit breakers.
-
Extensions: Could integrate with distributed tracing.
Given the instruction: "Build a per-request adaptive retry orchestrator that evaluates risk heuristics, error taxonomies, and per-tenant service-levels." It's like an exam question. I should produce a solution.
We'll write in Markdown with code blocks. Let's produce a clear design and a Python implementation.
We need to be careful: The orchestrator is "per-request adaptive", meaning each request can have different retry behavior based on its context, not a static policy per service.
We'll design:
- RequestContext: contains tenant_id, request_id, maybe priority, endpoint, etc.
- ErrorTaxonomy: mapping from error code (HTTP status, exception type) to category (transient, permanent, rate-limit, etc.)
- TenantServiceLevel: tier (e.g., gold, silver, bronze), with associated base retry limit and maybe aggressiveness factor.
- RiskHeuristics: factors like current system load, error rate for the target service (last minute), tenant's recent failure count, maybe time since last retry for that service (to avoid thundering herd). Could be computed as a risk score that influences retry decisions.
We'll define:
class RetryPolicy:
max_attempts: int
backoff_factor: float # multiplier for base delay
jitter: bool
But these can be computed on the fly per request based on risk.
Algorithm:
-
Before first attempt, compute policy based on tenant's SLA and possibly risk heuristics (maybe from service metrics). Actually, risk heuristics may depend on what happens during retries (e.g., after a failure, error rate may increase). So we could recompute policy after each failure.
-
On failure:
- Classify error using taxonomy. If error is permanent, abort.
- Update metrics (increment failure count for service/tenant).
- Compute new risk factors: maybe current error rate for that service is high => reduce remaining attempts.
- Compute remaining attempts: perhaps initial max_attempts adjusted by risk factor (e.g., if error rate > threshold, reduce by half). Or even decide to stop early.
- Compute backoff: exponential base * backoff_factor, possibly add jitter.
- Sleep and retry.
-
On success: reset metrics, report success.
We need to store per-request state: remaining attempts, current backoff.
Implementation:
We'll have an orchestrator class that takes a callable (the actual request function). The orchestrator will wrap it with retry logic.
The orchestrator will need dependencies:
- TenantConfigProvider: get config for tenant_id.
- ErrorTaxonomyProvider: get category for error.
- MetricsProvider: get current metrics for service (error rate, latency, etc.)
- Clock: for time.
We'll define interfaces.
We'll implement a simple rule-based risk heuristic: if service error rate in last 60 seconds > 0.5, risk is high; else low. Also if tenant is premium, they may get more retries even under high risk? Actually risk heuristics might be used to reduce retries to protect system; for premium tenants, we might be more lenient? Not sure. Let's define: risk is a value between 0 (low risk) and 1 (high risk). We'll compute risk = 0.7 * service_error_rate + 0.3 * (some other factor). Then we can adjust max_attempts: effective_max = int(base_max * (1 - risk))? But if risk high, we reduce max attempts. But if base_max is 5, and risk=0.8, then effective_max = 1? That might be too low. Actually we might want to reduce retries when risk is high, meaning fewer attempts because we don't want to overload. Or maybe for critical requests we want to maintain attempts regardless? That's a policy decision. Simpler: we define a mapping from risk level to retry limits: low: base_max, medium: base_max/2, high: 1 (just fail fast). Could also incorporate tenant tier: premium gets higher limits even at medium risk.
So we need a function: compute_retry_limit(tenant_tier, risk_score, base_limits) -> int.
We also need to handle backoff: base_delay = initial_delay * (backoff_factor ** (attempt - 1)). With jitter: random between 0 and base_delay.
We'll implement a class AdaptiveRetryOrchestrator with a method execute(request_context, request_func, *args, **kwargs). request_func is a function that makes the actual HTTP call (or any operation) and raises exceptions on failure. It might also return a response.
We'll catch exceptions, classify, decide retry.
We'll also need to handle that some errors might be non-retriable at all (e.g., 400 Bad Request). So after each failure, check if error category is permanent: if so, break.
We'll maintain metrics: we can simulate with in-memory counters.
We'll also need thread-safe metric updates.
We'll produce a simplified but functional code.
After code, we can discuss enhancements.
We'll also show usage.
Let's start writing.
We'll define:
ErrorCategory: ENUM with TRANSIENT, PERMANENT, RATE_LIMITED, UNKNOWN.
Taxonomy: map based on exception type or status code. For simplicity, we'll assume request_func raises HttpError with status_code.
TenantTier: GOLD, SILVER, BRONZE.
We'll define TenantConfig: tier, base_max_retries, base_backoff_factor (maybe constant across tenants? Could differ). For example, GOLD: base_max=5, SILVER:3, BRONZE:2.
We'll have a RiskHeuristicCalculator that takes service metrics (error rate, failure count) and maybe request context to compute risk score.
We'll have a ServiceMetricsCollector that tracks per-service error rate over sliding window. Could be simple: maintain list of timestamps of failures, compute rate = failures / window.
We'll also need to account for multiple concurrent requests: maybe use a shared metrics store.
We'll implement:
class ServiceMetrics:
def init(self):
self.failures = [] # list of timestamps
self.lock = threading.Lock()
def record_failure(self):
with self.lock:
now = time.time()
self.failures.append(now)
# prune old ones (> window)
self.failures = [t for t in self.failures if now - t < 60]
def error_rate(self):
with self.lock:
now = time.time()
recent = [t for t in self.failures if now - t < 60]
return len(recent) / 60.0 # failures per second; but maybe we want failures per request? Not needed, just relative.
But we need request count too to get rate. Could also track total requests. Actually error rate as failures per second is not normalized by request volume. Better: keep counts of successes and failures over sliding window, or maintain moving average of failure rate. Simpler: maintain a list of outcomes (success/failure) with timestamps, compute failure ratio in last N requests or time. We can keep a list of (timestamp, is_failure) and prune old, then compute ratio of failures. But this might get large. For demo, simple.
We'll track per service name. We'll have a dict: service_name -> ServiceMetrics.
We also need to capture successes to compute success rate? Actually risk might be higher if recent failure count is high relative to request volume. Without request volume, high error rate could be due to high traffic or low. But we can approximate using failure rate per second if we also know request rate. Could track both. Let's keep it simple: we'll maintain a counter of total requests and failures in the last minute, reset each minute? Or use a rolling window.
Simpler: We'll compute risk based solely on recent failure count: if failures in last 60 sec > threshold, risk high. That's a heuristic.
Define risk thresholds:
- low: failures < 5
- medium: 5 <= failures < 20
- high: >=20
Then risk_score = (failures / 20) capped at 1.0.
But we can also adjust by tenant tier: for GOLD, we might be more tolerant (scale factor). We'll keep it simple.
We'll create class RiskHeuristic:
def calculate_risk(service_name, tenant_tier):
failures = metrics.get_failures_last_60s(service_name)
base_risk = min(failures / 20.0, 1.0)
# Tier adjustments: BRONZE more sensitive, GOLD less?
# Suppose we want to be more aggressive for higher tiers: they get more retries even under risk. So we could reduce risk for higher tiers.
tier_factor = {'GOLD': 0.5, 'SILVER': 0.75, 'BRONZE': 1.0}[tenant_tier]
risk = base_risk * tier_factor
return min(risk, 1.0)
But careful: if we multiply by factor <1, risk reduces, meaning we allow more retries. That might be desirable for premium.
Now compute effective max attempts:
tenant_base_max = tenant_config.base_max_retries
risk = risk_score
reduce max by risk factor: lower max when risk high.
effective_max = max(1, int(tenant_base_max * (1 - risk))) # But if risk=1, effective_max=0? So adjust: maybe (1 - risk/2) etc. Let's do: effective_max = int(tenant_base_max * (1 - risk * 0.5))? Let's think.
Simplify: map risk to a retry limit multiplier:
if risk < 0.3: multiplier = 1.0 (full)
elif risk < 0.6: multiplier = 0.7
else: multiplier = 0.3
effective_max = max(1, int(tenant_base_max * multiplier))
Or we could compute directly: effective_max = tenant_base_max - floor(risk * (tenant_base_max - 1)). But if risk=1, we get 1 remainder? That's okay: minimum 1 attempt (the initial). Actually we always try at least once, then retries. So max_attempts includes initial attempt. So base_max is total attempts. We want to reduce number of retries, not the initial call. So number of retries = effective_max - 1. So we could set max_attempts = 1 + floor((tenant_base_max-1) * (1 - risk)). That ensures at least 1 attempt. Or we can decide to fail fast after first failure if risk high.
Let's do: max_attempts = 1 + int((tenant_base_max - 1) * (1 - risk))
That gives: if risk=0 => base_max; if risk=1 => 1 (no retry); if risk=0.5 => half retries.
That seems reasonable.
Now backoff: initial_backoff = some base (e.g., 0.1s), backoff_factor = 2, jitter = random.
But we could also adjust backoff factor based on risk: higher risk -> longer backoff to avoid hammering. Or base backoff increase with each failure. We'll keep exponential.
We'll also incorporate per-tenant backoff factor maybe from config.
Now code structure:
We'll have:
-
HttpError class with status_code and maybe message.
-
ErrorTaxonomy: dictionary mapping status codes to categories. e.g., 429: RATE_LIMITED, 5xx: TRANSIENT (except 501? but 5xx generally transient), 4xx (except 429) PERMANENT maybe (except 408 Request Timeout which is transient). Actually 408 is transient. But we'll keep simple.
-
TenantConfig: mapping tenant_id -> config (tier, base_max_retries, backoff_factor, initial_delay). We'll assume we can get it via provider.
-
Orchestrator:
class AdaptiveRetryOrchestrator:
def init(self, tenant_provider, metrics_collector, error_taxonomy, clock=time.time, sleep=time.sleep):
self.tenant_provider = tenant_provider
self.metrics = metrics_collector
self.taxonomy = error_taxonomy
self.clock = clock
self.sleep = sleep
def execute(self, tenant_id, service_name, request_func, *args, **kwargs):
# get tenant config
tenant_config = self.tenant_provider.get_config(tenant_id)
# maybe fetch risk later after first failure? We need to compute initial max attempts? Could compute before each attempt based on current risk.
# We'll compute max_attempts dynamically after each failure.
attempt = 0
last_exception = None
while True:
attempt += 1
try:
response = request_func(*args, **kwargs)
# success
self.metrics.record_success(service_name)
return response
except HttpError as e:
last_exception = e
# record failure for metrics
self.metrics.record_failure(service_name)
# classify error
category = self.taxonomy.classify(e.status_code)
if category == ErrorCategory.PERMANENT:
# no retry
break
# compute risk score using current metrics (including this failure)
risk = self.compute_risk(service_name, tenant_config.tier)
# compute max_attempts allowed
max_attempts = self.compute_max_attempts(tenant_config.base_max_retries, risk)
if attempt >= max_attempts:
break
# compute backoff
delay = self.compute_backoff(attempt, tenant_config.initial_delay, tenant_config.backoff_factor)
self.sleep(delay)
except Exception as e:
# unknown error, maybe treat as transient? or re-raise?
# For safety, treat as transient up to max attempts?
self.metrics.record_failure(service_name)
last_exception = e
risk = self.compute_risk(service_name, tenant_config.tier)
max_attempts = self.compute_max_attempts(tenant_config.base_max_retries, risk)
if attempt >= max_attempts:
break
delay = self.compute_backoff(attempt, tenant_config.initial_delay, tenant_config.backoff_factor)
self.sleep(delay)
# out of loop, raise last exception or a custom error
raise last_exception
def compute_risk(self, service_name, tier):
failures = self.metrics.get_failures_last_60s(service_name) # count failures in last 60s
base_risk = min(failures / 20.0, 1.0) # threshold 20
tier_factor = {'GOLD': 0.5, 'SILVER': 0.75, 'BRONZE': 1.0}[tier]
risk = base_risk * tier_factor
return min(risk, 1.0)
def compute_max_attempts(self, base_max, risk):
# include initial attempt
if base_max <= 1:
return 1
retries_allowed = int((base_max - 1) * (1 - risk))
return 1 + retries_allowed
def compute_backoff(self, attempt, initial_delay, backoff_factor):
# attempt is 1-indexed; we want delay before next attempt after failure.
# For first retry (after first failure, attempt=2? Actually after failure on attempt 1, we want delay before attempt 2. So backoff based on retry count = attempt-1.
retry_num = attempt - 1
delay = initial_delay * (backoff_factor ** retry_num)
jitter = random.uniform(0, delay * 0.1) # 10% jitter
return delay + jitter
But note: risk changes after each failure, so max_attempts may shrink dynamically. That's okay.
We need metrics methods:
class ServiceMetricsCollector:
def init(self):
self.services = {} # service_name -> ServiceMetrics
self.lock = threading.Lock()
def get_metrics(self, service_name):
with self.lock:
if service_name not in self.services:
self.services[service_name] = ServiceMetrics()
return self.services[service_name]
def record_success(self, service_name):
# we may want to update success count
metrics = self.get_metrics(service_name)
metrics.record_success()
def record_failure(self, service_name):
metrics = self.get_metrics(service_name)
metrics.record_failure()
def get_failures_last_60s(self, service_name):
metrics = self.get_metrics(service_name)
return metrics.failures_last_60s()
class ServiceMetrics:
def init(self):
self.failures = [] # timestamps of failures
self.successes = [] # optionally, but not needed for risk
self.lock = threading.Lock()
def record_failure(self):
now = time.time()
with self.lock:
self.failures.append(now)
# prune old failures
self.failures = [t for t in self.failures if now - t < 60]
def record_success(self):
# we could record successes but not used; could prune but not needed.
pass
def failures_last_60s(self):
now = time.time()
with self.lock:
# prune before counting?
# Can prune and count in one go
self.failures = [t for t in self.failures if now - t < 60]
return len(self.failures)
But this approach may not be efficient for high QPS because list grows then prune each call. Could use deque with maxlen based on time, but easier for demo.
We could also maintain a counter with timestamps in a ring buffer, but okay.
Now tenant provider:
class SimpleTenantProvider:
def init(self, configs):
self.configs = configs # dict tenant_id -> TenantConfig
def get_config(self, tenant_id):
return self.configs.get(tenant_id, TenantConfig.default())
TenantConfig:
class TenantConfig:
def init(self, tier, base_max_retries=3, initial_delay=0.1, backoff_factor=2.0):
self.tier = tier
self.base_max_retries = base_max_retries
self.initial_delay = initial_delay
self.backoff_factor = backoff_factor
@staticmethod
def default():
return TenantConfig(tier='BRONZE', base_max_retries=2)
Error taxonomy:
class ErrorCategory(Enum):
TRANSIENT = auto()
PERMANENT = auto()
RATE_LIMITED = auto()
UNKNOWN = auto()
class ErrorTaxonomy:
def init(self):
self.map = {
408: ErrorCategory.TRANSIENT,
429: ErrorCategory.RATE_LIMITED,
500: ErrorCategory.TRANSIENT,
502: ErrorCategory.TRANSIENT,
503: ErrorCategory.TRANSIENT,
504: ErrorCategory.TRANSIENT,
# 4xx others
400: ErrorCategory.PERMANENT,
403: ErrorCategory.PERMANENT,
404: ErrorCategory.PERMANENT,
# etc.
}
def classify(self, status_code):
return self.map.get(status_code, ErrorCategory.UNKNOWN)
But we need to handle exceptions that aren't HttpError. In that case we may treat as transient up to max.
We'll also treat network errors like ConnectionError as transient.
We'll modify except block: except HttpError as e: then use status. If other exception, we can treat as transient up to max.
Now we need to import random, time, threading.
Let's produce the full code in a single block.
We'll also show a simple usage:
def mock_request(should_fail, status_code):
if should_fail:
raise HttpError(status_code, "error")
return "OK"
orchestrator = AdaptiveRetryOrchestrator(tenant_provider, metrics, taxonomy)
tenant_id = "tenant1"
service = "order-service"
for i in range(10):
# simulate some requests
...
But we can just demonstrate.
We'll also discuss that we could incorporate more sophisticated risk: e.g., current system load, circuit state. Also we could persist metrics to a DB.
Now think about per-request adaptive: The orchestrator evaluates risk heuristics (maybe based on current metrics) and error taxonomies (error type) and per-tenant service-levels (tier) to adjust retries. That's what we do.
Now we must produce final answer with explanation and code. The user didn't specify language, but we can choose Python. Could also be Go, but Python is fine.
We'll produce:
- Overview
- Design
- Data model
- Algorithm
- Implementation (code)
- Example usage
- Considerations and extensions
We'll also talk about thread-safety, scalability, potential improvements.
Make sure to include proper imports and class definitions.
We'll also mention that the orchestrator is per-request because it recalculates policy after each failure using current metrics.
Now potential issues: if many requests from same tenant are happening concurrently, they all see the same metrics and may all decide to retry, causing more load. That's a known retry storm problem. Could incorporate jitter or coordinated backoff (e.g., using a distributed token). But for now, our jitter is per request.
We could also add a circuit breaker that trips when failure rate high, and then orchestrator would fail fast for a cooldown.
But we can mention as enhancements.
Now produce final answer.
Make sure code is clear, with docstrings.
We'll also define HttpError class:
class HttpError(Exception):
def init(self, status_code, message):
self.status_code = status_code
self.message = message
super().init(f"{status_code}: {message}")
Now final.
Per‑Request Adaptive Retry Orchestrator
Overview
A retry orchestrator decides if, when, and how many times to retry a failed request. A per‑request adaptive orchestrator makes these decisions based on the context of the individual request (tenant, service, error type) and on dynamic risk indicators (current error rates, tenant SLA, error taxonomy). This approach:
- Improves success rates for critical or high‑value tenants.
- Reduces overload on unhealthy back‑ends by backing off early when risk is high.
- Respects SLAs by applying different retry limits for different service levels.
Below we present a reference design and a Python implementation that combines:
- Error taxonomy – classifies failures into transient, permanent, rate‑limited, etc.
- Risk heuristics – evaluates current system health (e.g., recent failure rate) and tenant importance.
- Per‑tenant service‑levels – provides baseline retry limits and back‑off parameters for each tenant tier (Gold, Silver, Bronze).
Design
1. Core Components
| Component | Responsibility |
|---|
TenantProvider | Returns configuration (tier, base retry limits, back‑off settings) for a given tenant_id. |
ErrorTaxonomy | Maps an exception or HTTP status to an ErrorCategory (TRANSIENT, PERMANENT, RATE_LIMITED, UNKNOWN). |
MetricsCollector | Tracks recent successes/failures per service (sliding window) to compute current error rates. |
RiskHeuristic | Combines metrics (service_error_rate) with tenant tier to produce a risk score in [0,1]. |
AdaptiveRetryOrchestrator | Wraps a user‑provided request_func, applying retry logic that adapts on each failure. |
2. Workflow (per request)
-
Pre‑call
- Fetch tenant configuration (
base_max_retries, initial_delay, backoff_factor).
- Initialise retry state (
attempt = 0).
-
Attempt
- Call
request_func.
- On success → record success, return response.
- On exception:
- Record failure in metrics.
- Classify error via
ErrorTaxonomy. If PERMANENT, abort immediately.
- Compute current risk score based on latest metrics and tenant tier.
- Compute effective max attempts:
1 + floor((base_max-1) * (1 - risk)).
(Risk = 1 ⇒ only 1 attempt; Risk = 0 ⇒ full base max.)
- If current
attempt ≥ effective max → abort.
- Compute back‑off delay:
initial_delay * (backoff_factor ** (attempt-1)) with jitter.
- Sleep → next attempt.
-
Post‑loop
- If all retries exhausted, raise the last exception (or a custom
RetryFailedError).
The orchestrator re‑evaluates risk after every failure, allowing it to shrink the retry budget in real‑time when the service degrades.
3. Data Model
TenantConfig
tier : Enum (GOLD, SILVER, BRONZE)
base_max_retries: int (total attempts, ≥1)
initial_delay : float (seconds)
backoff_factor : float (exponential multiplier)
ErrorCategory (Enum)
TRANSIENT, PERMANENT, RATE_LIMITED, UNKNOWN
ServiceMetrics (per service name)
failures: list[timestamp] # sliding window (e.g., 60 s)
(successes optional)
Implementation (Python)
The following code is a self‑contained, thread‑safe reference implementation.
import time
import random
import threading
from enum import Enum, auto
from typing import Callable, Any, Dict, List
# ----------------------------------------------------------------------
# Exceptions & Taxonomy
# ----------------------------------------------------------------------
class HttpError(Exception):
"""Raised for HTTP errors with a status code."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f"{status_code}: {message}")
class ErrorCategory(Enum):
TRANSIENT = auto()
PERMANENT = auto()
RATE_LIMITED = auto()
UNKNOWN = auto()
class ErrorTaxonomy:
"""Maps status codes to error categories."""
def __init__(self):
# Basic mapping – extend as needed.
self._map = {
408: ErrorCategory.TRANSIENT, # Request Timeout
429: ErrorCategory.RATE_LIMITED,
500: ErrorCategory.TRANSIENT, # Internal Server Error
502: ErrorCategory.TRANSIENT, # Bad Gateway
503: ErrorCategory.TRANSIENT, # Service Unavailable
504: ErrorCategory.TRANSIENT, # Gateway Timeout
# Client errors that are generally permanent (adjust per domain)
400: ErrorCategory.PERMANENT,
401: ErrorCategory.PERMANENT,
403: ErrorCategory.PERMANENT,
404: ErrorCategory.PERMANENT,
405: ErrorCategory.PERMANENT,
409: ErrorCategory.PERMANENT,
422: ErrorCategory.PERMANENT,
}
def classify(self, status_code: int) -> ErrorCategory:
return self._map.get(status_code, ErrorCategory.UNKNOWN)
# ----------------------------------------------------------------------
# Tenant Configuration
# ----------------------------------------------------------------------
class TenantConfig:
"""Retry configuration associated with a tenant tier."""
def __init__(
self,
tier: str,
base_max_retries: int = 3,
initial_delay: float = 0.1,
backoff_factor: float = 2.0
):
self.tier = tier.upper()
self.base_max_retries = max(1, base_max_retries)
self.initial_delay = initial_delay
self.backoff_factor = backoff_factor
@staticmethod
def default() -> 'TenantConfig':
return TenantConfig(tier='BRONZE', base_max_retries=2)
class TenantProvider:
"""Simple provider that returns TenantConfig from a dict."""
def __init__(self, configs: Dict[str, TenantConfig]):
self._configs = configs
def get_config(self, tenant_id: str) -> TenantConfig:
return self._configs.get(tenant_id, TenantConfig.default())
# ----------------------------------------------------------------------
# Metrics Collection
# ----------------------------------------------------------------------
class ServiceMetrics:
"""Thread‑safe metrics for a single service (sliding window)."""
def __init__(self, window_seconds: float = 60.0):
self._window = window_seconds
self._failures: List[float] = [] # timestamps
self._lock = threading.Lock()
def record_failure(self) -> None:
now = time.time()
with self._lock:
self._failures.append(now)
self._prune(now)
def record_success(self) -> None:
# successes not needed for current risk heuristic, but could be stored.
pass
def failures_last_60s(self) -> int:
now = time.time()
with self._lock:
self._prune(now)
return len(self._failures)
def _prune(self, now: float) -> None:
cutoff = now - self._window
# Keep only failures within the sliding window.
while self._failures and self._failures[0] < cutoff:
self._failures.pop(0)
class MetricsCollector:
"""Global registry of ServiceMetrics per service name."""
def __init__(self):
self._services: Dict[str, ServiceMetrics] = {}
self._lock = threading.Lock()
def _get_metrics(self, service_name: str) -> ServiceMetrics:
with self._lock:
if service_name not in self._services:
self._services[service_name] = ServiceMetrics()
return self._services[service_name]
def record_failure(self, service_name: str) -> None:
self._get_metrics(service_name).record_failure()
def record_success(self, service_name: str) -> None:
self._get_metrics(service_name).record_success()
def failures_last_60s(self, service_name: str) -> int:
return self._get_metrics(service_name).failures_last_60s()
# ----------------------------------------------------------------------
# Risk Heuristic
# ----------------------------------------------------------------------
class RiskHeuristic:
"""Computes a risk score in [0,1] given service error rate and tenant tier."""
def __init__(self):
# Thresholds for failure count in the last 60s that map to risk levels.
self._failure_threshold_low = 5
self._failure_threshold_high = 20
self._tier_factors = {
'GOLD': 0.5,
'SILVER': 0.75,
'BRONZE': 1.0
}
def calculate(self, service_name: str, tier: str, metrics: MetricsCollector) -> float:
failures = metrics.failures_last_60s(service_name)
# Base risk grows linearly from 0 to 1 between thresholds.
if failures <= self._failure_threshold_low:
base_risk = 0.0
elif failures >= self._failure_threshold_high:
base_risk = 1.0
else:
# Linear interpolation
base_risk = (failures - self._failure_threshold_low) / (
self._failure_threshold_high - self._failure_threshold_low
)
tier_factor = self._tier_factors.get(tier.upper(), 1.0)
risk = base_risk * tier_factor
return min(risk, 1.0)
# ----------------------------------------------------------------------
# Adaptive Retry Orchestrator
# ----------------------------------------------------------------------
class AdaptiveRetryOrchestrator:
"""
Wraps a request function with per‑request adaptive retry logic.
The orchestrator uses:
- Tenant configuration (base limits)
- Error taxonomy (to classify exceptions)
- Real‑time metrics (to compute risk)
"""
def __init__(
self,
tenant_provider: TenantProvider,
metrics_collector: MetricsCollector,
error_taxonomy: ErrorTaxonomy,
risk_heuristic: RiskHeuristic,
clock: Callable[[], float] = time.time,
sleeper: Callable[[float], None] = time.sleep
):
self._tenant_provider = tenant_provider
self._metrics = metrics_collector
self._taxonomy = error_taxonomy
self._risk_heuristic = risk_heuristic
self._clock = clock
self._sleep = sleeper
self._random = random.Random() # independent RNG
def execute(
self,
tenant_id: str,
service_name: str,
request_func: Callable[..., Any],
*args,
**kwargs
) -> Any:
"""
Execute request_func with adaptive retry.
Parameters:
tenant_id – identifier of the tenant (used to fetch config).
service_name – logical name of the service (used for metrics).
request_func – callable that performs the actual request.
Returns:
The result of request_func if successful.
Raises:
The last exception if all attempts fail.
"""
config = self._tenant_provider.get_config(tenant_id)
attempt = 0
last_exc = None
while True:
attempt += 1
try:
response = request_func(*args, **kwargs)
# Success
self._metrics.record_success(service_name)
return response
except HttpError as http_err:
last_exc = http_err
self._metrics.record_failure(service_name)
category = self._taxonomy.classify(http_err.status_code)
if category == ErrorCategory.PERMANENT:
break # do not retry
except Exception as exc:
# Treat any other exception as transient (network, timeout, etc.)
last_exc = exc
self._metrics.record_failure(service_name)
# No classification, assume transient.
# Compute effective max attempts based on current risk
risk = self._risk_heuristic.calculate(service_name, config.tier, self._metrics)
max_attempts = self._compute_max_attempts(config.base_max_retries, risk)
if attempt >= max_attempts:
break
# Compute backoff before next attempt
delay = self._compute_backoff(attempt, config.initial_delay, config.backoff_factor)
self._sleep(delay)
# Exhausted retries or permanent error
raise last_exc
def _compute_max_attempts(self, base_max: int, risk: float) -> int:
"""
Adjust the maximum number of attempts based on risk.
Guarantees at least 1 attempt.
Formula: 1 + floor((base_max-1) * (1 - risk))
"""
if base_max <= 1:
return 1
retries = int((base_max - 1) * (1 - risk))
return 1 + retries
def _compute_backoff(self, attempt: int, initial: float, factor: float) -> float:
"""
Exponential backoff with jitter.
`attempt` is the current attempt number (1-indexed). The delay is for the next retry,
i.e., based on `retry_num = attempt - 1`.
"""
retry_num = attempt - 1
delay = initial * (factor ** retry_num)
# Add up to 10% jitter
jitter = self._random.uniform(0, delay * 0.1)
return delay + jitter
# ----------------------------------------------------------------------
# Example Usage
# ----------------------------------------------------------------------
if __name__ == "__main__":
# Mock HTTP error and request function
class MockHttpError(HttpError):
pass
def flaky_request(service: str, fail_rate: float = 0.3, status_code: int = 500):
"""A pretend request that fails randomly."""
if random.random() < fail_rate:
raise MockHttpError(status_code, "Service temporarily unavailable")
return f"Success from {service}"
# Setup tenants
tenant_configs = {
"tenant_gold": TenantConfig(tier='GOLD', base_max_retries=5, initial_delay=0.2),
"tenant_silver": TenantConfig(tier='SILVER', base_max_retries=3, initial_delay=0.1),
"tenant_bronze": TenantConfig(tier='BRONZE', base_max_retries=2, initial_delay=0.05),
}
tenant_provider = TenantProvider(tenant_configs)
# Shared infrastructure
metrics_collector = MetricsCollector()
error_taxonomy = ErrorTaxonomy()
risk_heuristic = RiskHeuristic()
orchestrator = AdaptiveRetryOrchestrator(
tenant_provider,
metrics_collector,
error_taxonomy,
risk_heuristic
)
# Simulate 10 requests for a gold tenant
print("=== Gold Tenant ===")
for i in range(10):
try:
# The request function is a closure capturing service name and fail rate
result = orchestrator.execute(
tenant_id="tenant_gold",
service_name="order-service",
request_func=lambda: flaky_request("order-service", fail_rate=0.4, status_code=503)
)
print(f"Request {i+1}: {result}")
except Exception as e:
print(f"Request {i+1} failed after retries: {e}")
# Show current metrics
print("\nMetrics (failures in last 60s for order-service):",
metrics_collector.failures_last_60s("order-service"))
Explanation of the Example
- Three tenants with different tiers and initial retry limits.
- A mock
flaky_request that fails with probability 0.4 and returns a 503 (transient).
- The orchestrator will:
- Retry up to 5 times for Gold, but risk may shrink that number if many failures accumulate.
- Record each failure in
MetricsCollector.
- After each failure, recompute risk; if the recent failure count is high, the number of remaining attempts is reduced.
- The example prints the outcome of each request.
Discussion & Extensions
1. Risk Heuristics – More Signals
The current heuristic uses only recent failure count. Real‑world systems may incorporate:
- System load (CPU, queue depth).
- Latency trends (p99 latency increase).
- Circuit breaker state (open/half‑open).
- Tenant priority (beyond tier, e.g., contractual penalties).
- Time of day (maintenance windows).
These can be combined via a weighted sum or a machine‑learning model predicting the probability of a successful retry.
2. Error Taxonomy – richer classification
- Map specific exception types (e.g.,
TimeoutError, ConnectionRefused) to categories.
- Use content of the response (e.g., error codes in JSON body).
- Support dynamic updates via a configuration service.
3. Mitigating Retry Storms
Multiple concurrent requests for the same service may all retry simultaneously, worsening overload. Strategies:
- Jitter (already included) to spread retries.
- Token bucket per service that limits the rate of retry attempts.
- Exponential back‑off with a common base derived from the service’s health (e.g., increase base delay when error rate high).
- Coordinated retries using a distributed lock or a shared “retry after” header.
4. Observability
- Emit metrics:
retry_attempts, retry_outcome (success/failure), risk_score.
- Add tracing (e.g., OpenTelemetry) with tags for tenant, service, and retry count.
- Log decisions at debug level for audit.
5. Persistence & Scalability
- In‑memory metrics are fine for a single process. For a distributed system:
- Use a shared time‑series database or Redis to store sliding‑window counts.
- Pull metrics via an async client (non‑blocking) or delegate risk computation to a sidecar.
- Ensure the orchestrator is lightweight: core logic should be in‑process; remote calls should be avoided during request handling.
6. Circuit Breaker Integration
The orchestrator can be combined with a circuit breaker that trips when the error rate exceeds a threshold. When open, the orchestrator would fail fast without even trying, providing a back‑pressure mechanism.
7. Configuration Management
Tenant configuration (tiers, limits) can be stored in a database and refreshed periodically, allowing on‑the‑fly policy tuning without restarts.
Summary
The provided AdaptiveRetryOrchestrator demonstrates a practical, per‑request adaptive retry mechanism that:
- Classifies errors to avoid futile retries on permanent failures.
- Monitors real‑time service health to gauge risk.
- Applies tenant‑specific retry budgets that shrink as risk grows.
- Uses exponential back‑off with jitter to avoid spikes.
- Is thread‑safe and readily extensible.
This design balances reliability and resilience while respecting the diverse service‑level expectations of multi‑tenant applications.