Course contents

09. Reliability and Resilience Lesson 1 of 10

Timeouts

Watch a slow database exhaust an API’s workers, then see how timeouts fail fast, how to pick the value from P99, and why deadlines must propagate.

13 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A worker waiting on a dependency is busy; without a timeout a slow dependency can hold every worker.
  • Then requests that do not even need that dependency queue behind it.
  • A timeout bounds the hold time: a fast failure for some requests instead of a slow failure for all.
  • Pick the value above the healthy P99 (or P99.9), far below "forever"; never below the P99.
  • Inner timeouts must fit inside outer ones; propagating the deadline does this automatically.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A timeout is the longest a caller is willing to wait for an operation before it gives up and treats the operation as failed. Every remote interaction has several waits that can each hang: opening a connection, getting a connection from a pool, sending the request, and waiting for the answer. A timeout puts an upper bound on each of them, or on all of them together.

Why it exists

A caller that waits is not idle. A thread, an async task, a socket and some memory stay reserved while the call is outstanding. If a dependency slows down and nothing limits the wait, those resources stay reserved for as long as the dependency takes, and new requests have to queue for them. Little’s law makes the effect concrete: concurrency = arrival rate × time held. Hold each worker ten times longer and you need ten times the workers for the same traffic. When the workers run out, the caller is effectively down, including for requests that never needed the slow dependency. That is how one slow component turns into a cascading failure.

A dependency that is down is usually less dangerous: the connection is refused at once and the caller learns quickly. Slow is the hard case, and timeouts exist mostly for it.

How it works

Kinds of timeout. A connect timeout limits establishing a TCP/TLS connection (usually short: tens to a few hundred milliseconds inside a data centre). A request or read timeout limits waiting for the response. A pool acquire timeout limits waiting for a free connection in a client-side pool; library defaults here are often long (30 s is common). A statement timeout on the database side cancels a query that runs too long. An overall deadline limits the entire operation, including retries.

What happens on expiry. The caller stops waiting, frees its resources and reports a failure (an error, a fallback, or a retry if the operation allows it). The other side is not informed unless something tells it: the request may still be queued or running downstream.

Choosing the value. Measure the dependency’s latency distribution when it is healthy and pick a value above its high percentiles, for example a bit above P99.9, or about two to three times P99, then check what that means for capacity: with W workers and a timeout T, a fully hung dependency still lets the caller finish about W / T requests per second. A timeout below the healthy P99 fails at least 1% of perfectly good requests, usually the slowest and often the most valuable ones (big carts, large reports).

Deadline propagation. Instead of a fixed timeout per hop, the first service sets an absolute deadline and every call passes the remaining budget downstream. A service that receives a request whose deadline has passed does not start it; a service whose budget runs out mid-way cancels its own downstream calls. gRPC sends a deadline with every call, and a server that passes the incoming call’s context to its own outgoing calls propagates it; with HTTP, services pass the remaining budget in a header and check it themselves.

When to use it

  • On every call that crosses a process boundary: HTTP and gRPC calls, database queries and connection acquisition, cache and queue clients, DNS lookups, calls to third-party APIs.
  • On the client side of any user-facing request, so users get an answer (even an error) in bounded time.
  • Together with retries and circuit breakers: the timeout produces the failure signal the other two act on.

When not to

  • Do not use a short timeout for work that is legitimately long (a large export, a batch job). Make such work asynchronous: accept it, return a job id, and let the client poll or be notified.
  • Do not rely on a timeout to protect against overload you could prevent: if a dependency is routinely near its limit, fix capacity or shed load.
  • Avoid a timeout that cancels a non-idempotent operation and then retries it blindly (see the Retries lesson).

Trade-offs

Choice You gain You pay
Short timeout Workers are freed quickly; slow dependencies cannot drag the caller down Healthy-but-slow requests fail; more false failures during brief latency spikes
Long timeout (or none) Few false failures A slow dependency can hold every worker; users wait a long time for an error
Fixed per-hop timeouts Simple to configure Inner hops can outlive the caller; work continues after the user left
Propagated deadline Every hop works only within the remaining budget Needs support in every service and client library
Adaptive timeouts (from live percentiles) Follow real latency Can drift upward during a slow degradation; harder to reason about

