Your API is working fine. Average response time is around 200 milliseconds, error rates are low, and everything looks healthy.
Then a third-party service starts responding slowly.
Your API requests begin taking several seconds. Connections stay open longer, workers become busy, and eventually even unrelated requests start slowing down.
The first instinct is often to add retries.
If a request fails, try again. Simple, right?
Unfortunately, retries can make the situation worse.
I've worked on backend performance optimization, including reducing average API response times by 35% at SaneBox. One thing I've learned is that performance isn't just about making successful requests faster.
It's also about controlling how much time and resources we're willing to spend when something goes wrong.
Let's look at how timeouts, deadlines, retries, and fallback strategies work together to make APIs more reliable.
1. Why One Slow Dependency Can Affect Your Entire API
Imagine a checkout endpoint that calls three services:
Client | v Checkout API | +-- Inventory Service | +-- Pricing Service | +-- Shipping Service | v Response Under normal conditions, each service responds quickly.
Now imagine the shipping service becomes slow.
If your application waits indefinitely for its response, that delay can keep request-handling resources occupied.
As more requests arrive, resource usage increases. Depending on your server's concurrency model and connection limits, requests may start queueing.
Eventually, one unhealthy dependency can degrade the entire application.
This is called a cascading failure.
The important question isn't simply:
"How do we make the shipping service faster?"
It's:
"How long should our checkout API wait before deciding the dependency is unavailable?"
That's what timeouts help us control.
2. Understand What a Timeout Actually Does
A timeout defines how long an operation is allowed to wait before the client stops waiting.
With Python's HTTPX library, you can configure several timeout types.
import httpx timeout = httpx.Timeout( connect=2.0, read=3.0, write=3.0, pool=1.0, ) client = httpx.AsyncClient(timeout=timeout) Each timeout protects a different stage.
| Timeout | What it controls |
|---|---|
| Connect | Waiting to establish a network connection |
| Read | Waiting for response data |
| Write | Waiting to send request data |
| Pool | Waiting for an available connection |
These values are illustrative. Production settings should reflect measured latency and service requirements.
One detail is easy to miss: an HTTPX read timeout isn't necessarily a limit on total request duration.
It measures inactivity while waiting for response data. A server that repeatedly sends data can keep a response alive longer than the configured read timeout.
HTTPX documents these behaviors in its timeout configuration guide.
For a strict total operation deadline, we need another layer.
3. Give Each API Request a Time Budget
Suppose our checkout endpoint should respond within two seconds.
It calls inventory, pricing, and shipping services sequentially.
If every dependency has a two-second timeout, the total request could consume much more than two seconds.
Instead, define a deadline for the entire operation.
In Python, asyncio.timeout() provides a convenient way to enforce an overall time limit.
import asyncio import httpx async def get_checkout_details(client, order_id): async with asyncio.timeout(2.0): inventory = await client.get( f"/inventory/{order_id}" ) inventory.raise_for_status() pricing = await client.get( f"/pricing/{order_id}" ) pricing.raise_for_status() shipping = await client.get( f"/shipping/{order_id}" ) shipping.raise_for_status() return { "inventory": inventory.json(), "pricing": pricing.json(), "shipping": shipping.json(), } This example assumes client is an HTTPX client configured with the appropriate base URL and per-operation timeouts.
The two-second budget covers the awaited operations inside the context, not just one HTTP call.
When the deadline expires, asyncio.timeout() cancels the current task and raises TimeoutError outside the context.
There are limitations.
Cancellation is cooperative, and blocking synchronous code or poorly behaved asynchronous operations can delay cleanup. The deadline also doesn't guarantee that a remote service stops processing a request.
Still, an overall deadline prevents the application from accidentally allocating a full timeout to every dependency.
See the Python asyncio documentation for the details.
4. Why Adding Retries Can Make an Outage Worse
Let's say a downstream service is overloaded and starts returning errors.
Your API automatically retries every failed request three times.
That sounds reasonable until you consider what happens across multiple services.
Imagine this hypothetical architecture:
Client | v Service A (3 attempts) | v Service B (3 attempts) | v Service C (3 attempts) | v Database If each layer independently makes up to three attempts, one original request can trigger as many as 27 database operations along a failing path.
This is an illustrative worst case, not a measured workload.
Instead of reducing pressure, retries amplify it.
The downstream service is already struggling. Now every failure creates additional traffic.
AWS discusses this failure pattern in its Builders' Library article on timeouts, retries, and backoff.
The practical lesson is simple:
Retries are useful for transient failures, but they aren't free recovery mechanisms.
Every retry consumes time, connections, CPU, and possibly money.
5. Retry Only When It Makes Sense
Not every failure deserves another attempt.
Consider these cases:
| Failure | Typical decision |
|---|---|
| Temporary connection failure | Retry may help |
| HTTP 503 | Retry may help |
| HTTP 429 | Respect server retry guidance |
| HTTP 400 | Usually don't retry unchanged |
| HTTP 401 | Fix authentication first |
| Invalid application data | Don't retry |
| Request deadline exceeded | Stop |
The distinction matters because a permanent failure won't disappear just because we repeat the same request.
Retries should also depend on whether the operation is safe to repeat.
A read-only request is usually safer to retry than a payment or order-creation request.
For operations with side effects, use an idempotency mechanism or an equivalent business-level guarantee.
A network timeout doesn't prove the remote operation failed. It may have completed successfully before the response was lost.
That uncertainty is exactly why blindly retrying writes can create duplicate operations.
6. Use Exponential Backoff With Jitter
If retries are appropriate, avoid retrying immediately.
Suppose hundreds of clients experience the same temporary failure.
If they all retry exactly one second later, they create another traffic spike.
Exponential backoff increases the delay between attempts.
Jitter adds randomness so clients don't retry at the same moment.
Here's a small Python example for a read-only request:
import asyncio import random import httpx RETRYABLE_STATUS = {429, 502, 503, 504} async def fetch_with_retry(client, url): max_attempts = 3 for attempt in range(max_attempts): try: response = await client.get(url) if response.status_code not in RETRYABLE_STATUS: response.raise_for_status() return response.json() response.raise_for_status() except (httpx.TimeoutException, httpx.NetworkError, httpx.HTTPStatusError) as exc: retryable = ( not isinstance(exc, httpx.HTTPStatusError) or exc.response.status_code in RETRYABLE_STATUS ) if not retryable or attempt == max_attempts - 1: raise max_delay = min(0.5 * (2 ** attempt), 2.0) await asyncio.sleep( random.uniform(0, max_delay) ) This demonstrates bounded retries with full jitter.
It assumes the provided client has configured connection and I/O timeouts.
For production use, I'd also honor Retry-After where applicable, put the entire operation inside a deadline, and avoid repeating retry logic at multiple layers.
The delays shown are examples, not recommended production values.
Even with backoff, retrying without a total deadline can make users wait much longer than expected.
7. Sometimes a Fallback Is Better Than Another Retry
Consider a product page that displays estimated delivery times from a shipping provider.
If that provider becomes unavailable, should the entire product page fail?
Probably not.
The application might return the product details without the delivery estimate.
{ "product": { "id": 42, "name": "Wireless Keyboard" }, "shipping_estimate": null, "shipping_status": "temporarily_unavailable" } This is graceful degradation.
The primary functionality remains available while a noncritical feature is temporarily unavailable.
However, not every dependency can be optional.
If a checkout system cannot confirm inventory or calculate the correct total, continuing with guessed values may create bigger problems.
The decision depends on business risk.
A good rule is:
- Fail closed when missing information could cause incorrect financial transactions, authorization decisions, or irreversible actions.
- Degrade gracefully when missing information affects a noncritical feature and the product can communicate that limitation clearly.
A fallback isn't necessarily a cached or approximate value. Sometimes returning an explicit unavailable state is the safest choice.
8. Measure the Right Metrics
Average API latency is useful, but it doesn't show the full picture.
A service might have excellent average response times while a small percentage of requests take several seconds.
Those slow requests are often the ones customers notice.
For dependency reliability, I'd monitor:
| Metric | What it reveals |
|---|---|
| p95/p99 latency | Slow requests hidden by averages |
| Timeout rate | How often operations exceed their budget |
| Retry rate | How much additional work is being generated |
| Connection pool wait | Whether callers are waiting for connections |
| In-flight requests | How many requests are consuming resources |
| Fallback rate | How often a feature runs in degraded mode |
I'd also track latency and failure rates by dependency.
Otherwise, an overloaded shipping service may appear as a general checkout performance problem.
When setting timeout values, use real latency distributions and the caller's overall response-time budget.
Setting every timeout to an arbitrary number can create unnecessary failures or allow requests to wait too long.
9. How I'd Test This Before Production
Timeout and retry behavior should be tested under controlled failure conditions, not just successful responses.
I'd simulate a downstream service that:
- Responds normally.
- Delays its response beyond the configured timeout.
- Returns HTTP 503 several times before recovering.
- Remains unavailable throughout the retry budget.
- Accepts a request but loses the response.
Then I'd verify that the API stays within its intended deadline, retries only eligible operations, and doesn't continue consuming excessive resources after failure.
For write operations, I'd also verify that the same logical request cannot create duplicate side effects.
Load testing matters here.
A retry policy that works with one user can behave very differently when hundreds of requests fail simultaneously.
The goal isn't to prove the system never fails.
It's to make sure a partial failure stays contained instead of becoming a larger outage.
Final Thoughts
Reliable APIs need more than fast database queries and efficient application code.
They also need predictable behavior when dependencies slow down or fail.
Three lessons are worth remembering:
- Set an overall deadline, not just individual timeouts. Every dependency call needs to fit within the request's available time budget.
- Be selective with retries. Retry only appropriate failures, with bounded attempts and backoff.
- Design for partial failure. A slow or unavailable dependency shouldn't automatically take down unrelated functionality.
Retries can improve reliability, but only when they're used carefully.
Sometimes the most important optimization is knowing when to stop waiting.
