AlgoViz

Timeouts

easy 30 min

A timeout is the longest time you are willing to wait for something.

Video lesson · Chapter 1 of 5

Give the whole restaurant order one timer

0:00 / 4:22

Timeouts in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A timeout is a limit on waiting. When it passes, the caller stops, frees what it was holding, and handles the situation as a failure: it retries, falls back or reports an error.

One network call has several waits, and each can have its own limit: getting a connection from the pool, opening the connection, sending the request, waiting for bytes of the answer, and the whole call. A deadline is the same idea as a moment on the clock. It can be handed to the next service, so that a whole chain of calls stops together.

Why it exists

A network call can hang without any error. The machine at the other end may have lost power, a cable may be unplugged, or the process may be busy. The caller hears nothing, and nothing is not an error until somebody decides how long is too long.

Waiting costs something: a thread, a connection, memory, and a person in front of a screen. If calls arrive faster than they finish, these run out, and then healthy parts of the system stop as well.

A short history

  1. 1981

    RFC 793 defines TCP. It resends data after a retransmission timeout, and has a user timeout after which a connection is given up.

  2. 1989

    RFC 1122 sets requirements for internet hosts, including how TCP computes its retransmission timeout and backs off.

  3. 1997

    RFC 2068, the first HTTP/1.1, describes status 408 Request Timeout and 504 Gateway Timeout.

  4. 2011

    RFC 6298 restates the TCP timer: a smoothed round-trip time plus four times its variation, doubled after each timeout.

  5. 2013

    Dean and Barroso publish The Tail at Scale, about the rare slow answers that large systems meet all the time.

  6. 2014

    The Go blog introduces the context package, which carries deadlines and cancellation through a program's calls.

  7. 2018

    The gRPC team writes gRPC and Deadlines. Its short version: always set a deadline.

Words to know

Connect timeout
The limit for opening the connection, for example the TCP handshake.
Read timeout
The limit for waiting for data. In many libraries it is the longest silence between two pieces, not the length of the whole answer.
Write timeout
The limit for sending the request.
Pool timeout
The limit for getting a free connection from the pool.
Total timeout
The limit for the whole operation, from start to last byte.
Deadline
The moment by which the work must be finished. It can be passed on.
False timeout
Giving up on a call that would have succeeded a little later.
Cancellation
Telling the other side to stop, because nobody waits any more.

How it works

Step through the idea, or press Play.

Step 1 of 3

Limit each wait. Pool, connect, write, read, and the whole call

Understand it

Start here

The bus and the swimming lesson

Imagine waiting for a bus. If you never decide when to stop waiting, a bus that does not come takes your whole afternoon. If you leave after one minute, you walk on days when the bus was just around the corner. A good limit comes from two facts: how late the bus usually is, and when you must be there.

How long does Sam wait?
SWIMMINGbegins 3:30BUS3:00

Two facts set the limit: buses nearly always come within 8 minutes, and at 3:10 there are just 20 minutes left to walk.

With timeouts

  • Slow services are noticed quickly
  • Threads and connections come back after the limit
  • The rest of the system keeps answering
  • There is time left for a fallback

Without

  • Threads blocked for as long as the other side likes
  • The connection pool empties
  • Memory fills with waiting requests
  • The failure spreads to callers

The problem

How waiting uses everything up

Picture a service with five threads. Each takes a request, works a moment, and then calls a service that never answers. After five such requests all five threads are busy waiting. Request number six finds nobody.

Five threads, all waiting

One shop machine holds five threads. All five wait for a reviews service that does not answer. A new request from users finds no free thread.
The shop is healthy. It is full of people who wait.

What a limit is worth

most threads held=calls per second×timeout40×2=80,40×10=400\text{most threads held} = \text{calls per second} \times \text{timeout} \qquad 40 \times 2 = 80,\quad 40 \times 10 = 400
40 calls a second to a service that hangs. A limit of 2 s holds at most 80 threads, a limit of 10 s wants 400. With a pool of 200, the second limit is as good as none. Resilience shows the cascade that follows.

Kinds

One call, several waits

The phases of one call