Alternatives

  • Circuit breakers fail calls without waiting at all once a dependency is clearly failing; they need timeouts to detect slowness in the first place.
  • Bulkheads cap how many workers one dependency may use, so even a long wait cannot exhaust the whole pool.
  • Asynchronous processing takes the slow work off the request path entirely.
  • Hedged requests send a second copy after a short delay (for example at P95) and use whichever answers first; they cut tail latency at the cost of extra load and only suit idempotent reads.
  • Adaptive concurrency limits shrink the number of in-flight calls when latency rises.

Failure modes

  • Missing timeouts: library defaults that are infinite or very long (socket reads, pool waits) are the classic root cause of thread-pool exhaustion.
  • Inner longer than outer: an API waits 5 s for a dependency while the user gave up after 2 s; the remaining 3 s are wasted work.
  • Timeout below the healthy tail: a constant trickle of failures, often hidden by retries that double the load.
  • Timeout plus aggressive retries: every timeout produces another call to the dependency that is already slow, a retry storm.
  • Timeout only on the request, not on the connection or the pool: the call hangs before the request timeout even starts counting.

In production

Set connect, request and pool timeouts explicitly in every client; do not trust defaults. Derive values from measured latency (dashboards of P99 and P99.9 per dependency) and revisit them when the dependency changes. Give each user-facing request an overall budget and pass it down, with gRPC deadlines or a header the services respect, and make servers check the remaining budget before starting expensive work. Count timeouts per dependency as a metric and alert on them. Test with injected latency, not just injected errors: a dependency that answers in 10 s reveals missing timeouts that a dead dependency never will.

Common misconceptions

  • "A timeout stops the work." It stops the waiting. The server keeps working unless cancellation or a deadline reaches it.
  • "A long timeout is the safe choice." A long timeout is what lets a slow dependency take down the caller.
  • "Set it to the average latency plus a bit." Averages hide the tail; choose from high percentiles.
  • "If the dependency is down, timeouts matter most." A dependency that refuses connections fails fast; timeouts matter most when it is slow.

Interview angle

When a design has a synchronous call chain, say where timeouts go and how they relate: the user-facing timeout is the outer budget, each downstream call gets less, ideally through a propagated deadline. Show the capacity argument (workers / timeout = the throughput left when a dependency hangs) and how you choose the value from P99 or P99.9. Then connect it to retries (only idempotent operations, with backoff) and circuit breakers (stop waiting entirely when failures persist).

Model assumptions

