Timeouts
easy 30 minA 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
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
1981
RFC 793 defines TCP. It resends data after a retransmission timeout, and has a user timeout after which a connection is given up.
1989
RFC 1122 sets requirements for internet hosts, including how TCP computes its retransmission timeout and backs off.
1997
RFC 2068, the first HTTP/1.1, describes status 408 Request Timeout and 504 Gateway Timeout.
2011
RFC 6298 restates the TCP timer: a smoothed round-trip time plus four times its variation, doubled after each timeout.
2013
Dean and Barroso publish The Tail at Scale, about the rare slow answers that large systems meet all the time.
2014
The Go blog introduces the context package, which carries deadlines and cancellation through a program's calls.
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.
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.
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
What a limit is worth
Kinds
One call, several waits
The phases of one call
| Timeout | Limits | What it tells you | Common starting point |
|---|---|---|---|
| Pool | Waiting for a free connection in your own process | Your pool is too small, or calls are too slow | Short: tens of milliseconds |
| Connect | TCP handshake (often the TLS handshake too, or it has its own) | The host is down, unreachable or cannot accept | A few hundred ms in one region, 1 to 5 s across the internet |
| Write | Sending the request body | A slow network or a large upload | Seconds for small bodies. More for uploads |
| Read | Silence while waiting for data | The server is slow or stuck | From the measured latency. Many guides say 5 to 30 s, which is long for a person |
| Total | The whole operation, retries included | The safety net when each piece is just fast enough | What the caller can afford: 1 to 3 s for a person, longer for a job |
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.Timeoutof zero means no timeout. It covers the whole call including the body.gRPC
No deadline by default. Set one on every call.
axios
timeoutis one limit in milliseconds. It is 0, meaning none, unless you set it.PostgreSQL
statement_timeoutis 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?
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
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
| Operation | Common values (connect, read, total) | For a person who waits | Reason |
|---|---|---|---|
| Internal service | 1 to 2 s, 5 to 10 s, 15 s | 0.2 s, p99.9 plus room, under 1 s | One region: a healthy round trip is about a millisecond |
| External API | 3 to 5 s, 10 to 30 s, 60 s | 1 to 3 s, 2 to 5 s, or take it out of the request | Nobody looks at a spinner for a minute. Use a queue |
| Database query | 2 to 3 s, 5 to 30 s, 30 s | 0.2 s, 1 s, with statement_timeout | Reports get their own, longer limit and their own pool |
| User-facing API | 1 s, 3 to 5 s, 10 s | 1 s, 1 to 2 s, 2 to 3 s | The whole page must fit |
Strategies
Four ways to set a limit
| Strategy | How | Good | Bad |
|---|---|---|---|
| Static | A fixed value from configuration | Simple, predictable | Does not follow conditions, goes stale |
| Per operation | A value for each kind of call | Fits search and checkout alike | More configuration to keep true |
| Adaptive | Computed from recent latency | Follows the network, uses resources well | More complex. A slow service can teach it to wait longer, so keep a ceiling |
| Deadline propagation | The remaining time travels with the request | All services stop together, no wasted work, one clear budget | Every service must pass it on and respect it |
An adaptive limit, as TCP does it
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
The rule, with retries
Deadlines
One clock for the whole chain
A deadline travels with the request
What each service does with a deadline
- 1
Check at the door
No time left, or less than this work needs? Refuse at once. Do not start.
- 2
Keep a little for yourself
Reserve time for your own last step and for the answer to travel.
- 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
Check again before expensive steps
A queue may have eaten the time.
- 5
Stop when it passes
Cancel your own calls, close the query, release locks.
May this service start?
Code
Limits in real clients
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") # millisecondsConnectTimeout 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
| Answer | Meaning | Typical sender |
|---|---|---|
| 408 Request Timeout | The client took too long to send its request | A web server |
| 504 Gateway Timeout | A server behind the gateway did not answer in time | A gateway or proxy |
| 503 Service Unavailable | Not now. Often with Retry-After | An overloaded service |
| DEADLINE_EXCEEDED | The deadline passed. The work may have been done | gRPC |
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
Timeout rate per dependency
About your chosen share of wrong cuts when all is well. A jump is an alarm.
- 2
Latency percentiles with the limit drawn in
If p99 moves towards the limit, act before it arrives.
- 3
Threads and connections in use
The thing the limit protects.
- 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.