AlgoViz

Timeouts

easy 30 min

A 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

PhaseTakesClock after
1Connecting0.5 s0.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

BuyerShopwaits 1 sPayment companyworking

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

    critical

    The library does not set one. The call can hold its thread for ever.

    Wrong
    requests.get(url)
    Right
    requests.get(url, timeout=(0.5, 2))
  • The inner limit is longer

    critical

    Orders gives up after 2 seconds while payments still works, and charges a customer who has seen an error.

    Wrong
    orders_limit = 2payments_limit = 5
    Right
    payments_limit = 1orders_limit = 2 * payments_limit + 0.2 + 0.3
  • Inventing time

    major

    With half a second left, max() hands out a whole second. The old code did this.

    Wrong
    child = max(left - 2.0, 1.0)
    Right
    child = left - RESERVEif child < NEED: raise DeadlineExceeded
  • A race that leaves the work running

    major

    The promise loses the race but goes on using the connection.

    Wrong
    Promise.race([fetch(url), timer(500)])
    Right
    fetch(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.