Sub topic 4
Timeouts: bounding the cost of waiting
This chapter assumes you have built a service that calls other services or databases over a network, that you know how exceptions work in your language, and that you understand latency and availability. It covers how to set timeouts so that a slow dependency cannot take your service down with it.
Why waiting is expensive
A failing dependency that returns an error quickly is easy to handle. A dependency that responds slowly, or never, is harder. Your service still holds a thread, a connection, and memory for every request that waits on it.
Suppose a service handles 200 requests per second and has a pool of 100 worker threads. Normally each request takes 50 ms, so about 10 threads are busy. If a dependency starts hanging and every request waits 30 seconds, the pool fills in under a second. After that, even requests that do not need the dependency are queued behind the stuck ones. One slow optional feature has caused a full outage.
A timeout sets an upper limit on how long you wait. When the limit passes, you stop waiting, release the resources, and take a different path, such as a fallback.
Kinds of timeouts
Most clients expose more than one timeout. They protect against different problems.
| Timeout | What it limits | Typical failure it catches |
|---|---|---|
| Connect timeout | Time to establish the connection | Host down, network partition, full backlog |
| Read (or response) timeout | Time waiting for data after the request is sent | Overloaded server, slow query |
| Total (deadline) timeout | Time for the whole operation, including all steps | Slow trickle of data, many retries |
| Pool acquire timeout | Time waiting for a free connection from a pool | Pool exhausted by slow calls |
A read timeout usually resets each time bytes arrive. A server that sends one byte every few seconds can keep a read timeout from ever firing. A total timeout closes that gap, so set one when the library supports it.
Many libraries default to no timeout at all. Check the default for every client you use. In Python, for example, the requests library waits forever unless you pass timeout=.
Choosing a value
A timeout is a trade-off. Too long, and you waste resources on calls that will not succeed. Too short, and you cancel calls that would have succeeded, which adds load and causes false failures.
A practical method:
- Measure the dependency's latency under normal load, using percentiles instead of the average.
- Start near the 99th or 99.9th percentile. If p99 is 120 ms, a limit of 300 to 500 ms is a reasonable first guess.
- Check it against your own budget. If your service promises a response in one second, the sum of all downstream waits must fit inside that.
- Use a tighter timeout for optional dependencies than for critical ones. Dropping a recommendation widget after 200 ms is cheaper than failing a checkout.
- Revisit the value when traffic or the dependency changes.
Deadlines across a call chain
When service A calls B, and B calls C, each hop having its own 2-second timeout is a mistake. A may give up after 2 seconds while B and C keep working on a result nobody will read. A better approach is to pass a deadline down the chain, and have each service use only the time that remains.
import time
class DeadlineExceeded(TimeoutError):
pass
class Deadline:
def __init__(self, seconds):
self.expires_at = time.monotonic() + seconds
def remaining(self):
left = self.expires_at - time.monotonic()
if left <= 0:
raise DeadlineExceeded("no time left for this call")
return left
def handle_request(fetch_profile, fetch_recommendations):
deadline = Deadline(1.0) # whole request must finish in 1 second
profile = fetch_profile(timeout=min(0.4, deadline.remaining()))
try:
recs = fetch_recommendations(timeout=min(0.3, deadline.remaining()))
except TimeoutError: # DeadlineExceeded is a subclass
recs = []
return {"profile": profile, "recommendations": recs}Each call gets the smaller of its own limit and the time left. The optional call catches the timeout and returns an empty list, while the critical profile call lets the error propagate. This is the pattern used by gRPC deadlines and by request context timeouts in many frameworks.
Common errors
- No timeout set. The library default is often infinite. Set it explicitly.
- Timeout longer than the caller's timeout. The caller gives up first, and your work is wasted.
- Only a read timeout. A slow trickle of data can still hold a worker. Add a total limit.
- Retrying without a budget. Three retries with a 2-second timeout can take over 6 seconds. The next chapter covers retries. Count them against the total deadline.
- Treating a timeout as a failure of the operation. For writes, a timeout means the outcome is unknown. The server may have completed the work. Use idempotency keys before you retry a write.
- Wall-clock time for measuring. Use a monotonic clock, as in the example above, so clock adjustments do not shorten or extend the wait.
Exercise
Your service has a 1-second response budget. It calls a critical database (p99 of 80 ms) and an optional recommendation service (p99 of 150 ms). A teammate sets both client timeouts to 5 seconds "to be safe". Describe two problems with this and propose better values.
Show answer
First, 5 seconds exceeds the 1-second budget, so the caller has already given up when the timeout fires, and a hung dependency still ties up workers for 5 seconds each, which can exhaust the pool. Second, giving the optional service the same limit as the critical one lets a non-essential feature consume as much waiting time as an essential one. Better values: about 250 ms for the database (a few times its p99, well inside the budget) and about 200 to 300 ms for recommendations, with a fallback of an empty list or cached results. Pass a shared 1-second deadline so each call uses the smaller of its own limit and the time remaining.