The simulation is a simplified model, not a benchmark. Users send 60 requests per second (Poisson) to an API with 12 workers, 15 ms of own work per request (lognormal, cv 0.3) and room for 60 waiting requests. The API checks a product cache first, modelled as a fixed 60% hit ratio; a miss reads the inventory database with 2 connections and 40 ms per query (lognormal, cv 0.4). An API worker is held for the whole request, including waits. "Slow" makes the database 4× slower. The engine models two timeouts: the users’ end-to-end timeout and the API’s wait for a database connection; a query that has started always runs to completion (no statement timeout, no cancellation), and a request whose user timed out is still processed. Deadline propagation is not modelled: that step is a scripted illustration with live traffic paused. Latency figures count successful requests only. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A request holds a worker until it is done

    Users send 60 requests a second to an API with 12 workers. Each request checks a product cache first; 6 in 10 are answered there. The other 4 in 10 read the inventory database, which needs about 40 ms per query.

    A worker is busy for the whole request, including the time it waits for the cache or the database. Right now that is well under 100 ms, so only a few workers are busy and every request succeeds.

    Notice what is not configured: nobody has a timeout. The API would wait up to 30 seconds for a database connection, a common library default.

    Scene: Users send 60 requests per second to an API with 12 workers. Most are answered by the cache, the rest read the database. Few workers are busy, latency is low and nothing fails.

    Key idea: A worker waiting on a dependency is still a busy worker. Waiting is not free.

  2. 2. One slow dependency, everything queues

    One second in, the database becomes 4 times slower (a missing index, a lock, a noisy neighbour). It can now finish about 12 queries a second, but 24 cache misses arrive every second.

    The extra misses wait for a connection, and while they wait they hold API workers. Within a few seconds all 12 workers are stuck waiting on the database, the API’s queue fills up and new requests are rejected with 503.

    Now look at the median latency: it climbs past a second. Most requests are cache hits that never needed the database, yet they queue behind the ones that do. One slow dependency has taken the whole API down with it.

    Scene: The database slows down. Cache misses wait for a connection and hold API workers; all 12 become busy, the API queue fills and requests are rejected. Even cache hits now take over a second.

    Key idea: Without a timeout, a slow dependency borrows the caller’s workers indefinitely. Requests that do not even need it queue behind it.

  3. 3. A timeout gives the worker back

    The API now waits at most 150 ms for a database connection. A miss that cannot get one in time fails fast with an error, and its worker is free again.

    The database is still slow and some misses still fail; a timeout does not create capacity. But the API keeps its workers: cache hits flow again, throughput recovers to roughly the 36 hits plus the 12 queries the database can still serve, and the slowest successful request finishes in well under a second.

    That is the trade a timeout makes: a quick, clear failure for some requests instead of a slow failure for all of them.

    Scene: The API gives up on the database connection after 150 ms. Some misses fail quickly, but API workers stay available, cache hits are served again and latency drops back near normal.

    Key idea: A timeout bounds how long one dependency can hold your resources. It turns a slow failure for everyone into a fast failure for a few.

  4. 4. Choose the timeout from the latency you measure

    The database is healthy again. Now the users’ side gets a timeout too, and we have to pick a number. Healthy P99 here is about 150 ms.

    First try: 80 ms. That is below the P99, and below almost every cache miss. Watch the error rate: about 4 in 10 perfectly healthy requests are cut off, the cache misses, which are simply the slower ones.

    At 3 seconds the timeout becomes 300 ms, about twice the healthy P99. No healthy request is cut off any more, yet a request that is truly stuck is abandoned in well under a second.

    Scene: With a healthy database, users first time out after 80 ms and about 4 in 10 requests fail. At 3 seconds the timeout is raised to 300 ms and the errors stop.

    Key idea: Set a timeout from measured latency: comfortably above the healthy P99 (or P99.9), far below "forever". Never below the P99.

  5. 5. The user left, the work goes on

    The database is slow again. Users give up after 300 ms, the API still waits up to 150 ms for a connection, and a query that got one takes about 160 ms.

    So many misses outlive the user’s patience: the user has already seen a timeout, but the API worker keeps waiting and the database keeps running the query. When the answer finally arrives, nobody is listening. That is wasted capacity at exactly the moment capacity is short.

    The layers do not know about each other’s timeouts. The API does not know the user has only 300 ms in total.

    Scene: The database is slow again. Users time out after 300 ms, but the API and the database keep working on many of those requests and send answers nobody waits for.

    Key idea: Timeouts that do not know about each other let work continue after the caller has given up. Inner timeouts must fit inside outer ones.

  6. 6. Pass the deadline down

    *Scripted illustration: the simulator does not propagate deadlines, so live traffic is paused and the packets below are drawn by hand.*

    With deadline propagation the user’s request carries an absolute deadline ("answer by 12:00:00.300"). Each hop subtracts the time already spent and passes only the remaining budget downstream: the API has used about 40 ms and needs 20 ms to send its reply, so the database call gets about 240 ms.

    The slow query would take longer than that, so it is cancelled when the budget runs out and the API answers 504 right at the deadline. A request that arrives with its deadline already passed is not started at all. gRPC sends a deadline with every call; HTTP services typically pass the remaining budget in a header.

    Scene: Scripted: a request carries a 300 ms deadline. The API passes the remaining ~240 ms to the database; the query is cancelled when the budget runs out and the user gets a timely error.

    Key idea: Propagate the deadline, not a fixed timeout per hop: every layer works only within what is left of the caller’s budget.

  7. 7. Every remote call gets a timeout

    The database is healthy, users wait at most 300 ms, and the API waits at most 150 ms for the database, so the inner timeout fits inside the outer one.

    The rules: every remote call (HTTP, database, cache, queue) gets a timeout, connection and request alike. Choose it from measured latency, above the healthy P99. Inner timeouts are shorter than outer ones, or better, derived from a propagated deadline. And decide what a timeout means for the user: an error, a fallback, or a retry (next lesson).

    Scene: A healthy database, a 300 ms user timeout and a 150 ms database timeout: every request succeeds quickly.

    Key idea: A timeout is a capacity decision: it caps how long any one dependency may hold your workers.