Sub topic 4
Timeouts: Bounding the Cost of Waiting
A dependency that returns an error is easy to handle. A dependency that never answers is harder, because your code waits and holds resources while it does. A timeout turns that open-ended wait into a bounded cost, and it is the first tool in this tutorial that makes a fallback possible. A fallback can only run once the call has been declared failed.
This chapter assumes you can write a service that calls other services over HTTP, that you know how exceptions work, and that you know what latency percentiles (p50, p99) mean. Later chapters cover retries, circuit breakers, and the fallbacks themselves. Here the focus is how to choose, layer, and enforce timeouts.
Why slow is worse than down
When a dependency is down, connections are refused and calls fail in milliseconds. When it is slow, each call holds a thread, a socket, and a connection-pool slot until it returns. Little's law gives the number of requests in flight at any moment:
in-flight requests = arrival rate × time each request spends waiting
Suppose your service gets 200 requests per second and each needs one call to a dependency that normally answers in 50 ms. About 10 requests are in flight. Now the dependency starts hanging.
| Timeout | In-flight requests at 200 req/s | Effect |
|---|---|---|
| 50 ms (healthy latency) | 10 | Normal operation |
| 500 ms | 100 | Pressure, but recoverable |
| 30 s | 6000 | Worker pool and memory exhausted |
| None | Grows without limit | The whole service stops, including features that do not use the dependency |
The last row is how a slow optional dependency turns into a full outage. Every worker ends up parked on the slow call, and requests that never touch the dependency have no worker left to run on.
What a timeout is, and which kinds exist
A timeout is a limit on how long you wait for one step. Most client libraries expose several limits, and they guard against different failures.
| Timeout | What it bounds | Typical failure it catches |
|---|---|---|
| Connect timeout | Establishing the TCP (and TLS) connection | Host unreachable, packets dropped, overloaded listener |
| Read timeout | Waiting for the next bytes from the peer | Dependency accepted the request but is stuck |
| Write timeout | Sending the request body | Peer not draining its receive buffer |
| Pool acquisition timeout | Waiting for a free connection from your own pool | Pool exhausted by slow calls |
| Total timeout (deadline) | The whole operation from start to finish | Slow-drip responses, many small waits adding up |
Two points about this table matter in practice.
First, a read timeout usually restarts each time bytes arrive. A server that sends one byte every few seconds can keep a read timeout from ever firing. If your library offers a total timeout, set it. If it does not, enforce a deadline yourself (shown below).
Second, the pool acquisition timeout is the one people forget. If every connection in your pool is held by a slow call, new callers queue for a connection. Without a limit on that queue, the wait is unbounded even though each individual socket has a timeout.
Many HTTP clients have no timeout by default. Python's requests library, for example, waits indefinitely unless you pass timeout=. Treat "no timeout" as a bug to find in code review, not as a neutral default.
Choosing a value
A timeout that is too long gives you the exhaustion problem above. One that is too short turns normal latency spikes into errors and fallbacks. Pick values from data and from the request's budget, not by feel.
- Start from healthy latency. Measure the dependency's latency percentiles under normal load. A common starting point is a little above p99 or p99.9, for example 2 to 3 times p99. Below p99, you deliberately fail 1% or more of healthy calls.
- Cap it by the caller's budget. If your endpoint promises a response within 1 second, the sum of all waits on the critical path must fit inside that second, with room for your own processing.
- Treat optional dependencies more tightly than critical ones. If a feature can be dropped, spending a large share of the budget waiting for it is a poor trade. Give it a short timeout and fall back early.
- Account for retries. Three attempts with a 300 ms timeout each can take 900 ms plus backoff delays. The timeout for one attempt and the number of attempts have to be chosen together.
- Revisit after incidents and launches. Latency distributions change as data grows.
A worked budget for a home page with a 1 second target:
| Step | Role | Timeout | Notes |
|---|---|---|---|
| Session lookup | Critical | 150 ms | p99 is 60 ms. Failure means the request fails. |
| Account data | Critical | 250 ms | p99 is 100 ms. |
| Recommendations | Optional | 300 ms | p99 is 120 ms. Failure means fallback. |
| Own processing and rendering | n/a | about 100 ms | Reserved headroom. |
If the three calls ran one after another, the worst case is 700 ms of waiting plus 100 ms of work, which fits in 1 second. If they run in parallel, the worst case is the longest single timeout, and you have extra headroom you could use for one retry.
Enforcing a deadline
A deadline is an absolute point in time by which the whole request must finish. Each call receives only the time that remains, so waits cannot add up past the budget. Use a monotonic clock for this, because wall-clock time can jump when the system clock is adjusted.
The following program is complete and runs with only the standard library. It starts a local server that takes 2 seconds to respond, then calls it with a 0.4 second deadline and a 0.3 second per-call cap.
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class SlowHandler(BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(2) # simulate a stuck dependency
try:
self.send_response(200)
self.end_headers()
self.wfile.write(b"ok")
except (BrokenPipeError, ConnectionResetError):
pass # the client already gave up
def log_message(self, *args):
pass
class Deadline:
def __init__(self, seconds):
self.expires_at = time.monotonic() + seconds
def remaining(self):
return max(0.0, self.expires_at - time.monotonic())
def fetch(url, deadline, per_call_cap=0.3):
timeout = min(per_call_cap, deadline.remaining())
if timeout <= 0:
raise TimeoutError("deadline already exceeded")
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.read()
except urllib.error.URLError as exc:
# Connect timeouts arrive wrapped in URLError.
if isinstance(exc.reason, TimeoutError):
raise TimeoutError("connect timed out") from exc
raise ConnectionError(str(exc.reason)) from exc
if __name__ == "__main__":
server = ThreadingHTTPServer(("127.0.0.1", 0), SlowHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_address[1]}/"
deadline = Deadline(0.4)
started = time.monotonic()
try:
fetch(url, deadline)
except TimeoutError as exc:
print(f"{exc} after {time.monotonic() - started:.2f}s")
server.shutdown()The program prints a line such as timed out after 0.30s. Two details are worth noting. The check timeout <= 0 happens before the call, because a timeout of 0 in Python sockets means non-blocking mode, not "give up immediately". And the function raises TimeoutError and ConnectionError, the same exceptions the get_recommendations fallback in the spine's first example catches. The timeout is the trigger that sends the code down the fallback path.
In Python 3.10 and later, socket.timeout is an alias of TimeoutError, so a read timeout surfaces as TimeoutError directly. The connect case needs the unwrapping shown above. Other languages and libraries have similar quirks, so test what your client actually raises.
Passing the deadline downstream
If your service calls another service that calls a third one, each hop should know how much time is left. Otherwise the third service may spend 5 seconds on a request whose caller gave up after 1 second. This is wasted work, and under load it deepens the overload.
- gRPC propagates deadlines for you. Set one on the call and servers see the remaining time.
- With plain HTTP, there is no universal standard. Teams commonly send the remaining budget in a custom header, such as
X-Request-Timeout-Ms, and have each service subtract its own elapsed time before calling onward. - Every hop should use a timeout that is shorter than its caller's. If the caller waits 500 ms and the callee waits 800 ms on its own dependency, the caller has already given up and the callee's work is thrown away.
Edge cases and common errors
A timeout does not cancel remote work. When your client stops waiting, the server may keep processing. For reads this only wastes capacity. For writes it creates ambiguity: the payment may have been charged even though you saw a timeout. A timed-out write has an unknown outcome, not a failed one. Use idempotency keys so that a later retry or reconciliation does not apply the operation twice. Do not substitute a default value for a write that may have succeeded.
A timeout does not always free your resources. In threaded code, giving up on a call frees the caller only if the socket itself has the timeout. Wrapping a blocking call in a "timeout" that abandons the thread leaves the thread blocked. In async code, cancellation must actually propagate to the awaited operation, and the connection must be closed or returned to the pool in a clean state.
Timeouts that are too uniform cause synchronized failure. If thousands of clients share the same timeout and all start waiting at the same moment, they all fail and retry at the same moment. Jitter on retries, covered in the next chapter, addresses this.
Tuning timeouts to the worst case hides problems. Raising a timeout from 300 ms to 5 s because "the dependency sometimes takes 4 s" removes the errors from your dashboard but moves the cost into held workers. Raise a timeout only if the slow calls are valuable and you have capacity to wait. Otherwise fix the dependency or degrade.
Timeouts need to be visible. A timeout that silently triggers a fallback looks like success. Count timeouts per dependency and report whether a response was degraded, as the spine's fallback example does with its degraded flag. A later chapter covers this in detail.
Putting it together
A practical checklist for each outbound call:
- Set connect and read timeouts explicitly. Set a total deadline if the client supports one, or enforce it yourself.
- Bound the wait for a pool connection.
- Derive the value from measured p99 latency and the caller's remaining budget.
- Pass the remaining budget to the callee when you can.
- Decide in advance what happens when the timeout fires: fail the request for a critical dependency, or use a fallback for an optional one.
- Emit a metric and a log field every time it fires.
Exercise
An endpoint receives 100 requests per second. Each request calls a dependency, and your service has 20 worker threads. The dependency starts hanging. Using in-flight = rate × wait time, how long does it take to exhaust the workers if the timeout is 10 s, and what is the largest timeout that keeps the pool from being exhausted by this one dependency?
Show answer
With a 10 s timeout, requests accumulate at 100 per second, so all 20 workers are occupied after about 20 / 100 = 0.2 s, and every other request on the service stalls. To stay within 20 workers, in-flight = 100 × timeout must be below 20, so the timeout must be under 0.2 s (200 ms). That value is probably too tight for a normal dependency, which shows why a timeout alone is not enough and why bulkheads (a separate worker pool per dependency) are covered later.
Exercise
Your checkout service calls a payment provider with a 2 s read timeout. The call times out. A teammate proposes returning "payment failed" and letting the user click Pay again. What is wrong with this, and what should you do?
Show answer
A timeout means the outcome is unknown. The provider may have completed the charge after your client stopped waiting, so a second click could charge the user twice. Send an idempotency key with each payment attempt so repeated requests with the same key are applied once, and check the payment status before telling the user it failed.