AI Hints
Home›System Design Tutorial›Services and Timeouts
System Design · Lesson 78 of 120

Timeouts

Never wait forever.

⏱ 2 min read▶ Video at 1:33:46🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Timeouts
From the video: Timeouts
  • 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.

timeout.pypython
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)
Output
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.

keyvalue
Every callhas a timeout
Based onp99 latency
Too longthreads pile up
Too shortgood 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
Next up: Retries and Backoff — try again, politely