Timeouts
Never wait forever.
The order service calls payment, and payment hangs. Without a timeout, the order service waits forever. Its threads fill up with stuck calls, and soon the order service stops answering too. One slow service has taken down two.

- Payment hangs
- Order waits forever
- Two services down
A call with a timeout
Always set a timeout on network calls. Here, a slow service takes three seconds, but we only wait for one. Run it. The call gives up after about one second, and we can show a friendly error, or try something else, instead of hanging.
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import time
def slow_payment():
time.sleep(3)
return "paid"
pool = ThreadPoolExecutor(1)
start = time.perf_counter()
try:
print(pool.submit(slow_payment).result(timeout=1))
except TimeoutError:
print(f"gave up after {time.perf_counter() - start:.1f} s")
pool.shutdown(wait=False, cancel_futures=True)gave up after 1.0 s
Choosing timeouts
How long should a timeout be? Base it on real latency. A little above the slowest normal response, like the P ninety nine. Too long, and stuck calls pile up. Too short, and good calls fail. And make sure a caller's timeout is longer than the timeouts of the services it calls.
| key | value |
|---|---|
| Every call | has a timeout |
| Based on | p99 latency |
| Too long | threads pile up |
| Too short | good calls fail |
Summary
Timeouts stop one slow service from freezing its callers. Set them on every network call, based on real latency. Next, trying again, politely.
Key takeaways- Never wait forever
- Base on p99
- Fail fast, recover