Connect, write, the server's work, read. The total limit is drawn around them all.
TimeoutLimitsWhat it tells youCommon starting point
PoolWaiting for a free connection in your own processYour pool is too small, or calls are too slowShort: tens of milliseconds
ConnectTCP handshake (often the TLS handshake too, or it has its own)The host is down, unreachable or cannot acceptA few hundred ms in one region, 1 to 5 s across the internet
WriteSending the request bodyA slow network or a large uploadSeconds for small bodies. More for uploads
ReadSilence while waiting for dataThe server is slow or stuckFrom the measured latency. Many guides say 5 to 30 s, which is long for a person
TotalThe whole operation, retries includedThe safety net when each piece is just fast enoughWhat the caller can afford: 1 to 3 s for a person, longer for a job
If a server is healthy, connecting takes one round trip, so a connect limit may be short. A read limit must leave room for work.

Where your clients stand by default

  • Python requests

    No timeout unless you give one. Always pass timeout=(connect, read).

  • Python httpx

    5 seconds of network inactivity by default. Four separate limits: connect, read, write, pool.

  • Go net/http

    Client.Timeout of zero means no timeout. It covers the whole call including the body.

  • gRPC

    No deadline by default. Set one on every call.

  • axios

    timeout is one limit in milliseconds. It is 0, meaning none, unless you set it.

  • PostgreSQL

    statement_timeout is off by default. The server itself stops the query, which is what you want.

Ambiguity

What a timeout does not tell you

No answer in time. What happened?

The caller sees the same silence in all four cases.

So the caller may say "I do not know", never "it failed". A read can simply be asked again. A write needs a key that makes a second attempt harmless, which is idempotency. How to ask again is the subject of retries.

Choosing

Where the number comes from

Choosing a limit

Accept a share of wrong cuts

P(latency>T)=0.001;⇒;T=p99.92,000,000×0.001=2,000 wrong cuts a dayP(\text{latency} > T) = 0.001 ;\Rightarrow; T = p_{99.9} \qquad 2{,}000{,}000 \times 0.001 = 2{,}000 \text{ wrong cuts a day}
With a limit at p99.9, one good call in 1,000 is cut. Whether 2,000 a day is fine depends on what happens then: with one safe retry, most users notice nothing. The AWS Builders' Library describes the same method.

A little too long

  • Few wrong cuts
  • But threads are held for longer
  • And the user waits, then sees an error anyway

Too short

  • Good answers are thrown away after the work was done
  • Retries add load to a service that is only slow
  • A small slowdown becomes an outage

Limits to argue about

OperationCommon values (connect, read, total)For a person who waitsReason
Internal service1 to 2 s, 5 to 10 s, 15 s0.2 s, p99.9 plus room, under 1 sOne region: a healthy round trip is about a millisecond
External API3 to 5 s, 10 to 30 s, 60 s1 to 3 s, 2 to 5 s, or take it out of the requestNobody looks at a spinner for a minute. Use a queue
Database query2 to 3 s, 5 to 30 s, 30 s0.2 s, 1 s, with statement_timeoutReports get their own, longer limit and their own pool
User-facing API1 s, 3 to 5 s, 10 s1 s, 1 to 2 s, 2 to 3 sThe whole page must fit
The second column suits jobs and calls to other companies. The third is an assumption for a web page inside one region: replace it by your own measurements.

Strategies

Four ways to set a limit

StrategyHowGoodBad
StaticA fixed value from configurationSimple, predictableDoes not follow conditions, goes stale
Per operationA value for each kind of callFits search and checkout alikeMore configuration to keep true
AdaptiveComputed from recent latencyFollows the network, uses resources wellMore complex. A slow service can teach it to wait longer, so keep a ceiling
Deadline propagationThe remaining time travels with the requestAll services stop together, no wasted work, one clear budgetEvery service must pass it on and respect it
They combine: a per-operation limit, capped by the remaining time of the request.

An adaptive limit, as TCP does it

RTO=SRTT+4⋅RTTVAR100+4×50=300 msRTO = SRTT + 4 \cdot RTTVAR \qquad 100 + 4 \times 50 = 300 \text{ ms}
After a first measurement of 100 ms the average is 100 and the variation starts at half, 50. A second of 140 ms makes them 105 and 47.5, so 105 + 190 = 295 ms. Calm networks get short limits, shaky ones longer. TCP itself rounds up to at least 1 second in the standard.

Chains

Limits that fit inside each other

In a chain from A to B to C, the one nearer the user must wait longer: A longer than B, B longer than C. If B waits longer than A, B goes on working for a caller that has left.

A chain: 30, 20, 10, 5

