The user wants a resilience layer for third-party APIs.
The key requirements are:
Bulkheads: Isolate failures so one slow/failing API doesn't bring down the whole system.
Adaptive Timeouts: Timeouts that adjust based on the API's current performance (e.g., if it gets slow, timeout gets shorter; if it recovers, it extends).
Synthetic Fallback Responses: Returning a mock/cached/default response when the actual API fails.
I need to design a Python class (or a set of classes) that wraps an API client and adds these features. Python's asyncio is the best fit for modern, high-performance API handling, but synchronous code is easier to demonstrate simply. However, resilience patterns often benefit greatly from async (especially timeouts and bulkheads). I will use asyncio for a robust solution.
Architecture:
ResilientClient: The main wrapper. It takes the actual API client or a function to call.
CircuitBreaker (implied/needed): While "Bulkheads" were asked for, usually Bulkheads go hand-in-hand with Circuit Breakers, but I must stick to the requested features. I will focus on the Bulkhead (semaphore/concurrency limit).
AdaptiveTimeout: Needs a mechanism to track latency and calculate the next timeout. A simple exponential moving average or TCP-like estimation works.
TokenBucket: A standard algorithm. Needs to be keyed by tenant_id.
FallbackStrategy: A way to define what to return if things go wrong.
Component Breakdown & Implementation Details:
Token Bucket (Per-Tenant):
Class TokenBucket.
Method consume(tokens=1).
A manager class RateLimiter that holds a dict of {tenant_id: TokenBucket}.
Needs to handle thread-safety (or async-safety) and cleanup of old buckets (optional but good practice, maybe skip for brevity).
Bulkhead:
Limits concurrent executions.
asyncio.Semaphore is perfect for this.
Adaptive Timeout:
This is tricky. I'll implement a simplified version.
Track recent response times.
If current_time > avg * factor, timeout.
Or simpler: Adjust a timeout variable.
Let's use a basic TCP-reno style logic or just "latency percentile".
Decision: I'll create an AdaptiveTimeout class that tracks the smoothed RTT (Round Trip Time). Timeout = SRTT + margin.
Synthetic Fallback:
A registry of functions or static values.
Keyed by maybe the API endpoint name or just a generic fallback for the client.
Putting it together:
I will create a Python module using asyncio.
TokenBucket: Logic to refill tokens based on time delta.
ResilienceLayer: The main class.
Usage: A context manager or a decorator. A decorator wrapper @resilient is elegant, but an instance wrapper is more explicit for dependency injection. Let's go with an instance wrapper ResilientClient.
Drafting the Code Structure:
python
import asyncio
import time
from dataclasses import dataclass, field
from typing import Dict, Callable, Any, Optional
# 1. Token Bucket
class TokenBucket:
def __init__(self, rate, capacity): ...
def consume(self): ...
# 2. Rate Limiter Manager (Per Tenant)
class TenantRateLimiter:
def __init__(self, rate, capacity):
self.buckets = {} # tenant_id -> TokenBucket
def acquire(self, tenant_id): ...
# 3. Adaptive Timeout
class AdaptiveTimeout:
def __init__(self):
self.min_timeout = 0.1
self.max_timeout = 5.0
self.current_timeout = 1.0
# stats to track latency
def record_latency(self, latency): ...
def get_timeout(self): ...
# 4. Bulkhead
# Just a Semaphore passed in, or managed inside the client.
# 5. Fallbacks
# A dictionary mapping functions/endpoints to static data or generators.
# 6. The Wrapper
class ResilientApiClient:
def __init__(self, tenant_limiter, bulkhead_limit, fallback_handler):
self.semaphore = asyncio.Semaphore(bulkhead_limit)
self.limiter = tenant_limiter
self.fallback = fallback_handler
self.adaptive_timeouts = {} # per-endpoint adaptive timeouts? Or global? Let's do per-endpoint.
async def execute(self, endpoint_name, tenant_id, call_func, *args, **kwargs):
# 1. Rate Limit
if not self.limiter.acquire(tenant_id):
return self.fallback.get(endpoint_name, tenant_id) # Or raise 429
# 2. Adaptive Timeout
timeout_manager = self.get_timeout_manager(endpoint_name)
current_timeout = timeout_manager.get_timeout()
# 3. Bulkhead
async with self.semaphore:
try:
start = time.time()
# Run with timeout
result = await asyncio.wait_for(call_func(*args, **kwargs), timeout=current_timeout)
latency = time.time() - start
timeout_manager.record_success(latency)
return result
except Exception as e:
timeout_manager.record_failure()
return self.fallback.get(endpoint_name)
Refining the Adaptive Timeout:
It shouldn't just be "timeout increases on failure". It should react to slowness.
If requests fail (timeout), we might back off the timeout (increase it slightly or just rely on the bulkhead to stop spamming). Usually, if timeouts happen, the Circuit Breaker opens. Here we are tuning the wait duration.
Let's stick to a simple EWMA (Exponential Weighted Moving Average) for latency.
timeout = ewma_latency + deviation.
Refining Fallbacks:
The user asked for "synthetic" fallbacks. This implies generating data that looks real but isn't (e.g., for "Search" API returning empty list, or "Price" API returning last known cached price). I'll implement a simple registry.
Code Structure for Final Output:
Imports: asyncio, time, typing.
TokenBucket Class: Standard implementation.
TenantRateLimiter: Manages buckets per tenant.
AdaptiveTimeoutManager: Tracks latency and calculates timeout.
FallbackGenerator: Handles mock data.
ResilienceProxy: The main class that ties it all together.
What if tenant_id is missing? Default to global bucket.
Thread safety: Since this is asyncio, we need to be careful with shared state (timeouts, buckets) being modified while the event loop is yielding. Regular dict updates are atomic in Python for single ops, but compound logic (read-modify-write) in TokenBucket needs to ensure it's not yielding during the logic if not thread-safe, or just use asyncio.Lock. Actually, simple arithmetic in Python is atomic for GIL, but await statements break atomicity. I'll ensure TokenBucket logic doesn't yield.
Implementation Plan:
I will provide a complete, runnable Python script using asyncio that defines these components and simulates a scenario.
TokenBucket: Uses time.monotonic().
TenantRateLimiter: Stores buckets in a dict.
AdaptiveTimeout: Uses EWMA.
ResilienceLayer: The wrapper.
Demo:
Define a mock "External API".
Set up the layer: 3 concurrent calls (bulkhead), 2 req/sec per tenant.
Run a simulation where the API gets slow/fails, and show timeouts adapting + fallbacks returning.
Let's refine the Adaptive Timeout logic.
If the request times out, we don't know the real latency.
If it fails immediately, latency is low.
Logic:
On success: update_rtt(latency).
On timeout/failure: We could optionally increase the "penalty" or "safety margin" to be more conservative, but standard adaptive timeouts usually just track the window of successful RTTs. If it times out, it's a failure. I'll keep it simple: Track successful RTTs to set the expectation.
Let's start generating the response.
This solution implements a comprehensive resilience layer in Python using asyncio. It combines four critical patterns:
Per-Tenant Token Buckets: Ensures fair usage and prevents "noisy neighbor" problems where one tenant consumes all API capacity.
Bulkheads (Semaphores): Limits concurrent connections to the third-party API to prevent resource exhaustion in your application.
Adaptive Timeouts: Uses Exponential Moving Average (EMA) to track API latency. If the API slows down, the timeout tightens to fail fast; if it recovers, the timeout relaxes.
Synthetic Fallbacks: Returns a statically typed or generated response when the API fails, ensuring the calling system remains stable.
Python Implementation
python
Breakdown of Logic
Token Bucket (RateLimiter, TokenBucket):
Every tenant gets their own TokenBucket.
Before entering the bulkhead, wait_for_token checks if tokens exist.
If a tenant exceeds their rate (e.g., Tenant_C spams requests), they are put to sleep (asynchronously) until tokens refill. This protects the API quota and isolates Tenant_C's impact on others.
Bulkhead (asyncio.Semaphore):
The async with self.bulkhead: block ensures that globally, no more than max_concurrent_calls are active simultaneously.
If the third-party API is slow, the semaphore slots will remain occupied, preventing new requests from starting and protecting your application's memory/thread resources.
Adaptive Timeout (AdaptiveTimeoutController):
We track the duration of successful calls.
We calculate an Exponential Moving Average (EMA). This smooths out spikes but reacts to trends.
The timeout is set to EMA * 1.5.
Behavior: If the API usually takes 200ms, the timeout might be 300ms. If the API suddenly slows to 2000ms, the first request times out, but subsequent successful requests (if any) will drive the timeout up automatically. Conversely, if it speeds up, the timeout tightens, freeing up resources faster.
Synthetic Fallbacks:
If unstable_external_api raises an exception or times out, the except block catches it.
It looks up get_user in the registry.
It returns a static dictionary {"status": "degraded", ...}.
The calling application (simulate_tenant) receives a valid dictionary and continues operating, albeit in a degraded mode, rather than crashing.
import asyncio
import time
import random
from dataclasses import dataclass, field
from typing import Dict, Callable, Any, Optional
from collections import deque
import math
# ==========================================
# 1. Data Structures & Configuration
# ==========================================
@dataclass
class ApiConfig:
"""Configuration for the resilience layer."""
max_concurrent_calls: int = 10 # Bulkhead limit
tokens_per_second: float = 5.0 # Token bucket refill rate (per tenant)
bucket_capacity: int = 10 # Token bucket max size (per tenant)
min_timeout_ms: int = 200 # Floor for adaptive timeouts
max_timeout_ms: int = 5000 # Ceiling for adaptive timeouts
initial_timeout_ms: int = 1000 # Starting timeout
latency_sensitivity: float = 0.2 # EMA weight (0.0-1.0) for adaptive calc
# ==========================================
# 2. Token Bucket (Rate Limiting)
# ==========================================
class TokenBucket:
"""
Standard Token Bucket algorithm.
Threadsafety: Designed for asyncio (single-threaded concurrency).
"""
def __init__(self, rate: float, capacity: int):
self.rate = rate # Tokens added per second
self.capacity = capacity # Max tokens
self.tokens = capacity # Current tokens
self.last_update = time.monotonic()
def acquire(self, tokens: int = 1) -> bool:
now = time.monotonic()
elapsed = now - self.last_update
# Refill tokens based on time elapsed
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.last_update = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
class RateLimiter:
"""Manages token buckets per tenant."""
def __init__(self, config: ApiConfig):
self.config = config
self.buckets: Dict[str, TokenBucket] = {}
def _get_bucket(self, tenant_id: str) -> TokenBucket:
if tenant_id not in self.buckets:
self.buckets[tenant_id] = TokenBucket(
self.config.tokens_per_second,
self.config.bucket_capacity
)
return self.buckets[tenant_id]
async def wait_for_token(self, tenant_id: str):
"""
Blocks asynchronously until a token is available.
In a real prod system, you might want a max wait time here.
"""
bucket = self._get_bucket(tenant_id)
# Simple spin-lock (yielding control to event loop)
while not bucket.acquire():
await asyncio.sleep(0.1) # Wait briefly before retrying
# ==========================================
# 3. Adaptive Timeout Logic
# ==========================================
class AdaptiveTimeoutController:
"""
Adjusts timeouts based on the moving average of recent request latencies.
Uses Exponential Moving Average (EMA) to react to changes.
"""
def __init__(self, config: ApiConfig):
self.config = config
self.current_timeout_ms = config.initial_timeout_ms
self.ema_latency_ms = float(config.initial_timeout_ms)
# History to calculate variance (optional, simplified here to just EMA)
def record_latency(self, latency_ms: float):
# Update EMA: EMA = (Alpha * New) + ((1 - Alpha) * Old)
self.ema_latency_ms = (self.config.latency_sensitivity * latency_ms) + \
((1 - self.config.latency_sensitivity) * self.ema_latency_ms)
# Set timeout to be slightly higher than average latency (e.g., Mean + 2*StdDev simplified to Mean * 1.5)
calculated_timeout = self.ema_latency_ms * 1.5
# Clamp values
self.current_timeout_ms = max(
self.config.min_timeout_ms,
min(self.config.max_timeout_ms, calculated_timeout)
)
def get_timeout(self) -> float:
"""Returns timeout in seconds."""
return self.current_timeout_ms / 1000.0
# ==========================================
# 4. Resilience Layer Core
# ==========================================
class ResilienceLayer:
def __init__(self, config: ApiConfig):
self.config = config
self.rate_limiter = RateLimiter(config)
self.timeout_controller = AdaptiveTimeoutController(config)
# Bulkhead: Semaphore to limit concurrent outgoing connections
self.bulkhead = asyncio.Semaphore(config.max_concurrent_calls)
# Registry for synthetic fallbacks (Key: endpoint_name)
self.fallback_registry: Dict[str, Callable[[], Any]] = {}
def register_fallback(self, endpoint_name: str, generator: Callable[[], Any]):
"""Register a function that returns synthetic data for a specific endpoint."""
self.fallback_registry[endpoint_name] = generator
async def execute(self,
tenant_id: str,
endpoint_name: str,
api_call: Callable[[], Any],
*args, **kwargs) -> Any:
"""
Executes the API call wrapped in resilience logic.
"""
# 1. Token Bucket (Rate Limiting)
# Wait until this tenant has capacity
await self.rate_limiter.wait_for_token(tenant_id)
# 2. Bulkhead (Concurrency Limit)
# Wait until a global connection slot is free
async with self.bulkhead:
# 3. Adaptive Timeout Execution
current_timeout = self.timeout_controller.get_timeout()
try:
start_time = time.monotonic()
# Execute the actual call with a timeout
# We assume api_call is an async function
result = await asyncio.wait_for(
api_call(*args, **kwargs),
timeout=current_timeout
)
# Record success latency
latency_ms = (time.monotonic() - start_time) * 1000
self.timeout_controller.record_latency(latency_ms)
return result
except (asyncio.TimeoutError, Exception) as e:
# 4. Fallback Logic
print(f"[WARN] Call to {endpoint_name} failed for {tenant_id}: {type(e).__name__}. Invoking fallback.")
# If it timed out, we might want to penalize future timeouts
if isinstance(e, asyncio.TimeoutError):
# Record the timeout duration as the 'latency' to force the timeout to grow
self.timeout_controller.record_latency(current_timeout * 1000)
# Return synthetic response
if endpoint_name in self.fallback_registry:
return self.fallback_registry[endpoint_name]()
# If no fallback is registered, re-raise critical error or return generic error
raise RuntimeError(f"Critical failure in {endpoint_name} and no fallback available.")
# ==========================================
# 5. Usage Example
# ==========================================
# Mock External API
async def unstable_external_api(user_id):
# Simulate latency (50ms to 300ms normally)
latency = random.uniform(0.05, 0.3)
# Simulate occasional massive slowdowns
if random.random() < 0.1:
await asyncio.sleep(1.0) # Trigger timeout likely
else:
await asyncio.sleep(latency)
# Simulate occasional errors
if random.random() < 0.1:
raise ConnectionError("Network unreachable")
return {"status": "success", "user_id": user_id}
# Synthetic Fallback Generator
def get_user_fallback():
print(" -> Returning synthetic user profile.")
return {
"status": "degraded",
"user_id": "unknown",
"name": "Guest User",
"features": ["basic_access"]
}
async def main():
config = ApiConfig(
max_concurrent_calls=5,
tokens_per_second=2.0 # 2 requests per second per tenant
)
layer = ResilienceLayer(config)
layer.register_fallback("get_user", get_user_fallback)
async def simulate_tenant(tenant_id, requests=10):
for i in range(requests):
try:
print(f"[{tenant_id}] Request {i+1}: Sending...")
res = await layer.execute(
tenant_id=tenant_id,
endpoint_name="get_user",
api_call=unstable_external_api,
user_id=f"{tenant_id}-{i}"
)
timeout = layer.timeout_controller.get_timeout()
print(f"[{tenant_id}] Request {i+1}: Success. Adaptive Timeout: {timeout:.2f}s")
except Exception as e:
print(f"[{tenant_id}] Request {i+1}: Hard Failure - {e}")
# Small delay between user actions
await asyncio.sleep(random.uniform(0.1, 0.5))
# Simulate multiple tenants hitting the system at once
await asyncio.gather(
simulate_tenant("Tenant_A", 5),
simulate_tenant("Tenant_B", 5),
simulate_tenant("Tenant_C", 5) # Tenant C is a "noisy neighbor"
)
if __name__ == "__main__":
asyncio.run(main())