← Building blocks

Never wait forever

Reliability & failure handlingfundamental

A hung downstream call ties up threads until the whole service stalls.

Say it like this

Every network call gets a timeout shorter than the deadline of whoever called me, and the deadline travels with the request, so a hung dependency costs one thread for a bounded time instead of the whole pool forever.

Basic solution

Set a timeout on every network call, shorter than the caller’s own deadline, and propagate deadlines.

connect / read timeoutsgRPC deadlinescontext cancellation

A deadline that shrinks at every hop

The gateway sets 300 ms. Each service gives the next call the smaller of that dependency's budget and the time it has left, and forwards that as the deadline, so no hop waits longer than its caller will.

How it works

  1. The entry point (the gateway or the first service) assigns the request a deadline: the current time plus the latency objective for that endpoint, say 500 ms. Everything downstream works inside that deadline.
  2. Before each outbound call the service computes a timeout for it: the smaller of the dependency's normal budget (tuned to its p99) and the time left until the deadline, minus a margin for the work it must still do after the call returns.
  3. The service forwards the deadline in a header (grpc-timeout, or a custom X-Deadline) so the downstream service can run the same arithmetic for its own calls, and nobody waits longer than the original caller will.
  4. When a timeout fires, the client actively cancels: it closes the connection or cancels the request context, which frees the thread or coroutine immediately. It does not keep waiting for a reply that may still come.
  5. The caller then decides what to do with the time left: retry if the retry budget and the deadline allow, or return a degraded or error response before the user gives up.

Set three different timeouts

  • Connect: how long to wait to establish the TCP or TLS session, which is tens of milliseconds within a region. A dead host that drops packets would otherwise hang here for minutes.
  • Request or read: how long to wait for the response once connected, set near the dependency's p99.
  • Overall deadline: the cap on everything for this request, including every retry.

Worked example

Feed read with an SLO of 300 ms at p99

  • Deadline: 300 ms. Timeline cache ZREVRANGE: p99 2 ms, timeout 20 ms. Ranking service: p99 60 ms, timeout 100 ms. Post hydration MGET: p99 5 ms, timeout 30 ms. User cache: timeout 30 ms. Sum of timeouts 180 ms, leaving margin for serialisation and the two network hops.
  • Thread pool arithmetic without timeouts: 200 threads, ranking service hangs. At 2,000 req/s every thread is stuck within 100 ms and the service answers nothing, including requests that never needed ranking.
  • With a 100 ms ranking timeout: each stuck call holds a thread 100 ms, so 2,000 req/s × 0.1 s = 200 threads busy. Still saturated, which is why the breaker opens after a few seconds and ranking is skipped (chronological fallback) until it recovers.
  • Propagation: the ranking service receives deadline 100 ms and sets its own feature-store timeout to 60 ms, so it never does work the caller has already abandoned.

Variants and when each wins

Static per-dependency timeouts

  • A fixed value per dependency, tuned to its p99. It wins on simplicity and predictability; it ignores how much of the overall budget earlier calls already spent.

Deadline propagation

  • Each hop forwards the time remaining, and every service sizes its own calls from that. It wins by preventing work that nobody will consume; it needs every service in the chain to honour the header.

Adaptive timeouts

  • The timeout tracks a rolling p99 of the dependency's recent latency. It wins when latency varies by time of day; the risk is that it creeps upward during a slow period and hides a regression.

Hedged requests

  • Instead of waiting for the full timeout, send a second copy of the request after the p95 latency has passed and take whichever reply arrives first. It wins for latency-critical idempotent reads, cutting the tail at the cost of a few percent extra load.

Static timeouts plus deadline propagation is the baseline; add hedging for latency-critical idempotent reads.

Failure modes

Timeout longer than the caller's

  • The user received a 504 but the backend kept working on their request for ten more seconds. It happens because the downstream timeout was larger than the upstream one, so the upstream gave up first and the downstream never knew. Make deadlines shrink at every hop so no service waits longer than its caller.

No connect timeout

  • Calls to a dead host hang for two minutes. It happens because only a read timeout was set, and a host whose IP drops packets never completes the connection, so the operating system's default connect timeout applies. Set an explicit connect timeout of tens of milliseconds within a region.

Timeout without cancellation

  • Threads are freed on timeout, but the database keeps executing the abandoned queries and stays overloaded. It happens because the client stopped waiting but never told the server to stop. Cancel the request context, close the connection, and set a statement timeout on the database side so it kills queries nobody is waiting for.

Timeout treated as failure of the remote

  • A payment is charged twice. It happens because the first call completed on the server after the client had timed out, and the retry ran it again. Use an idempotency key on every write, or query the outcome before retrying.

Timeouts set by folklore

  • Every call has a 30-second timeout. It happens because nobody measured the dependencies and a default was copied everywhere. Set each timeout from the dependency's p99 metrics and review it whenever the dependency changes.

Interviewer follow-ups

Answer out loud before you open each one.

How do you pick the number?

Start from the dependency’s p99 under normal load and add a margin, then check it fits inside the caller’s remaining deadline. A timeout well above p99 only protects against hangs; one near p50 turns normal variance into failures.

What do you return when a call times out?

Whatever keeps the user moving: a cached or default value for non-critical data, an error for critical writes. Decide this per call site in advance; the timeout is only useful if there is a defined fallback behind it.

How do deadlines interact with retries?

The deadline bounds the sum of all attempts. Before each retry check that the remaining time fits another full attempt plus backoff; if not, stop. Otherwise the last retry starts with 5 ms left and is guaranteed to fail.

Why is a timed-out request still dangerous for the server?

Because the server may still be executing it: the query runs, the row is written, the email is sent. Cancellation must reach the server (statement timeouts, cancellable contexts) and side effects must be idempotent so a retry is safe.

Connections

In study paths
Making retries safe
Pairs with
Retry transient failures carefully · Stop calling a failing dependency · Degrade instead of failing · Measure p95 / p99, not the average · Make retries safe

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayGatewayAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon EC2 Auto ScalingFeed serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon SageMakerRanking serviceVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton