Timeouts
easy 30 minA timeout is the longest time you are willing to wait for something.
See it run
Where a call waits, what a limit protects, and how one deadline stops a whole chain.
Operations
One call, limit 5 s
A call with a total limit of 5 seconds, first on a good day, then when the server hangs.
Step 1 of 5
Connecting
| Phase | Takes | Clock after | |
|---|---|---|---|
| 1 | Connecting | 0.5 s | 0.5 s |
| 2 | |||
| 3 | |||
| 4 |
0.5 seconds to open the connection. Far below a connect limit of 3 seconds.
Step 1: Connecting
requests.get(url, timeout=(3, 10)) # 3 s connect, 10 s silenceasync with asyncio.timeout(5): # everything together response = await client.get(url)- Protects
- The caller
- Costs
- Some wrong cuts
- No limit
- waits as long as the server likes
Connect and read limits guard single phases. Only a total limit bounds the sum.
In the real world
The same timeouts doing real jobs. Pick one and step through it.
A charge times out. Was the card charged?
Step 1 of 4
The call
known
order 7 sent
The shop asks for 20 dollars with a limit of 1 second and the key order-7.
Step 1: The call
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No timeout at all
criticalThe library does not set one. The call can hold its thread for ever.
Wrongrequests.get(url)Rightrequests.get(url, timeout=(0.5, 2))The inner limit is longer
criticalOrders gives up after 2 seconds while payments still works, and charges a customer who has seen an error.
Wrongorders_limit = 2payments_limit = 5Rightpayments_limit = 1orders_limit = 2 * payments_limit + 0.2 + 0.3Inventing time
majorWith half a second left, max() hands out a whole second. The old code did this.
Wrongchild = max(left - 2.0, 1.0)Rightchild = left - RESERVEif child < NEED: raise DeadlineExceededA race that leaves the work running
majorThe promise loses the race but goes on using the connection.
WrongPromise.race([fetch(url), timer(500)])Rightfetch(url, { signal: AbortSignal.timeout(500) })
Interview tips
How to explain it
- A limit on waiting protects threads.
- The number comes from measured latency.
- In a chain, one deadline.
Memory trick: TIME OUT
- TCP connect, Individual, Monitor.
- Err on neither side.
- Order, Use deadlines, Test.
Three checks
- Above p99.9?
- Rate x limit below the pool?
- All attempts inside the deadline?
After a timeout
- A read: ask again, gently.
- A write: unknown, use the key.
- Cancel what is still running.