We are going to design a resilience layer for third-party APIs. The requirements are:
- Bulkheads: Isolate failures in one part of the system from affecting others. We can use thread pools or semaphores to limit concurrent calls to different services or tenants.
- Adaptive timeouts: Dynamically adjust timeouts based on past response times.
- Token buckets per-tenant: Rate limit each tenant (API client) using a token bucket algorithm.
- Synthetic fallback responses: When a call fails, return a pre-defined (synthetic) response.
We'll design a class ResilienceLayer that wraps around a function that makes an API call.
Steps:
-
We'll have a configuration per tenant (or per endpoint) that includes:
- bulkhead: max concurrent calls
- token bucket: capacity and refill rate (tokens per second)
- base timeout and how to adapt it (maybe exponential moving average of response times)
- fallback response (synthetic)
-
We'll use:
- A semaphore for bulkhead (to limit concurrent calls).
- A token bucket for rate limiting (per tenant). We can use a leaky bucket or token bucket with a fixed refill rate.
- For adaptive timeout: we'll keep a history of response times (or an exponentially weighted moving average) for each tenant/endpoint and set the timeout accordingly.
- Fallback: if the call fails (timeout, exception, etc.) and we have a fallback, return the fallback.
-
We'll design the ResilienceLayer to be used as a decorator or a wrapper around the callable that does the API request.
-
We need to handle:
- Bulkhead: if the semaphore cannot be acquired, we reject immediately (or we can queue? but typically bulkhead rejects to avoid overloading).
- Token bucket: if no token, reject (or wait? but we want to limit rate, so we can wait until a token is available or reject? We'll do a non-blocking try to acquire, so we reject if no token).
- Timeout: we set a timeout for the call. We can use
asyncio.wait_for if async, or a thread with timeout if sync. But note: the adaptive timeout is the total time we allow for the call.
-
We'll assume we are in an async environment because most API calls are I/O bound and we want to avoid blocking threads.
-
We'll use asyncio and asyncio.Semaphore for bulkhead, and aiolimiter for token bucket? But to avoid external dependencies, we can implement a simple token bucket with asyncio.
However, note: the requirement says "per-tenant", so we need to maintain state per tenant.
Let's design:
For each tenant (or for each combination of tenant and endpoint) we have:
- bulkhead_semaphore: asyncio.Semaphore(max_concurrent)
- token_bucket: we can use a fixed window or a token bucket. We'll implement a token bucket that refills at a constant rate and has a maximum capacity.
- adaptive_timeout: we'll track the average response time and set the timeout to, say, 2*average or something. But note: we don't want to set the timeout too high because we want to fail fast.
We'll create a class TenantResilienceConfig that holds:
- max_concurrent: int
- rate_limit_capacity: int (burst)
- rate_limit_refill_rate: float (tokens per second)
- base_timeout: float (initial timeout in seconds)
- fallback: any (the synthetic response)
And we'll have:
- current_timeout: float (updated adaptively)
For the token bucket, we can have:
- tokens: float (current tokens)
- last_refill: float (timestamp of last refill)
We'll need to update the token bucket on each call and also periodically? But since we are in async, we can update on each call and refill based on the time passed.
We'll create a class TokenBucket:
def init(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate # tokens per second
self.tokens = capacity
self.last_refill = time.monotonic()
async def consume(self, tokens=1):
now = time.monotonic()
# refill
delta = now - self.last_refill
self.tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
self.last_refill = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
else:
return False
But note: we are in async and multiple tasks might call consume at the same time. We need a lock.
Alternatively, we can use asyncio.Lock to protect the token bucket.
However, we want to avoid blocking for too long. We can do:
async def consume(self, tokens=1):
async with self.lock:
now = time.monotonic()
delta = now - self.last_refill
self.tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
self.last_refill = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
else:
return False
But if we don't have enough tokens, we return False and the caller can decide what to do (reject). We don't wait for tokens to refill because we want to reject if rate limit exceeded.
For adaptive timeout:
We'll keep a list of recent response times (or an exponentially weighted moving average). Let's do EWMA:
new_avg = alpha * last_response_time + (1-alpha) * old_avg
Then set timeout = max(base_timeout, 2 * new_avg) or something.
But note: we are only updating when the call succeeds? Or also when it fails? We should only update on success because a failure might be due to timeout and we don't know the actual time.
We can update the average only on success, and set the timeout to, say, 2 * average + some buffer.
However, if we are using a fallback, then the call might be considered a success? We don't want to update the average with the fallback time because the fallback is fast. But the call to the API failed and we used fallback. So we should not update the average with the fallback response time.
So we update the average only when we get a response from the API (success or failure that is not a timeout? Actually, if it's a timeout, we don't have a response time? We set a timeout and it times out, so we know the time it took is at least the timeout? We can record the timeout as the response time? That might be misleading because it's an upper bound.
Alternatively, we can record the time from when we start the call until we get a response (or timeout). Then if we get a response, we record that time. If we timeout, we record the timeout value? But then the average will be inflated by timeouts.
Maybe we should only update on successful responses (i.e., we got a response from the API within the timeout). Then the average is based on successful calls.
For timeout, we set the timeout to, say, 2 * average + 1 second.
We'll keep:
self.response_times = deque(maxlen=100) # last 100 successful response times
then average = sum(self.response_times) / len(self.response_times)
But we want to adapt quickly? Maybe use EWMA.
Let's do:
self.ewma = None
self.alpha = 0.1 # smoothing factor
On success:
if self.ewma is None:
self.ewma = response_time
else:
self.ewma = self.alpha * response_time + (1-self.alpha) * self.ewma
Then timeout = max(self.base_timeout, 2 * self.ewma)
But note: we are using the same timeout for all calls? And we are updating per tenant? Yes.
-
We'll have a dictionary of tenant_id -> TenantResilienceConfig (which includes the semaphore, token bucket, and adaptive timeout state).
-
We'll create a class ResilienceLayer:
def init(self, tenant_configs: dict):
self.tenant_configs = tenant_configs # tenant_id -> TenantResilienceConfig
async def call(self, tenant_id, api_call_func, *args, **kwargs):
config = self.tenant_configs.get(tenant_id)
if config is None:
raise ValueError(f"No config for tenant {tenant_id}")
# 1. Bulkhead: acquire semaphore
try:
async with config.bulkhead_semaphore:
# 2. Token bucket: try to consume a token
if not await config.token_bucket.consume():
# rate limit exceeded
if config.fallback is not None:
return config.fallback
else:
raise RateLimitException(f"Rate limit exceeded for tenant {tenant_id}")
# 3. Adaptive timeout: get current timeout
timeout = config.current_timeout
# 4. Make the call with timeout
try:
start = time.monotonic()
result = await asyncio.wait_for(api_call_func(*args, **kwargs), timeout=timeout)
elapsed = time.monotonic() - start
# Update adaptive timeout with this successful response time
config.update_response_time(elapsed)
return result
except asyncio.TimeoutError:
# The call timed out
if config.fallback is not None:
return config.fallback
else:
raise
except Exception as e:
# If we get an exception from the semaphore? Actually, the semaphore context manager doesn't throw.
# But the token bucket might throw? We don't throw, we return False.
# So the only exceptions are from the api_call_func or timeout.
# But if we get an exception from the api_call_func (other than timeout) we don't update the timeout.
if config.fallback is not None:
return config.fallback
else:
raise
-
However, note: the bulkhead semaphore might block until it can acquire. But we don't want to wait indefinitely for the bulkhead? Actually, the semaphore will wait until it can acquire. That's the point of bulkhead: to limit concurrent calls, but we wait in a queue. But if we want to reject when bulkhead is full, we should use try_acquire (non-blocking). But the requirement says bulkheads to isolate failures, so we want to limit concurrency but we might want to queue? Typically, bulkheads are used to prevent cascading failures by limiting the number of concurrent calls, and when the limit is reached, we reject (fast-fail). So we should use a non-blocking acquire for bulkhead?
Let me think: the bulkhead pattern is about having a fixed number of threads (or connections) so that if one service fails, it doesn't exhaust all threads. So we want to limit the number of concurrent calls, and when the limit is reached, we reject immediately (without waiting). So we should use a semaphore with a non-blocking try.
Alternatively, we can update the average with the timeout value when we timeout? But that might be an overestimate because the call might have taken even longer? Actually, we set the timeout and then the call times out exactly at the timeout? Not necessarily, it might take a bit longer? But in practice, asyncio.wait_for cancels the task at the timeout, so the time taken is approximately the timeout.
But if we update with the timeout, then next time we set a longer timeout, which might lead to even longer timeouts? We are in a bad state.
Maybe we should not update on timeout. Then the timeout remains at the last successful average (or base). If the service becomes slower and we start timing out, we don't increase the timeout, so we continue to fail fast. That might be acceptable.
Alternatively, we can have a separate mechanism to detect that the service is down and then use a shorter timeout? But that's more complex.
Let's stick to updating only on success.
22. We also need to handle the case when the token bucket is empty and we have a fallback: we return the fallback without making the call.
-
We are using non-blocking bulkhead and token bucket. So we are rejecting immediately if either limit is exceeded.
-
We are using asyncio.Semaphore for bulkhead. The semaphore is per tenant and we are creating one in the config. That's fine.
-
We are using time.monotonic() for measuring time and for token bucket refill. That's good.
-
We'll define:
class BulkheadException(Exception):
pass
class RateLimitException(Exception):
pass
-
We might want to have a way to reset the adaptive timeout? Maybe if we have a series of failures, we might want to reset the average? But that's not required.
-
We are not handling the case when the token bucket or bulkhead are shared between multiple ResilienceLayer instances? We are creating one config per tenant and then using it. So if we have multiple ResilienceLayer instances for the same tenant, we should share the same config? We can have a separate configuration registry.
Alternatively, we can design the ResilienceLayer to be a singleton per tenant? But the requirement is to build a layer, so we can assume that the same tenant config is used for all calls for that tenant.
-
We'll assume that the tenant_configs dictionary is shared and the same TenantResilienceConfig instance is used for the same tenant.
-
Let's write the code accordingly.
-
But note: the token bucket and bulkhead semaphore are not thread-safe if we are in a multi-threaded environment? We are using asyncio, so we are in a single thread event loop. But if we have multiple event loops? We are using asyncio.Semaphore which is tied to an event loop. We must create the semaphore in the same event loop that we are going to use.
We can create the TenantResilienceConfig in the event loop that we are going to use. Or we can create the semaphore without a loop? In Python 3.10+, `asyncio.Semaphore` can be created without a loop and it will use the current running loop.
But if we create the config in one event loop and then use in another, it might break. So we must ensure that the ResilienceLayer is used in the same event loop as the one in which the config was created.
Alternatively, we can create the semaphore and token bucket in the context of the current event loop when we first use the config? But that would require lazy initialization.
Since we are designing for an async environment, we assume that the ResilienceLayer is used in the same event loop.
32. We'll write the code accordingly.
-
Let's code:
import asyncio
import time
from collections import deque
class BulkheadException(Exception):
pass
class RateLimitException(Exception):
pass
class TokenBucket:
def init(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = capacity
self.last_refill = time.monotonic()
self.lock = asyncio.Lock()
async def consume(self, tokens=1):
async with self.lock:
now = time.monotonic()
delta = now - self.last_refill
self.tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
self.last_refill = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
else:
return False
class TenantResilienceConfig:
def init(self, max_concurrent, rate_limit_capacity, rate_limit_refill_rate, base_timeout, fallback):
self.bulkhead_semaphore = asyncio.Semaphore(max_concurrent)
self.token_bucket = TokenBucket(rate_limit_capacity, rate_limit_refill_rate)
self.base_timeout = base_timeout
self.current_timeout = base_timeout
self.fallback = fallback
self.ewma = None
self.alpha = 0.1
def update_response_time(self, response_time):
if self.ewma is None:
self.ewma = response_time
else:
self.ewma = self.alpha * response_time + (1-self.alpha) * self.ewma
# Set timeout to 2 times the EWMA, but not less than base_timeout
self.current_timeout = max(self.base_timeout, 2 * self.ewma)
class ResilienceLayer:
def init(self, tenant_configs: dict):
self.tenant_configs = tenant_configs
async def call(self, tenant_id, api_call_func, *args, **kwargs):
config = self.tenant_configs.get(tenant_id)
if config is None:
raise ValueError(f"No config for tenant {tenant_id}")
bulkhead_acquired = False
try:
# Try to acquire bulkhead without blocking
bulkhead_acquired = config.bulkhead_semaphore.acquire(block=False)
if not bulkhead_acquired:
if config.fallback is not None:
return config.fallback
else:
raise BulkheadException(f"Bulkhead full for tenant {tenant_id}")
# Try to consume a token from the token bucket
if not await config.token_bucket.consume():
if config.fallback is not None:
return config.fallback
else:
raise RateLimitException(f"Rate limit exceeded for tenant {tenant_id}")
# Set timeout
timeout = config.current_timeout
# Make the call
start = time.monotonic()
try:
result = await asyncio.wait_for(api_call_func(*args, **kwargs), timeout=timeout)
elapsed = time.monotonic() - start
config.update_response_time(elapsed)
return result
except asyncio.TimeoutError:
if config.fallback is not None:
return config.fallback
else:
raise
except Exception:
if config.fallback is not None:
return config.fallback
else:
raise
finally:
if bulkhead_acquired:
config.bulkhead_semaphore.release()
We can change:
except (asyncio.TimeoutError, aiohttp.ClientError, ...) as e:
...
But we don't know what exceptions the api_call_func might raise. We can let the user specify which exceptions are retryable? Or we can have a predicate.
Alternatively, we can only return fallback for asyncio.TimeoutError and for the token bucket and bulkhead exceptions? But note: the token bucket and bulkhead are already handled before the call.
Actually, the only exceptions that occur in the try block (after the token bucket and bulkhead) are from the api_call_func and asyncio.TimeoutError.
We are already handling asyncio.TimeoutError separately. For other exceptions, we return fallback. That might be acceptable because we want to be resilient to any failure of the third-party API.
But if the api_call_func raises a ValueError because of a programming error, we might not want to return a fallback. So we should let the user decide.
We can change the ResilienceLayer to take an optional `exceptions_to_fallback` tuple. But the requirement doesn't specify.
Let's assume we want to fallback for any exception that is not a programming error? That's hard to define.
Alternatively, we can have a configuration per tenant: `fallback_exceptions` which is a tuple of exception classes that we want to catch and use fallback. By default, we can catch all exceptions? But that might hide bugs.
Since the requirement says "synthetic fallback responses", we assume that we want to return a fallback for any failure of the third-party API. But note: the third-party API call might throw an exception for many reasons, and we want to be resilient.
We'll leave it as catching all exceptions for now, but note that in production we might want to be more selective.
35. We also need to consider that the token bucket and bulkhead are per tenant, but what about per endpoint? The requirement says "per-tenant", so we are doing per tenant. But if a tenant has multiple endpoints and we want to rate limit per endpoint, we would need a separate config per endpoint.
We can extend the `tenant_id` to include the endpoint? Or we can have a hierarchy. But the requirement says per-tenant, so we assume one config per tenant for all their API calls.
36. We are updating the adaptive timeout for the tenant, regardless of the endpoint. That's okay if all endpoints have similar performance. But if we have multiple endpoints with different latencies, we might want to track per endpoint.
We can change the key to be (tenant_id, endpoint) or we can have a separate config per endpoint. But the requirement says per-tenant, so we'll stick to tenant.
37. Let's test with a simple example.
-
We might want to have a way to reset the token bucket and bulkhead? For example, if we want to clear the state for a tenant. We can add methods to reset.
-
We are using asyncio.Semaphore and asyncio.Lock which are tied to the event loop. If we are in a multi-threaded environment with multiple event loops, we must be cautious.
-
We'll assume a single event loop.
-
This design is for async. If we want sync, we would need a different implementation (using threads and threading.Semaphore). But the requirement doesn't specify.
-
We'll leave it as async.
-
Let's write a simple test:
async def fake_api_call(delay, success=True):
await asyncio.sleep(delay)
if success:
return "OK"
else:
raise ValueError("API error")
configs = {
"tenant1": TenantResilienceConfig(
max_concurrent=2,
rate_limit_capacity=5,
rate_limit_refill_rate=1, # 1 token per second
base_timeout=1.0,
fallback="FALLBACK"
)
}
layer = ResilienceLayer(configs)
Test 1: within rate limit and bulkhead
result = await layer.call("tenant1", fake_api_call, 0.1, True)
print(result) # OK
Test 2: rate limit: make 6 calls quickly? But we have 5 tokens and refill 1 per second. So 6th should be rate limited if we don't wait.
But note: the token bucket refills over time. We are consuming tokens and then the refill happens on each consume based on the time passed.
We can test by making 6 calls in a loop without delay. The first 5 should succeed, the 6th should use fallback.
However, the token bucket is shared and we are using a lock, so it's safe.
-
We might want to have a way to adjust the token bucket refill rate and capacity at runtime? Not required.
-
We are not handling the case when the token bucket or bulkhead are full and we have no fallback: we raise an exception. That's acceptable.
-
We are not handling the case when the adaptive timeout becomes very large? We set it to max(base_timeout, 2*ewma). So if the ewma becomes 100 seconds, then timeout becomes 200 seconds. That might be too long. We might want to set a maximum timeout? We can have a max_timeout in the config.
We can change:
self.current_timeout = min(self.max_timeout, max(self.base_timeout, 2 * self.ewma))
But the requirement doesn't specify. We'll leave it as is.
47. We are not updating the adaptive timeout for the fallback response time? Correct, because we don't get a real response.
-
We are updating the adaptive timeout only on success. That means if we have a fallback, we don't update. So the timeout remains the same.
-
We are not distinguishing between different types of failures? We are using the same fallback for any failure (bulkhead, rate limit, timeout, exception). That's acceptable.
-
We are releasing the bulkhead semaphore in the finally block, so even if we return early (fallback) or raise, we release.
-
We are not releasing the token bucket because we already consumed the token and there's no way to put it back? That's by design: we consumed a token for this call, even if we didn't make the call (because of bulkhead or rate limit? Actually, we consume the token after bulkhead and then we make the call. If the call fails, we don't return the token. That's acceptable because we want to count the attempt.
But note: if we get a rate limit exception from the token bucket, we haven't consumed a token? Actually, in the code:
if not await config.token_bucket.consume():
... return fallback or raise ...
So if `consume` returns False, we haven't consumed a token. That's correct.
And if we acquire the bulkhead and then the token bucket fails, we release the bulkhead and then return fallback. That's correct.
52. We are not handling the case when the token bucket consume might block? We are using await and the consume method uses a lock, but it doesn't wait for tokens to refill. It just returns False if not enough tokens. So it's non-blocking.
-
We are using time.monotonic() for the token bucket refill. That's good.
-
We are using asyncio.wait_for for the timeout. If the call finishes before the timeout, we cancel the wait_for? No, wait_for returns when the call finishes. So it's fine.
-
We are measuring the time from just before the wait_for until after. That includes the time to schedule the call? But in async, the call might not start immediately? We are measuring the wall time from when we start the wait_for until it returns. That's acceptable.
-
We are not accounting for the time spent in the bulkhead and token bucket? That's okay because we want the timeout to be for the API call only.
-
We are not handling the case when the api_call_func is not a coroutine? We are using await, so it must be a coroutine. We can check? Not required.
-
We'll assume the user passes a coroutine function.
-
We are not handling the case when the api_call_func returns a future? We are using await so it must be awaitable.
-
We'll leave as is.
-
We might want to have a way to configure the adaptive timeout parameters (alpha, multiplier) per tenant? We can add them to the TenantResilienceConfig.
-
We'll keep it simple for now.
-
Let's write the code accordingly.
-
We'll also consider that the token bucket and bulkhead might be shared between multiple ResilienceLayer instances? We are passing the same config objects, so they are shared.
-
We are not handling the case when the ResilienceLayer is used in multiple event loops? We are using asyncio primitives that are tied to the current event loop. If we use the same config in multiple event loops, we might get an error. We can create the semaphore and lock in the current event loop when we first use them? But we are creating them in the init of TenantResilienceConfig. So we must create the config in the same event loop that we are going to use.
We can change the TenantResilienceConfig to create the semaphore and token bucket lazily in the current event loop? But then we have to store the loop and check.
Alternatively, we can require that the ResilienceLayer is used in the same event loop as the one in which the config was created.
We'll note that in the documentation.
66. We'll write the code as above.
-
Let's test with a simple example.
-
We might want to have a way to get the current state of the token bucket and bulkhead for monitoring.
-
We can add properties to TenantResilienceConfig:
@property
def available_tokens(self):
# we need to compute the current tokens without consuming? We can have a method that returns the current tokens without acquiring the lock? But we need the lock to get an accurate value.
We can add:
async def get_available_tokens(self):
async with self.lock:
now = time.monotonic()
delta = now - self.last_refill
tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
return tokens
And for bulkhead, we can check the semaphore's value? In asyncio.Semaphore, we don't have a public method to get the current value. We can store the current value ourselves? Or we can use a custom semaphore that exposes the value.
Alternatively, we can use an asyncio.BoundedSemaphore and then try to acquire and release? That would be messy.
We can change the bulkhead to use a custom class that tracks the current number of permits.
But for simplicity, we can skip.
-
We'll leave monitoring out for now.
-
We'll write the code as above.
-
Let's write the final code with some comments.
-
We'll also note that the token bucket refill rate is in tokens per second, and capacity is the maximum tokens.
-
We'll assume the tenant configs are provided at initialization and then we don't change them.
-
We'll write the code accordingly.
-
We'll also note that the api_call_func must be an async function that takes *args and **kwargs.
-
We are using asyncio.wait_for which cancels the task if it times out. That's what we want.
-
We are catching asyncio.TimeoutError and then returning fallback or re-raising.
-
We are catching all other exceptions and returning fallback or re-raising.
-
We are releasing the bulkhead semaphore in the finally block, so even if we raise an exception, we release.
-
We are not catching KeyboardInterrupt or SystemExit? We are catching Exception which doesn't include those. That's good.
-
We are not handling the case when the token bucket consume raises an exception? It shouldn't.
import asyncio
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, Optional, TypeVar, Generic
from datetime import datetime, timedelta
from collections import deque
import math
from contextlib import asynccontextmanager
T = TypeVar('T')
class FailureType(Enum):
TIMEOUT = "timeout"
CONNECTION_ERROR = "connection_error"
RATE_LIMIT = "rate_limit"
SERVER_ERROR = "server_error"
BULKHEAD_REJECTED = "bulkhead_rejected"
@dataclass
class ResilienceConfig:
"""Configuration for a tenant's resilience policies"""
# Bulkhead settings
max_concurrent: int = 10
max_queued: int = 20
# Token bucket rate limiting (per minute)
rate_limit_capacity: int = 100
rate_limit_refill_rate: float = 100.0 # tokens per minute
# Timeout settings
base_timeout: float = 5.0
min_timeout: float = 1.0
max_timeout: float = 30.0
timeout_ewma_alpha: float = 0.1
# Fallback settings
fallback_enabled: bool = True
fallback_ttl: float = 60.0 # seconds
fallback_on_failures: set[FailureType] = field(default_factory=lambda: {
FailureType.TIMEOUT,
FailureType.CONNECTION_ERROR,
FailureType.SERVER_ERROR
})
# Circuit breaker
circuit_breaker_enabled: bool = False
circuit_breaker_failure_threshold: int = 5
circuit_breaker_recovery_timeout: float = 60.0
class TokenBucket:
"""Thread-safe token bucket implementation"""
def __init__(self, capacity: int, refill_rate: float):
self.capacity = capacity
self.refill_rate = refill_rate # tokens per second
self._tokens = float(capacity)
self._last_refill = time.monotonic()
self._lock = asyncio.Lock()
async def consume(self, tokens: int = 1) -> bool:
"""Consume tokens from bucket. Returns True if successful."""
async with self._lock:
now = time.monotonic()
# Refill tokens based on elapsed time
delta = now - self._last_refill
self._tokens = min(
self.capacity,
self._tokens + delta * self.refill_rate
)
self._last_refill = now
if self._tokens >= tokens:
self._tokens -= tokens
return True
return False
@property
def available_tokens(self) -> float:
"""Get current token count without consuming"""
now = time.monotonic()
delta = now - self._last_refill
return min(self.capacity, self._tokens + delta * self.refill_rate)
class Bulkhead:
"""Bulkhead pattern implementation with capacity and queue limits"""
def __init__(self, max_concurrent: int, max_queued: int = 0):
self.max_concurrent = max_concurrent
self.max_queued = max_queued
self._semaphore = asyncio.Semaphore(max_concurrent)
self._queue = asyncio.Queue(maxsize=max_queued) if max_queued > 0 else None
self._active = 0
self._lock = asyncio.Lock()
@asynccontextmanager
async def acquire(self, timeout: Optional[float] = None):
"""Acquire bulkhead slot with optional timeout"""
try:
# Try immediate acquisition first
if self._semaphore.locked():
# Check queue if available
if self._queue and not self._queue.full():
try:
await asyncio.wait_for(self._queue.put(None), timeout=timeout)
except asyncio.TimeoutError:
raise BulkheadRejectedError("Bulkhead queue timeout")
else:
raise BulkheadRejectedError("Bulkhead at capacity")
# Acquire semaphore
await self._semaphore.acquire()
async with self._lock:
self._active += 1
yield
finally:
async with self._lock:
self._active -= 1
self._semaphore.release()
# Notify queued waiters
if self._queue and not self._queue.empty():
self._queue.get_nowait()
@property
def current_load(self) -> float:
"""Current load percentage (0-1)"""
return self._active / self.max_concurrent if self.max_concurrent > 0 else 0
class AdaptiveTimeout:
"""EWMA-based adaptive timeout calculator"""
def __init__(self, base_timeout: float, min_timeout: float, max_timeout: float, alpha: float = 0.1):
self.base_timeout = base_timeout
self.min_timeout = min_timeout
self.max_timeout = max_timeout
self.alpha = alpha
self._ewma: Optional[float] = None
self._history = deque(maxlen=100)
self._lock = asyncio.Lock()
def record_success(self, duration: float):
"""Record successful response time"""
self._history.append(duration)
def get_timeout(self) -> float:
"""Calculate adaptive timeout based on EWMA"""
if not self._history:
return self.base_timeout
# Calculate EWMA
if self._ewma is None:
self._ewma = sum(self._history) / len(self._history)
else:
latest = self._history[-1]
self._ewma = self.alpha * latest + (1 - self.alpha) * self._ewma
# Apply safety margins and bounds
timeout = max(self.min_timeout, min(self.max_timeout, self._ewma * 2))
return timeout
class CircuitBreaker:
"""Circuit breaker implementation"""
def __init__(self, failure_threshold: int, recovery_timeout: float):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self._failure_count = 0
self._last_failure_time: Optional[datetime] = None
self._state = "CLOSED" # CLOSED, OPEN, HALF_OPEN
self._lock = asyncio.Lock()
async def before_call(self) -> bool:
"""Check if call should proceed"""
async with self._lock:
if self._state == "OPEN":
if (datetime.utcnow() - self._last_failure_time).total_seconds() > self.recovery_timeout:
self._state = "HALF_OPEN"
return True
return False
return True
def record_success(self):
"""Record successful call"""
asyncio.create_task(self._reset_failures())
def record_failure(self):
"""Record failed call"""
asyncio.create_task(self._increment_failure())
async def _reset_failures(self):
async with self._lock:
self._failure_count = 0
self._state = "CLOSED"
async def _increment_failure(self):
async with self._lock:
self._failure_count += 1
self._last_failure_time = datetime.utcnow()
if self._failure_count >= self.failure_threshold:
self._state = "OPEN"
class FallbackCache:
"""Cache for synthetic fallback responses"""
def __init__(self, ttl: float = 60.0):
self.ttl = ttl
self._cache: Dict[str, tuple[Any, float]] = {}
self._lock = asyncio.Lock()
async def get(self, cache_key: str) -> Optional[Any]:
"""Get cached fallback if still valid"""
async with self._lock:
if cache_key in self._cache:
value, timestamp = self._cache[cache_key]
if time.monotonic() - timestamp < self.ttl:
return value
del self._cache[cache_key]
return None
async def set(self, cache_key: str, value: Any):
"""Cache fallback response"""
async with self._lock:
self._cache[cache_key] = (value, time.monotonic())
async def invalidate(self, cache_key: Optional[str] = None):
"""Invalidate cache entries"""
async with self._lock:
if cache_key:
self._cache.pop(cache_key, None)
else:
self._cache.clear()
class BulkheadRejectedError(Exception):
"""Raised when bulkhead rejects a request"""
pass
class ResilienceLayer:
"""Main resilience layer for third-party API calls"""
def __init__(self):
self._tenant_configs: Dict[str, ResilienceConfig] = {}
self._tenant_bulkheads: Dict[str, Bulkhead] = {}
self._tenant_token_buckets: Dict[str, TokenBucket] = {}
self._tenant_timeouts: Dict[str, AdaptiveTimeout] = {}
self._tenant_circuit_breakers: Dict[str, CircuitBreaker] = {}
self._fallback_cache = FallbackCache()
self._global_lock = asyncio.Lock()
def configure_tenant(self, tenant_id: str, config: ResilienceConfig):
"""Configure resilience policies for a tenant"""
async with self._global_lock:
self._tenant_configs[tenant_id] = config
self._tenant_bulkheads[tenant_id] = Bulkhead(
config.max_concurrent,
config.max_queued
)
self._tenant_token_buckets[tenant_id] = TokenBucket(
config.rate_limit_capacity,
config.rate_limit_refill_rate / 60.0 # Convert to per second
)
self._tenant_timeouts[tenant_id] = AdaptiveTimeout(
config.base_timeout,
config.min_timeout,
config.max_timeout,
config.timeout_ewma_alpha
)
if config.circuit_breaker_enabled:
self._tenant_circuit_breakers[tenant_id] = CircuitBreaker(
config.circuit_breaker_failure_threshold,
config.circuit_breaker_recovery_timeout
)
async def call(
self,
tenant_id: str,
api_func: Callable[..., Any],
*args,
fallback: Optional[Callable[..., Any]] = None,
failure_types: Optional[set[FailureType]] = None,
**kwargs
) -> Any:
"""
Execute API call with resilience patterns
Args:
tenant_id: Tenant identifier
api_func: Async function to call
fallback: Override fallback for this call
failure_types: Override failure types for fallback
**kwargs: Arguments for api_func
Returns:
API response or fallback
"""
config = self._tenant_configs.get(tenant_id)
if not config:
raise ValueError(f"Tenant {tenant_id} not configured")
bulkhead = self._tenant_bulkheads[tenant_id]
token_bucket = self._tenant_token_buckets[tenant_id]
adaptive_timeout = self._tenant_timeouts[tenant_id]
circuit_breaker = self._tenant_circuit_breakers.get(tenant_id)
# Check circuit breaker first
if circuit_breaker:
if not await circuit_breaker.before_call():
return await self._handle_failure(
tenant_id,
FailureType.SERVER_ERROR,
fallback,
failure_types,
"Circuit breaker OPEN"
)
# Check rate limit
if not await token_bucket.consume():
return await self._handle_failure(
tenant_id,
FailureType.RATE_LIMIT,
fallback,
failure_types,
"Rate limit exceeded"
)
# Acquire bulkhead with timeout
try:
async with bulkhead.acquire(timeout=1.0): # 1 second to acquire bulkhead
# Execute with adaptive timeout
timeout = adaptive_timeout.get_timeout()
try:
start = time.monotonic()
result = await asyncio.wait_for(api_func(*args, **kwargs), timeout=timeout)
duration = time.monotonic() - start
# Record success
adaptive_timeout.record_success(duration)
if circuit_breaker:
circuit_breaker.record_success()
return result
except asyncio.TimeoutError as e:
if circuit_breaker:
circuit_breaker.record_failure()
return await self._handle_failure(
tenant_id,
FailureType.TIMEOUT,
fallback,
failure_types,
f"Timeout after {timeout}s"
)
except Exception as e:
if circuit_breaker:
circuit_breaker.record_failure()
return await self._handle_failure(
tenant_id,
FailureType.CONNECTION_ERROR,
fallback,
failure_types,
str(e)
)
except BulkheadRejectedError:
return await self._handle_failure(
tenant_id,
FailureType.BULKHEAD_REJECTED,
fallback,
failure_types,
"Bulkhead rejected request"
)
async def _handle_failure(
self,
tenant_id: str,
failure_type: FailureType,
override_fallback: Optional[Callable[..., Any]],
override_failure_types: Optional[set[FailureType]],
error_message: str
) -> Any:
"""Handle failures with fallback logic"""
config = self._tenant_configs[tenant_id]
failure_types = override_failure_types or config.fallback_on_failures
if failure_type not in failure_types:
raise RuntimeError(f"Unhandled failure type: {failure_type}. Error: {error_message}")
# Try override fallback first
if override_fallback:
try:
return await override_fallback()
except Exception:
pass
# Check cache for synthetic fallback
if config.fallback_enabled:
cache_key = f"{tenant_id}:{failure_type.value}"
cached = await self._fallback_cache.get(cache_key)
if cached is not None:
return cached
# Generate synthetic fallback
fallback = await self._generate_synthetic_fallback(tenant_id, failure_type, error_message)
# Cache fallback
if config.fallback_enabled:
await self._fallback_cache.set(cache_key, fallback)
return fallback
async def _generate_synthetic_fallback(
self,
tenant_id: str,
failure_type: FailureType,
error_message: str
) -> Any:
"""Generate synthetic fallback response based on failure type"""
# This would be customized based on your API's expected response format
fallback_responses = {
FailureType.TIMEOUT: {
"status": "degraded",
"data": None,
"message": "Service responding slowly, using cached data",
"cached": True,
"timestamp": datetime.utcnow().isoformat()
},
FailureType.RATE_LIMIT: {
"status": "rate_limited",
"data": None,
"message": "Rate limit exceeded, please retry",
"retry_after": 60,
"timestamp": datetime.utcnow().isoformat()
},
FailureType.CONNECTION_ERROR: {
"status": "unavailable",
"data": None,
"message": "Service temporarily unavailable",
"retryable": True,
"timestamp": datetime.utcnow().isoformat()
},
FailureType.SERVER_ERROR: {
"status": "error",
"data": None,
"message": "Internal server error",
"error_code": "INTERNAL_ERROR",
"timestamp": datetime.utcnow().isoformat()
},
FailureType.BULKHEAD_REJECTED: {
"status": "busy",
"data": None,
"message": "Service at capacity, please retry",
"retry_after": 5,
"timestamp": datetime.utcnow().isoformat()
}
}
response = fallback_responses.get(failure_type, {
"status": "error",
"message": error_message,
"timestamp": datetime.utcnow().isoformat()
})
# Add debug info in non-production
# response["debug"] = {"failure_type": failure_type.value, "error": error_message}
return response
async def get_metrics(self, tenant_id: str) -> Dict[str, Any]:
"""Get current resilience metrics for a tenant"""
config = self._tenant_configs.get(tenant_id)
if not config:
return {}
bulkhead = self._tenant_bulkheads[tenant_id]
token_bucket = self._tenant_token_buckets[tenant_id]
timeout_calc = self._tenant_timeouts[tenant_id]
circuit_breaker = self._tenant_circuit_breakers.get(tenant_id)
return {
"tenant_id": tenant_id,
"bulkhead": {
"active": bulkhead._active,
"max_concurrent": config.max_concurrent,
"load_percent": bulkhead.current_load,
"queued": bulkhead._queue.qsize() if bulkhead._queue else 0
},
"rate_limit": {
"tokens_available": token_bucket.available_tokens,
"capacity": config.rate_limit_capacity,
"refill_rate": config.rate_limit_refill_rate
},
"timeout": {
"current": timeout_calc.get_timeout(),
"ewma": timeout_calc._ewma,
"history_size": len(timeout_calc._history)
},
"circuit_breaker": {
"state": circuit_breaker._state if circuit_breaker else "disabled",
"failure_count": circuit_breaker._failure_count if circuit_breaker else 0,
"last_failure": circuit_breaker._last_failure_time.isoformat()
if circuit_breaker and circuit_breaker._last_failure_time
else None
} if circuit_breaker else None
}
async def reset_tenant(self, tenant_id: str):
"""Reset all resilience state for a tenant"""
async with self._global_lock:
if tenant_id in self._tenant_timeouts:
self._tenant_timeouts[tenant_id] = AdaptiveTimeout(
self._tenant_configs[tenant_id].base_timeout,
self._tenant_configs[tenant_id].min_timeout,
self._tenant_configs[tenant_id].max_timeout,
self._tenant_configs[tenant_id].timeout_ewma_alpha
)
if tenant_id in self._tenant_circuit_breakers:
self._tenant_circuit_breakers[tenant_id] = CircuitBreaker(
self._tenant_configs[tenant_id].circuit_breaker_failure_threshold,
self._tenant_configs[tenant_id].circuit_breaker_recovery_timeout
)
await self._fallback_cache.invalidate(tenant_id)
# Example usage
async def example_third_party_api_call(param: str) -> dict:
"""Simulated third-party API call"""
await asyncio.sleep(0.1) # Simulate API latency
return {"result": f"Processed {param}"}
async def main():
# Initialize resilience layer
resilience = ResilienceLayer()
# Configure tenant
resilience.configure_tenant(
"tenant_123",
ResilienceConfig(
max_concurrent=5,
max_queued=10,
rate_limit_capacity=50,
rate_limit_refill_rate=50.0,
base_timeout=3.0,
fallback_enabled=True,
fallback_ttl=30.0
)
)
# Make API calls with resilience
try:
# Normal call
result = await resilience.call(
"tenant_123",
example_third_party_api_call,
"test_param"
)
print(f"Success: {result}")
# Call with custom fallback
result = await resilience.call(
"tenant_123",
example_third_party_api_call,
"test_param",
fallback=lambda: {"status": "custom_fallback", "data": "default"}
)
print(f"With custom fallback: {result}")
# Get metrics
metrics = await resilience.get_metrics("tenant_123")
print(f"Metrics: {metrics}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
asyncio.run(main())
Key Features:
1. Bulkheads
- Limits concurrent calls per tenant
- Optional queue for pending requests
- Prevents resource exhaustion in one tenant from affecting others
2. Adaptive Timeouts
- EWMA (Exponentially Weighted Moving Average) of response times
- Automatically adjusts timeouts based on observed latency
- Configurable min/max bounds
3. Token Buckets (Rate Limiting)
- Per-tenant rate limiting
- Smooth refill rate (tokens per second)
- Burst capacity support
4. Synthetic Fallback Responses
- Configurable fallback types per failure
- Cached fallback responses with TTL
- Structured JSON fallback format
- Custom fallback override per call
5. Circuit Breaker (Optional)
- Prevents calls to failing services
- Configurable failure threshold
- Automatic recovery after timeout
6. Comprehensive Metrics
- Real-time monitoring of all resilience components
- Bulkhead load, token bucket status, timeout stats, circuit breaker state
7. Configurable Failure Handling
- Per-tenant configuration
- Per-call override of fallback behavior
- Fine-grained control over which failures trigger fallbacks
Configuration Options:
# Example configurations for different tenant tiers
premium_config = ResilienceConfig(
max_concurrent=20,
max_queued=50,
rate_limit_capacity=500,
rate_limit_refill_rate=500.0,
base_timeout=10.0,
fallback_ttl=120.0,
circuit_breaker_enabled=True,
circuit_breaker_failure_threshold=10
)
basic_config = ResilienceConfig(
max_concurrent=5,
max_queued=10,
rate_limit_capacity=50,
rate_limit_refill_rate=50.0,
base_timeout=3.0,
fallback_ttl=30.0
)
Usage Patterns:
- Initial Setup: Configure each tenant with appropriate limits
- API Calls: Wrap all third-party calls with
resilience.call()
- Monitoring: Periodically poll
get_metrics() for observability
- Maintenance: Use
reset_tenant() to clear state during incidents
Production Considerations:
- Metrics Export: Integrate with Prometheus/OpenTelemetry
- Dynamic Config: Add runtime config reload capability
- Distributed Mode: Use Redis for shared state across instances
- Priority Queues: Add priority levels for different API endpoints
- Cost-aware: Track and limit expensive operations per tenant
- Tracing: Add distributed tracing context propagation
This implementation provides enterprise-grade resilience with clean separation of concerns, comprehensive metrics, and flexible configuration per tenant.