Users reach a gateway that waits at most 30 seconds, then orders with 20 seconds, then payments with 10 seconds. Outside our system is the bank, with a limit of 5 seconds.
Each box shows how long the call into it may take, and is shorter than the one before it. The proportions are right. For a person, divide the numbers by ten.

The rule, with retries

TA;≥;n⋅TB+backoff+own work+room2×0.5+0.1+0.2+0.1=1.4 sT_A ;\ge; n \cdot T_B + \text{backoff} + \text{own work} + \text{room} \qquad 2 \times 0.5 + 0.1 + 0.2 + 0.1 = 1.4 \text{ s}
Two attempts of 0.5 s, one pause of 0.1 s, 0.2 s of own work, 0.1 s of room. Only direct calls count, because T_B already includes what is below B. Calls made one after another add up. For parallel calls take the longest.

Deadlines

One clock for the whole chain

A deadline travels with the request

Orders received 1.9 s, worked 0.6 s and kept 0.1 s for itself: 1.2 s for payments.

What each service does with a deadline

  1. 1

    Check at the door

    No time left, or less than this work needs? Refuse at once. Do not start.

  2. 2

    Keep a little for yourself

    Reserve time for your own last step and for the answer to travel.

  3. 3

    Pass the rest on

    Send the remaining time, not a moment of your clock, if the clocks of the machines may differ. gRPC sends the remaining time.

  4. 4

    Check again before expensive steps

    A queue may have eaten the time.

  5. 5

    Stop when it passes

    Cancel your own calls, close the query, release locks.

May this service start?

Code

Limits in real clients

Python
import asyncio, httpx, psycopg2, requests# requests: (connect, read). Without it, it waits for ever.r = requests.get("https://api.example.com/users/42", timeout=(0.5, 2))# httpx: four limits, and a total limit around everythinglimits = httpx.Timeout(connect=0.5, read=2.0, write=2.0, pool=0.1)async def fetch(url):    async with httpx.AsyncClient(timeout=limits) as client:        async with asyncio.timeout(3):          # Python 3.11 or newer            return (await client.get(url)).json()# PostgreSQL: the server stops the query itselfconn = psycopg2.connect("dbname=shop", connect_timeout=2,                        options="-c statement_timeout=1000")   # milliseconds
ConnectTimeout and ReadTimeout are different errors in requests. The first means the request was not sent, so trying again is safe.

How others see your timeout

AnswerMeaningTypical sender
408 Request TimeoutThe client took too long to send its requestA web server
504 Gateway TimeoutA server behind the gateway did not answer in timeA gateway or proxy
503 Service UnavailableNot now. Often with Retry-AfterAn overloaded service
DEADLINE_EXCEEDEDThe deadline passed. The work may have been donegRPC
How to write errors in general is API error handling.

Practice

Do and do not

Do

  • Set a limit on every call that leaves the process
  • Use separate connect and read limits
  • Log each timeout, with the limit in the message
  • Put the limit and the phase in the metrics
  • Test what happens, with an injected delay
  • Pass deadlines through chains

Do not

  • Use no limit or a very long one
  • Use one value for every operation
  • Swallow the timeout error
  • Forget to release the connection, the lock or the task
  • Let an inner limit be longer than the outer one
  • Retry at once, without backoff

Watch these numbers

  1. 1

    Timeout rate per dependency

    About your chosen share of wrong cuts when all is well. A jump is an alarm.

  2. 2

    Latency percentiles with the limit drawn in

    If p99 moves towards the limit, act before it arrives.

  3. 3

    Threads and connections in use

    The thing the limit protects.

  4. 4

    Work finished after its deadline

    Wasted load. It should be near zero.

When one dependency keeps timing out, waiting for each limit is still too slow. A circuit breaker stops the calls, and a fallback decides what the user sees.

Summary

The whole topic in one minute.

Put a limit on every wait. Take it from the latency you measured, because a limit that is too long holds threads and one that is too short cuts off good answers.

In a chain, the caller must wait a little longer than everything it starts below itself. Pass one deadline through the chain, refuse work that cannot finish, cancel work that nobody needs, and remember that a timeout never tells you whether the work was done.

  • Every wait gets a limit: pool, connect, write, read, total.
  • Take the number from measured latency, then check threads and the user's patience.
  • Outer limits are longer than inner ones, retries included.
  • Pass one deadline, refuse what cannot finish, cancel what nobody needs.
  • A timeout means unknown, not failed.

Sources