We are going to design a resiliency layer for third-party APIs. The layer should include:
- Timeouts
- Retries with jitter
- Bulkheads (to limit the number of concurrent calls)
- Fallback stubs (when the API fails)
We'll design this in a way that it can be used as a wrapper around any API call.
Steps:
-
Timeout: We can set a timeout for the entire operation. If the operation takes longer than the timeout, we abort.
-
Retries with jitter: We retry on failures (like network errors, 5xx, etc.) but with a jitter to avoid thundering herd.
-
Bulkhead: We limit the number of concurrent calls to the same API (or group of APIs) to prevent overloading.
-
Fallback: When all retries fail, we can use a fallback function (stub) that returns a default or cached response.
We'll design a class that can be used to wrap a function that makes an API call.
Let's assume the function we are wrapping has the following signature:
async def api_call(*args, **kwargs) -> Any
We'll create a class ResilientAPIClient that takes:
- The function to call (the third-party API function)
- Configuration for:
- timeout: total time allowed for the operation (including retries? or per attempt?)
- max_retries: maximum number of retries (excluding the first call)
- retry_status_codes: which HTTP status codes should trigger a retry (if we are using an HTTP client, we might get the response)
- bulkhead_semaphore: a semaphore to limit concurrency (we can use asyncio.Semaphore)
- fallback_function: a function to call when all retries fail (can be async or sync? we'll assume async for consistency)
However, note that the bulkhead is about limiting concurrent calls. We can use a semaphore that is shared among multiple instances of the same API.
But note: we might want to have different bulkheads for different APIs. So we can accept a semaphore in the constructor.
Alternatively, we can create the semaphore inside the class if not provided, but then each instance would have its own bulkhead.
Better: let the user provide a semaphore (or we can create one per group of APIs by having a factory that returns the same semaphore for the same API name).
But for simplicity, we'll let the user pass a semaphore. If they don't, we'll create one with a default limit.
Let's design:
class ResilientAPIClient:
def init(self, func, timeout=10, max_retries=3, retry_status_codes=(500, 502, 503, 504), bulkhead_semaphore=None, fallback_function=None):
self.func = func
self.timeout = timeout # per attempt timeout? or total? We'll do per attempt and total? Actually, we want to set a timeout for each attempt and also a total timeout?
Actually, we have two timeouts:
- per attempt: we set a timeout for each try (including the first and retries)
- total: we set a deadline for the entire operation (from the first try to the last)
But the problem: if we set a total timeout, then we might not have time for all retries.
Alternatively, we can set:
- timeout: per attempt timeout (in seconds)
- total_timeout: overall timeout (in seconds) for the entire operation (including retries)
However, note that the bulkhead and retries are independent. We might want to set a total timeout that is independent of the per-attempt timeout.
Let's change: we'll have:
- per_attempt_timeout: the timeout for each individual attempt (including the first call and each retry)
- total_timeout: the total time from the start of the first attempt to the end of the last retry.
But note: if we have a total_timeout, then we might have to adjust the number of retries or the backoff.
Alternatively, we can just set a per_attempt_timeout and then in the retry loop, we check the elapsed time and stop if we exceed a total_timeout.
We'll do:
total_timeout: optional, if set, we will not retry if the elapsed time is already more than total_timeout.
But note: the per_attempt_timeout is for each try, so if one try takes the full per_attempt_timeout, then we might not have time for retries.
Let's design:
We have a deadline (if total_timeout is set) = current_time + total_timeout.
For each attempt:
- we set a timeout for that attempt (per_attempt_timeout)
- but we also check if we have exceeded the deadline, then we break.
However, if we are using asyncio, we can use asyncio.wait_for for the per_attempt_timeout, and then we can also check the deadline.
Alternatively, we can set the per_attempt_timeout to be the minimum of (per_attempt_timeout, remaining time until deadline).
But let's keep it simple: we'll have two timeouts and we'll handle them separately.
We'll do:
start_time = time.monotonic()
for attempt in range(max_retries+1):
if total_timeout is not None and (time.monotonic() - start_time) >= total_timeout:
break # we don't attempt because we've exceeded total_timeout
try:
# set a timeout for this attempt: if total_timeout is set, then the timeout for this attempt is min(per_attempt_timeout, remaining_time)
# but note: if we set the timeout for the attempt to be the remaining time, then if the attempt takes that long, we won't have time for retries.
# Actually, we want to set the per_attempt_timeout to the value we set, but if we are going to exceed the total_timeout, we should reduce the per_attempt_timeout.
remaining = total_timeout - (time.monotonic() - start_time) if total_timeout is not None else None
attempt_timeout = per_attempt_timeout
if remaining is not None and remaining <= 0:
break
if remaining is not None and remaining < per_attempt_timeout:
attempt_timeout = remaining
# Now, we call the function with the attempt_timeout.
# We can use asyncio.wait_for for the async function.
result = await asyncio.wait_for(self.func(*args, **kwargs), timeout=attempt_timeout)
# If we get a response and it's not in the retry_status_codes, we return.
if isinstance(result, Response): # if we are getting an HTTP response, we check the status
if result.status not in self.retry_status_codes:
return result
else:
# If the function doesn't return a response with status, then we assume success if no exception?
# Actually, we are catching exceptions. So if the function returns without exception, we return.
return result
except (asyncio.TimeoutError, SomeNetworkException) as e:
# We catch timeout and network exceptions (and maybe others) and then retry.
# But note: we might have other exceptions that we don't want to retry? We can have an option for that.
# For now, we retry on asyncio.TimeoutError and any exception that is considered a network error.
# We can also have a list of exceptions to retry on.
# We'll log the error and then retry if we have retries left and total_timeout not exceeded.
pass
# If we get here, we've exhausted retries or total_timeout.
if fallback_function is not None:
return await fallback_function(*args, **kwargs)
else:
raise # or return a default?
But note: the bulkhead. We must acquire the semaphore before making the call and release after.
We'll do:
async with bulkhead_semaphore:
... the above logic ...
However, note: the bulkhead is about limiting concurrent calls. So we want to acquire the semaphore for the entire attempt (including retries?) or just for the current attempt?
Actually, the bulkhead is for the number of concurrent calls to the same API. So we want to hold the semaphore for the entire time we are trying (including retries) for one logical call? Or just for each physical call?
Consider: if we have a bulkhead of 10, that means we can have 10 concurrent physical calls. But if we are retrying, we are making multiple physical calls for one logical call.
We want to limit the number of concurrent physical calls. So we should acquire the semaphore for each physical call (each attempt). But then note: if we are retrying, we will acquire again? That might not be what we want.
Actually, the bulkhead pattern is about isolating resources. We want to limit the number of concurrent calls to the external service. So each physical call (each attempt) should be counted.
So we should acquire the semaphore for each attempt. But then note: if we are going to retry, we release the semaphore after the attempt (whether success or failure) and then acquire again for the next attempt.
That is acceptable because we are limiting the number of concurrent physical calls.
However, if we have a bulkhead of 1, then we can only have one physical call at a time. And if we are retrying, we are going to release and then acquire again, but by the time we acquire again, the bulkhead might be taken by another logical call.
That is the intended behavior.
So we do:
for attempt in ...:
async with bulkhead_semaphore:
... make the attempt ...
But wait: what about the total_timeout? We are holding the semaphore only for the duration of the attempt. That is fine.
However, note that the bulkhead_semaphore is shared among all ResilientAPIClient instances for the same API (if we use the same semaphore). So we are limiting the total concurrent physical calls to that API.
Let's code accordingly.
5. Jitter: We want to add jitter to the retry delay to avoid all instances retrying at the same time.
We'll do exponential backoff with jitter.
We can have:
base_delay: the base delay in seconds (e.g., 0.1, 0.2, 0.4, ...)
max_delay: the maximum delay between retries.
jitter: we can add a random factor.
We can use: delay = min(base_delay * (2 ** attempt), max_delay) * (0.5 + random.random() * 0.5) [for full jitter]
or we can use: delay = min(base_delay * (2 ** attempt), max_delay) + random.uniform(0, base_delay)
Let's use full jitter: delay = min(base_delay * (2 ** attempt), max_delay) * random.uniform(0.5, 1.5)
But note: we want to avoid too much jitter? Actually, full jitter is good to avoid synchronization.
We can make jitter a factor: e.g., jitter=0.1 means we add up to 10% jitter.
Alternatively, we can have:
delay = min(base_delay * (2 ** attempt), max_delay)
jittered_delay = delay * (1 + random.uniform(-jitter, jitter))
But then jitter=0.1 would give 10% up and down.
Let's do:
jittered_delay = delay * (1 + random.uniform(-self.jitter, self.jitter))
We'll add jitter as a parameter (default 0.1 for 10%).
6. We also need to decide which exceptions to retry on.
We'll have a tuple of exceptions that we retry on. We can call it `retry_exceptions`.
We'll catch these exceptions and then retry.
But note: if we get an exception that is not in retry_exceptions, we don't retry.
Also, if we get a response with a status code in retry_status_codes, we treat that as a failure and retry.
However, note: some responses might be successful but with a 5xx? We are retrying on 5xx.
But what about 429 (Too Many Requests)? We might want to retry on 429 as well, but note that 429 often comes with a Retry-After header.
We can extend: if we get 429, we can check the Retry-After header and wait that long? But that's more advanced.
For now, we'll just treat 429 as a retryable status code (if it's in the list) and use the backoff.
But note: the backoff might not be enough because the server might ask us to wait longer. We can improve by looking at Retry-After, but let's keep it simple.
7. We also want to log the retries.
- We'll make the class async because most third-party API calls are async these days.
Let's define:
class ResilientAPIClient:
def init(self, func, timeout=10, max_retries=3, retry_status_codes=(500, 502, 503, 504, 429),
bulkhead_semaphore=None, fallback_function=None, retry_exceptions=(aiohttp.ClientError, asyncio.TimeoutError),
base_delay=0.1, max_delay=10, jitter=0.1, total_timeout=None):
self.func = func
self.timeout = timeout # per attempt timeout
self.max_retries = max_retries
self.retry_status_codes = retry_status_codes
self.bulkhead_semaphore = bulkhead_semaphore or asyncio.Semaphore(10) # default 10 concurrent calls
self.fallback_function = fallback_function
self.retry_exceptions = retry_exceptions
self.base_delay = base_delay
self.max_delay = max_delay
self.jitter = jitter
self.total_timeout = total_timeout
async def call(self, *args, **kwargs):
start_time = time.monotonic()
for attempt in range(self.max_retries + 1):
# Check total timeout
if self.total_timeout is not None:
elapsed = time.monotonic() - start_time
if elapsed >= self.total_timeout:
# We break and then will try fallback or raise
break
try:
async with self.bulkhead_semaphore:
# Calculate the remaining time for this attempt if total_timeout is set
if self.total_timeout is not None:
remaining = self.total_timeout - (time.monotonic() - start_time)
if remaining <= 0:
break
attempt_timeout = min(self.timeout, remaining)
else:
attempt_timeout = self.timeout
result = await asyncio.wait_for(self.func(*args, **kwargs), timeout=attempt_timeout)
# If the result is an HTTP response (we assume it has a status attribute) then check
if hasattr(result, 'status') and result.status in self.retry_status_codes:
# We treat this as a failure and will retry
raise RetryableError(f"Status code {result.status} received")
else:
# Success
return result
except self.retry_exceptions as e:
# We caught a retryable exception
# Log it
logger.warning(f"Attempt {attempt+1} failed with exception: {e}. Retrying...")
# If we are going to retry, then wait
if attempt < self.max_retries:
# Calculate delay with jitter
delay = min(self.base_delay * (2 ** attempt), self.max_delay)
jittered_delay = delay * (1 + random.uniform(-self.jitter, self.jitter))
await asyncio.sleep(jittered_delay)
else:
# We've exhausted retries
break
except Exception as e:
# If it's not a retryable exception, we break and then either fallback or raise
logger.error(f"Non-retryable exception: {e}")
break
# If we get here, we've exhausted retries or total_timeout
if self.fallback_function is not None:
return await self.fallback_function(*args, **kwargs)
else:
# We re-raise the last exception? But we might have broken out without an exception?
# We need to track the last exception.
# Let's track the last exception and then raise it if no fallback.
# But note: we might break due to total_timeout without an exception. Then we should raise a TimeoutError?
# We'll raise a custom exception.
raise ResiliencyError("All retries failed or total timeout exceeded")
However, note: we are catching only self.retry_exceptions and then for non-retryable we break and then re-raise? But we are not storing the last exception.
Let's change: we'll store the last exception and then if we break without a successful call, we raise the last exception (or a new one if we broke due to timeout).
We'll do:
last_exception = None
for attempt in ...:
try:
...
return result
except self.retry_exceptions as e:
last_exception = e
... retry logic ...
except Exception as e:
last_exception = e
break # non-retryable, break
# After loop
if self.fallback_function:
return await self.fallback_function(*args, **kwargs)
else:
if last_exception:
raise last_exception
else:
# We broke due to total_timeout? or because we didn't even try? (if max_retries=0 and we break immediately?)
raise ResiliencyError("Operation failed without an exception? This should not happen.")
But wait: we also break when total_timeout is exceeded. In that case, we don't have an exception. So we should set a flag or raise a TimeoutError.
Alternatively, we can raise a TimeoutError when we break due to total_timeout.
Let's adjust:
for attempt in ...:
if self.total_timeout and elapsed >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
Then at the end, we have last_exception set.
9. We also have to consider that the bulkhead_semaphore might be acquired and then we get a timeout in the wait_for? That will release the semaphore? Yes, because we are using async with.
-
We are using asyncio.wait_for for the per-attempt timeout. That will raise asyncio.TimeoutError, which is in retry_exceptions by default.
-
We are using a custom exception RetryableError for status codes that are retryable? But note: we are raising it and then catching it as a retry_exception? We have to include RetryableError in retry_exceptions? Or we can just raise a RetryableError and then catch it because we catch Exception? Actually, we are catching self.retry_exceptions which by default doesn't include RetryableError.
We can do: when we get a retryable status code, we raise a RetryableError (which we define) and then we catch it because we catch Exception? But we are catching only self.retry_exceptions.
Alternatively, we can just treat the status code as a condition to retry and then continue the loop without raising an exception? But then we have to break out of the try block and then go to the retry.
Let's change: we don't raise for status codes, we just break out of the try block and then go to the retry logic? But we are in the try block.
We can do:
if hasattr(result, 'status') and result.status in self.retry_status_codes:
# We treat as a failure and then we will retry
# But we are not in an exception, so we have to manually go to the retry logic.
# We can raise a custom exception that we catch, or we can set a flag and then break out of the try and then go to the retry.
# Let's raise a RetryableError and then catch it in the except block? But we are already in the try block.
# Alternatively, we can do:
if attempt < self.max_retries:
# wait and then continue the loop
... wait ...
continue
else:
break
But that would be inside the try block and then we break out of the try? Actually, we are in the try block and then we break the loop? That's messy.
Let's restructure:
We'll do:
try:
... make the call ...
if status in retry_status_codes:
raise RetryableError()
else:
return result
except self.retry_exceptions as e:
... handle ...
But then we have to include RetryableError in retry_exceptions? Or we can catch RetryableError separately?
Alternatively, we can have:
try:
... make the call ...
if status in retry_status_codes:
# We treat it as a failure and then we want to retry
# We can set an error and then break out of the try and then go to the retry logic?
# Actually, we can raise a RetryableError and then catch it in the same except block? But we are catching `self.retry_exceptions` and RetryableError is not in there.
Let's change: we catch two types of exceptions:
- the ones in retry_exceptions (like network errors, timeouts)
- and we also catch the case of retryable status codes by raising a RetryableError and then catching it? But then we have to include RetryableError in retry_exceptions.
Let's code accordingly.
However, note: the total_timeout check is at the beginning of the loop. But what about the time spent in the bulkhead semaphore? We are acquiring the semaphore and then doing the call. The time we wait for the semaphore is not counted? That might be acceptable because the bulkhead is about limiting concurrency, not about time.
But if we are waiting for the semaphore, we are not making progress. Should we count that towards total_timeout? Possibly, because the user might expect the operation to complete within total_timeout.
We can adjust: we check the elapsed time before acquiring the semaphore? But then we might break without acquiring, which is acceptable.
Alternatively, we can include the time waiting for the semaphore? That would require checking after we acquire? But then we might have already waited too long.
Let's keep it simple: we check the elapsed time at the beginning of each attempt (before acquiring the semaphore). If we are over, we break.
But note: if we are waiting for the semaphore, we are not in the attempt. So the time waiting for the semaphore is not counted. That might be acceptable because the bulkhead is a separate concern.
However, if the semaphore is not available for a long time, we might exceed the total_timeout without even trying. We can adjust:
while True:
if total_timeout and elapsed >= total_timeout:
break
try:
async with bulkhead_semaphore:
... do the call ...
break # if we get here, we succeeded or got a non-retryable exception? Actually, we have to handle the call result.
except ...:
... retry ...
But that's a different structure.
We are currently in a for loop for attempts. We want to try up to max_retries+1 times, but also respect total_timeout.
We can do:
for attempt in range(self.max_retries+1):
if self.total_timeout and (time.monotonic() - start_time) >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
try:
async with self.bulkhead_semaphore:
... make the call ...
except self.retry_exceptions as e:
last_exception = e
# retry
if attempt < self.max_retries:
... wait ...
continue
else:
break
else:
if status in retry_status_codes:
last_exception = RetryableError(...)
if attempt < self.max_retries:
... wait ...
continue
else:
break
else:
return result
This is getting complex.
Let's refactor:
We'll have a loop that tries up to max_retries+1 times, but also breaks if total_timeout is exceeded.
We'll track the last exception and the last status if we got a response.
We'll do:
start_time = time.monotonic()
last_exception = None
for attempt in range(self.max_retries+1):
# Check total timeout
if self.total_timeout is not None and (time.monotonic() - start_time) >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
try:
async with self.bulkhead_semaphore:
# Calculate remaining time for this attempt
if self.total_timeout is not None:
remaining = self.total_timeout - (time.monotonic() - start_time)
if remaining <= 0:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
attempt_timeout = min(self.timeout, remaining)
else:
attempt_timeout = self.timeout
result = await asyncio.wait_for(self.func(*args, **kwargs), timeout=attempt_timeout)
# Check if we should retry based on status
if hasattr(result, 'status') and result.status in self.retry_status_codes:
# We consider this a failure and will retry
raise RetryableError(f"Status {result.status} received")
else:
return result
except self.retry_exceptions as e:
last_exception = e
except RetryableError as e:
last_exception = e
except Exception as e:
# Non-retryable exception, we break and then re-raise
last_exception = e
break
# If we are here, we had an error and we are going to retry if we can
if attempt < self.max_retries and (self.total_timeout is None or (time.monotonic() - start_time) < self.total_timeout):
# Calculate delay with jitter
delay = min(self.base_delay * (2 ** attempt), self.max_delay)
jittered_delay = delay * (1 + random.uniform(-self.jitter, self.jitter))
await asyncio.sleep(jittered_delay)
else:
break
# After the loop
if self.fallback_function is not None:
return await self.fallback_function(*args, **kwargs)
else:
if last_exception:
raise last_exception
else:
raise ResiliencyError("Operation failed without an exception")
15. We are using RetryableError for status codes. We need to define that.
-
We are catching self.retry_exceptions and RetryableError separately? Actually, we can combine:
except (self.retry_exceptions, RetryableError) as e:
But note: self.retry_exceptions is a tuple, and we can add RetryableError to it? But we defined the class with a default tuple that doesn't include RetryableError.
We can change the default to include RetryableError? Or we can catch both.
Let's do:
except (self.retry_exceptions + (RetryableError,)) as e:
But note: if self.retry_exceptions is not a tuple? We assume it's a tuple.
Alternatively, we can have:
retry_exceptions = (aiohttp.ClientError, asyncio.TimeoutError, RetryableError)
But then the user might pass their own tuple and we want to include RetryableError.
Let's change: we'll define a class attribute _default_retry_exceptions and then in the init, we'll extend the user provided ones with RetryableError.
if retry_exceptions is None:
retry_exceptions = (aiohttp.ClientError, asyncio.TimeoutError)
self.retry_exceptions = retry_exceptions + (RetryableError,)
But then the user might provide a tuple that already includes RetryableError? That's okay.
Alternatively, we can do:
self.retry_exceptions = tuple(set(retry_exceptions + (RetryableError,)))
But then we lose order? Not important.
However, note: the user might have provided a custom exception that is a subclass of one of the default ones? Then we are adding RetryableError which is not a subclass.
We'll do:
self.retry_exceptions = retry_exceptions + (RetryableError,)
And then in the except, we catch self.retry_exceptions.
-
We are using asyncio.wait_for for the per-attempt timeout. That will raise asyncio.TimeoutError, which is in the default retry_exceptions.
-
We are using a bulkhead_semaphore that is an asyncio.Semaphore. We must ensure that we are in an async context.
-
We are using time.monotonic for time measurements.
-
We are using asyncio.sleep for the jittered delay.
-
We are returning the result of the fallback_function if provided, otherwise we raise the last exception.
-
We are not logging? We can add logging.
-
We are not handling the case when the function func returns a response that doesn't have a status attribute. We only check for status if the result has that attribute.
Let's code accordingly.
However, note: the above code does not account for the time spent in the jitter sleep? We are not counting that towards total_timeout? We are only checking the time at the beginning of the attempt and then after the attempt.
But the sleep is after the attempt and before the next attempt. So if we have a long sleep, we might exceed the total_timeout and then we break without trying the next attempt.
We are checking at the beginning of the loop, so after the sleep we check again. That's correct.
-
We are not accounting for the time spent in the bulkhead semaphore? We are checking before acquiring the semaphore. That means if we wait for the semaphore, we might exceed the total_timeout while waiting? We break without acquiring.
We can adjust: we can check after acquiring? But then we have already waited for the semaphore. We want to break if the total_timeout is exceeded even if we are waiting for the semaphore.
Let's change: we check the total_timeout at the beginning of the loop (before acquiring) and then also after acquiring? Because after acquiring, we might have waited for a while.
Alternatively, we can check the time after we acquire and then if we are over, we break? But then we have the semaphore and we are not using it? That might be acceptable.
But note: if we break after acquiring, we are holding the semaphore and then we break? That would release the semaphore when we exit the async with? Yes.
So let's do:
for attempt in ...:
if self.total_timeout and (time.monotonic() - start_time) >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
try:
async with self.bulkhead_semaphore:
# Now we have the semaphore, check again because we might have waited for it?
if self.total_timeout and (time.monotonic() - start_time) >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
... rest ...
except ...:
But that duplicates the check.
Alternatively, we can check only after we acquire? But then we might break without trying because we didn't check before acquiring? We want to avoid waiting for the semaphore if we know we are going to break.
We can do:
for attempt in ...:
# We are going to try to acquire the semaphore, but if we know we are going to time out, we break.
if self.total_timeout and (time.monotonic() - start_time) >= self.total_timeout:
last_exception = asyncio.TimeoutError("Total timeout exceeded")
break
try:
# Wait for the semaphore with a timeout? We don't want to wait for the semaphore indefinitely if we are going to time out.
# We can try to acquire the semaphore with a timeout that is the remaining total_timeout?
# But note: the semaphore doesn't support timeout in async with? Actually, we can do:
# try:
# await asyncio.wait_for(self.bulkhead_semaphore.acquire(), timeout=remaining)
# except asyncio.TimeoutError:
# # We couldn't acquire the semaphore in time, so we break?
# last_exception = asyncio.TimeoutError("Could not acquire bulkhead semaphore in time")
# break
# But then we have to release the semaphore manually? We are using async with, which does acquire and release.
# Alternatively, we can use:
# async with self.bulkhead_semaphore:
# ...
# But that doesn't have a timeout.
# We can do:
# try:
# await self.bulkhead_semaphore.acquire()
# except asyncio.TimeoutError: # but the semaphore acquire doesn't raise TimeoutError? We have to use wait_for.
# Actually, asyncio.Semaphore.acquire() is a coroutine that doesn't take a timeout. We have to use asyncio.wait_for.
# Let's change: we won't use async with, but we will manually acquire and release.
# But then we have to handle release in a finally block.
# Alternatively, we can create a context manager that times out? That's complex.
# Given the complexity, and the fact that the bulkhead is about limiting concurrency and not about time, we might decide that waiting for the semaphore is part of the operation and we don't time it? But then we might exceed the total_timeout while waiting for the semaphore.
# We'll do:
# if self.total_timeout:
# remaining = self.total_timeout - (time.monotonic() - start_time)
# if remaining <= 0:
# last_exception = asyncio.TimeoutError("Total timeout exceeded")
# break
# try:
# await asyncio.wait_for(self.bulkhead_semaphore.acquire(), timeout=remaining)
# except asyncio.TimeoutError:
# last_exception = asyncio.TimeoutError("Bulkhead semaphore not acquired in time")
# break
# else:
# await self.bulkhead_semaphore.acquire()
# try:
# ... make the call ...
# finally:
# self.bulkhead_semaphore.release()
# But then we are not using async with, and we have to release.
# This is getting too complex.
# Let's stick to the original: we don't time the semaphore wait. We only time the actual API call.
# We'll change the comment: the total_timeout is for the entire operation including retries and the time to make the call, but not including the time waiting for the bulkhead.
# That's acceptable because the bulkhead is about limiting concurrency, not about latency.
# So we'll keep the original structure.
except ...:
Let's code.
We'll define:
class RetryableError(Exception):
pass
class ResiliencyError(Exception):
pass
class ResilientAPIClient:
...
-
We are going to assume the function func is an async function that returns a response object with a status attribute if we want to check status codes.
If the function doesn't return such an object, we skip the status check and just return the result.
-
We are going to log warnings and errors. We'll use the standard logging module.
Let's code accordingly.
However, note: the user might not want to log. We can make logging configurable? We'll leave it as is for now.
-
We are going to use random for jitter.
-
We are going to use time.monotonic for timing.
-
We are going to use asyncio for async operations.
Let's write the code.
But note: we are using asyncio.wait_for for the per-attempt timeout. That will cancel the task if it times out. We are catching the TimeoutError and then retrying.
-
We are not handling the case when the function func is canceled by something else? We are catching only the exceptions we know.
-
We are not handling the case when the function func raises a CancelledError? That would be an asyncio.CancelledError, which is not in the default retry_exceptions? We are catching only asyncio.TimeoutError and aiohttp.ClientError.
We might want to retry on CancelledError? Probably not, because it's usually raised by the event loop when the task is canceled. We shouldn't retry.
So we leave it as non-retryable.
-
We are not handling the case when the function func returns a response with a status that is 200 but the body has an error? That's application specific. We don't handle that.
We only handle HTTP status codes if the result has a status attribute.
-
We are going to assume that the function func returns an object that has a status attribute only if we are dealing with HTTP. Otherwise, we return the result.
-
We are going to write the code accordingly.
Let's code.
I'll design a comprehensive resiliency layer for third-party APIs with all the requested patterns. This will be a Python implementation using asyncio for asynchronous operations, but the patterns are language-agnostic.
Resiliency Layer Architecture
import asyncio
import random
import time
import logging
from typing import Any, Callable, Optional, Dict, List
from dataclasses import dataclass
from enum import Enum
logger = logging.getLogger(__name__)
class FailureType(Enum):
TIMEOUT = "timeout"
NETWORK_ERROR = "network_error"
SERVER_ERROR = "server_error" # 5xx
CLIENT_ERROR = "client_error" # 4xx (usually not retryable)
RATE_LIMIT = "rate_limit" # 429
@dataclass
class RetryConfig:
"""Configuration for retry behavior"""
max_attempts: int = 3
base_delay: float = 0.1 # seconds
max_delay: float = 10.0 # seconds
jitter_factor: float = 0.25 # ±25% jitter
retry_on: tuple = (FailureType.TIMEOUT, FailureType.NETWORK_ERROR,
FailureType.SERVER_ERROR, FailureType.RATE_LIMIT)
@dataclass
class BulkheadConfig:
"""Configuration for bulkhead pattern"""
max_concurrent: int = 10
max_queued: int = 100 # max waiting requests
@dataclass
class TimeoutConfig:
"""Configuration for timeouts"""
connect_timeout: float = 5.0 # connection establishment
read_timeout: float = 10.0 # waiting for response
total_timeout: float = 30.0 # entire operation
class CircuitBreaker:
"""Circuit breaker pattern implementation"""
def __init__(self, failure_threshold: int = 5, recovery_timeout: float = 60.0):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.last_failure_time: Optional[float] = None
self.state = "CLOSED" # CLOSED, OPEN, HALF_OPEN
async def call(self, func: Callable, *args, **kwargs):
"""Execute function with circuit breaker protection"""
if self.state == "OPEN":
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = "HALF_OPEN"
logger.info("Circuit breaker entering HALF_OPEN state")
else:
raise Exception("Circuit breaker is OPEN - request rejected")
try:
result = await func(*args, **kwargs)
if self.state == "HALF_OPEN":
self._reset()
return result
except Exception as e:
self._record_failure()
raise
def _record_failure(self):
"""Record a failure and potentially open circuit"""
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = "OPEN"
logger.warning(f"Circuit breaker OPEN after {self.failure_count} failures")
def _reset(self):
"""Reset circuit breaker to closed state"""
self.failure_count = 0
self.last_failure_time = None
self.state = "CLOSED"
logger.info("Circuit breaker reset to CLOSED state")
class Bulkhead:
"""Bulkhead pattern - limits concurrent executions"""
def __init__(self, config: BulkheadConfig):
self.config = config
self.semaphore = asyncio.Semaphore(config.max_concurrent)
self.queue = asyncio.Queue(maxsize=config.max_queued)
self.active_count = 0
async def execute(self, func: Callable, *args, **kwargs):
"""Execute function with bulkhead protection"""
# Try to acquire semaphore immediately or queue
try:
await asyncio.wait_for(self.semaphore.acquire(), timeout=1.0)
self.active_count += 1
except asyncio.TimeoutError:
# Try to queue if there's space
if self.queue.qsize() < self.config.max_queued:
await self.queue.put(True)
await self.semaphore.acquire()
self.active_count += 1
await self.queue.get()
else:
raise Exception("Bulkhead full - request rejected")
try:
return await func(*args, **kwargs)
finally:
self.active_count -= 1
self.semaphore.release()
class ResilientAPIClient:
"""Main resiliency layer combining all patterns"""
def __init__(
self,
retry_config: Optional[RetryConfig] = None,
bulkhead_config: Optional[BulkheadConfig] = None,
timeout_config: Optional[TimeoutConfig] = None,
circuit_breaker: Optional[CircuitBreaker] = None,
fallback_handler: Optional[Callable] = None
):
self.retry_config = retry_config or RetryConfig()
self.bulkhead = Bulkhead(bulkhead_config) if bulkhead_config else None
self.timeout_config = timeout_config or TimeoutConfig()
self.circuit_breaker = circuit_breaker or CircuitBreaker()
self.fallback_handler = fallback_handler
self.metrics = {
"total_requests": 0,
"successful": 0,
"failed": 0,
"retried": 0,
"fallback_used": 0
}
async def request(
self,
func: Callable,
*args,
classify_error: Optional[Callable[[Exception], FailureType]] = None,
**kwargs
) -> Any:
"""
Execute API call with full resiliency layer
Args:
func: Async function that makes the actual API call
classify_error: Optional function to classify exceptions into FailureTypes
*args, **kwargs: Arguments passed to func
Returns:
API response or fallback result
"""
self.metrics["total_requests"] += 1
last_exception = None
for attempt in range(self.retry_config.max_attempts):
try:
# Apply timeout constraints
async with asyncio.timeout(self.timeout_config.total_timeout):
# Apply bulkhead if configured
wrapped_func = func
if self.bulkhead:
wrapped_func = lambda *a, **kw: self.bulkhead.execute(func, *a, **kw)
# Apply circuit breaker
if self.circuit_breaker:
wrapped_func = lambda *a, **kw: self.circuit_breaker.call(func, *a, **kw)
# Execute with individual timeouts
result = await asyncio.wait_for(
wrapped_func(*args, **kwargs),
timeout=self.timeout_config.read_timeout
)
self.metrics["successful"] += 1
return result
except asyncio.TimeoutError as e:
last_exception = e
failure_type = FailureType.TIMEOUT
logger.warning(f"Attempt {attempt + 1} timeout: {e}")
except Exception as e:
last_exception = e
# Classify error if classifier provided
failure_type = classify_error(e) if classify_error else self._classify_error(e)
logger.warning(f"Attempt {attempt + 1} failed with {failure_type.value}: {e}")
# Don't retry client errors (4xx) unless specifically configured
if failure_type == FailureType.CLIENT_ERROR:
logger.info(f"Client error, not retrying: {e}")
break
# Should we retry this failure?
if failure_type not in self.retry_config.retry_on:
break
# Calculate delay with exponential backoff and jitter
if attempt < self.retry_config.max_attempts - 1:
delay = self._calculate_retry_delay(attempt)
logger.info(f"Retrying in {delay:.2f}s...")
await asyncio.sleep(delay)
self.metrics["retried"] += 1
# All retries exhausted
self.metrics["failed"] += 1
# Use fallback if available
if self.fallback_handler:
try:
fallback_result = await self.fallback_handler(*args, **kwargs)
self.metrics["fallback_used"] += 1
logger.info("Fallback used successfully")
return fallback_result
except Exception as e:
logger.error(f"Fallback also failed: {e}")
# Re-raise the last exception
if last_exception:
raise last_exception
raise Exception("All retries failed without specific exception")
def _classify_error(self, exception: Exception) -> FailureType:
"""Classify exception into failure type"""
if isinstance(exception, asyncio.TimeoutError):
return FailureType.TIMEOUT
# Add more classifications based on your HTTP library
# Example for aiohttp:
# if isinstance(exception, aiohttp.ClientConnectorError):
# return FailureType.NETWORK_ERROR
# if hasattr(exception, 'status') and exception.status >= 500:
# return FailureType.SERVER_ERROR
return FailureType.NETWORK_ERROR
def _calculate_retry_delay(self, attempt: int) -> float:
"""Calculate retry delay with exponential backoff and jitter"""
base_delay = self.retry_config.base_delay * (2 ** attempt)
capped_delay = min(base_delay, self.retry_config.max_delay)
# Add jitter (±jitter_factor%)
jitter = capped_delay * self.retry_config.jitter_factor
jittered_delay = capped_delay + random.uniform(-jitter, jitter)
return max(0, jittered_delay)
def get_metrics(self) -> Dict[str, Any]:
"""Get current metrics"""
return self.metrics.copy()
def reset_metrics(self):
"""Reset metrics to zero"""
for key in self.metrics:
self.metrics[key] = 0
# Example usage
class ExampleAPIClient:
"""Example third-party API client"""
def __init__(self, base_url: str):
self.base_url = base_url
async def fetch_data(self, endpoint: str, timeout: float = 5.0) -> Dict:
"""Simulated API call - replace with actual HTTP client"""
# Simulate random failures for demo
if random.random() < 0.3: # 30% failure rate
raise ConnectionError("Simulated network error")
if random.random() < 0.1: # 10% timeout
await asyncio.sleep(10) # Longer than timeout
return {"data": "success", "endpoint": endpoint}
async def example_fallback(*args, **kwargs):
"""Fallback stub that returns cached/default data"""
return {"data": "fallback", "cached": True, "timestamp": time.time()}
async def main():
# Configure resiliency layer
resilient_client = ResilientAPIClient(
retry_config=RetryConfig(
max_attempts=3,
base_delay=0.5,
max_delay=5.0,
jitter_factor=0.2
),
bulkhead_config=BulkheadConfig(
max_concurrent=5,
max_queued=10
),
timeout_config=TimeoutConfig(
connect_timeout=3.0,
read_timeout=8.0,
total_timeout=15.0
),
circuit_breaker=CircuitBreaker(
failure_threshold=3,
recovery_timeout=30.0
),
fallback_handler=example_fallback
)
# Create API client
api_client = ExampleAPIClient("https://api.example.com")
# Make resilient call
try:
result = await resilient_client.request(
api_client.fetch_data,
endpoint="/users",
classify_error=lambda e: FailureType.NETWORK_ERROR if isinstance(e, ConnectionError) else FailureType.TIMEOUT
)
print(f"Success: {result}")
except Exception as e:
print(f"Failed after all retries and fallback: {e}")
# Print metrics
print(f"Metrics: {resilient_client.get_metrics()}")
if __name__ == "__main__":
asyncio.run(main())
Key Features Explained
1. Timeouts
- Connection timeout: Time to establish connection
- Read timeout: Time to wait for response after connection
- Total timeout: Maximum time for entire operation including retries
- Uses
asyncio.timeout() context manager for clean timeout handling
2. Retries with Jitter
- Exponential backoff:
delay = base_delay * (2^attempt)
- Jitter: Random variation to prevent thundering herd
- Configurable: Base/max delays, jitter factor
- Smart retry: Only retries on configured failure types
3. Bulkhead Pattern
- Concurrency limiting: Semaphore limits concurrent calls
- Queueing: Requests queue when limit reached (configurable max queue size)
- Isolation: Prevents one API from exhausting all resources
4. Circuit Breaker
- Failure counting: Opens circuit after threshold failures
- Recovery: Half-open state tests if service recovered
- Fast failure: Rejects requests immediately when open
5. Fallback Stubs
- Graceful degradation: Returns cached/default data when all else fails
- Configurable: Custom fallback function per use case
- Metrics: Tracks when fallbacks are used
Advanced Configuration Example
# Different configurations for different API types
payment_gateway_config = ResilientAPIClient(
retry_config=RetryConfig(
max_attempts=2, # Fewer retries for payments
base_delay=1.0,
max_delay=5.0,
retry_on=(FailureType.TIMEOUT, FailureType.SERVER_ERROR) # Don't retry 429s manually
),
circuit_breaker=CircuitBreaker(
failure_threshold=2, # More sensitive for payments
recovery_timeout=120.0 # Longer recovery
),
fallback_handler=local_payment_cache # Use cached payment methods
)
external_search_config = ResilientAPIClient(
retry_config=RetryConfig(
max_attempts=5, # More retries for search
base_delay=0.1,
max_delay=2.0,
retry_on=(FailureType.TIMEOUT, FailureType.NETWORK_ERROR,
FailureType.SERVER_ERROR, FailureType.RATE_LIMIT)
),
bulkhead_config=BulkheadConfig(
max_concurrent=20, # Higher concurrency for search
max_queued=50
),
fallback_handler=local_search_index # Fallback to local index
)
Production Considerations
- Metrics & Monitoring: Export metrics to Prometheus/Datadog
- Dynamic Configuration: Load configs from environment/consul
- Adaptive Timeouts: Adjust based on historical latency
- Priority Queues: Different priority levels for bulkhead queue
- Rate Limiting: Separate rate limiter per API
- Caching: Integrate with Redis/memcached for fallbacks
- Tracing: Add distributed tracing (OpenTelemetry)
- Health Checks: Periodic health checks for circuit breaker state
Testing Strategy
import pytest
from unittest.mock import AsyncMock, patch
@pytest.mark.asyncio
async def test_retry_with_jitter():
"""Test that retries happen with proper jitter"""
call_count = 0
async def flaky_api():
nonlocal call_count
call_count += 1
if call_count < 3:
raise ConnectionError("Fail")
return {"ok": True}
client = ResilientAPIClient(retry_config=RetryConfig(max_attempts=3))
result = await client.request(flaky_api)
assert result == {"ok": True}
assert call_count == 3
@pytest.mark.asyncio
async def test_circuit_breaker_opens():
"""Test circuit breaker opens after failures"""
breaker = CircuitBreaker(failure_threshold=2)
async def always_fails():
raise Exception("Fail")
with pytest.raises(Exception, match="Circuit breaker is OPEN"):
await breaker.call(always_fails)
await breaker.call(always_fails) # Second failure opens circuit
await breaker.call(always_fails) # Should be rejected
This implementation provides production-ready resiliency patterns that can be composed and configured per third-party API dependency.