SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

Timeouts and Deadlines

Never wait forever: set a limit on every call, and pass the remaining time down the chain.

โฑ 12 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A timeout is a limit on how long you will wait for an answer. A deadline is the moment by which the whole request must be finished, and it is passed down from service to service.

  • Without a timeout, one slow service can make every caller wait forever, and the failure spreads.
  • Each hop should get only the time that is left, not a fresh full timeout.
  • When the caller gives up, the work below should stop. Otherwise you pay for answers nobody will read.

02Concept: What is it?

Every network call can fail in a nasty way: not with an error, but with silence. The other side is slow, the line is cut, or the process is stuck. If your code waits with no limit, a thread (or a connection) is held for as long as the silence lasts. Soon every thread is waiting, and your service stops too. This is how one slow service brings down a whole system.

The first rule is simple: put a timeout on every call. There are three common kinds: a connect timeout (how long to wait to open the connection), a read or response timeout (how long to wait for the answer) and an overall timeout for the whole request, retries included.

The second rule is for chains. If the client waits 3 seconds, and service A calls B, and B calls C, each with its own 2-second timeout, then A and B may keep working for seconds after the client has left. A deadline fixes this. The client says "I need an answer by 3 s from now." Every hop passes on the remaining time, and stops when it runs out.

Fixed timeouts and a passed-down deadline
๐Ÿ“ฑClient3 s patience
โ†’โ†“3.0 s left
๐Ÿ…ฐ๏ธService A
โ†’โ†“2.5 s left
๐Ÿ…ฑ๏ธService B
โ†’โ†“1.8 s left
๐Ÿ…ฒService Cstops at 0
With a deadline, every hop knows how much time is left, and nobody works after the caller has gone.
๐Ÿง The inner time must fit inside the outer time
If A tries B three times with a 2-second timeout each, A may spend 6 seconds. A client that waits only 3 seconds will never see the third try. Add up the timeouts and retries, and check the total against what the caller will wait.

03Real-Life Example

๐ŸตThe Relay Race With a Closing Time
You ask a friend to get a parcel from a shop that closes at 6 pm. Your friend asks a courier, who asks the shop. If every person says "I will wait up to an hour", they may all wait, and walk back, long after the shop has closed and you have gone home. Instead you say "I need it by 6 pm." Your friend tells the courier "by 5:50", and the courier tells the shop "by 5:40". Each one leaves a little time for the walk back. When the time is up, everybody stops at once, and nobody carries a parcel to an empty house.
Relay race
Timeouts and deadlines
Waiting an hour at the shop
A timeout on a call
Closing time of 6 pm
The deadline of the whole request
Telling each person how much time is left
Passing the remaining time down the chain
Leaving time for the walk back
A shorter timeout for each deeper hop
Everybody stops when time is up
Cancelling work when the caller has gone
Carrying a parcel to an empty house
Work whose result nobody will read
Going back to ask again
A retry (which takes more of the time)
Waste after the caller has left
๐Ÿ“ฑClient leavesat 3 s
โ†’โ†“but...
โš™๏ธA, B, C keep workinguntil their own timeouts
โ‡ขโ‡ฃresult
๐Ÿ—‘๏ธThrown away

04Why Do We Need It?

๐ŸงตFree the threads
A timeout releases the thread or connection, so one stuck call does not block the next hundred.
๐ŸŒŠStop cascades
A slow dependency should cause one quick error, not a slow death of everything upstream.
๐Ÿ’ธStop wasted work
Deadlines cancel work whose result will be thrown away. That saves CPU, money and load.
โฑ๏ธKeep promises
If your SLO is 300 ms, you need a way to give up and answer, not wait without limit.
๐ŸงฏHelp recovery
A struggling service recovers faster if it is not still busy with abandoned requests.
๐Ÿ”ŽClear failures
A timeout is an error you can log, measure and handle. Waiting forever is invisible.
Never wait without a limit. Give the whole request one deadline, and let every hop see how much of it is left.

05Where Do We Use It?

๐ŸงฑMicroservice chains
A request that touches many services needs a shared budget so the sum of the waits fits.
๐Ÿ—„๏ธDatabase calls
Query timeouts stop one slow query from holding a connection from the pool.
๐ŸŒHTTP clients
Every outgoing call (to a payment provider, for example) needs connect and read timeouts.
๐Ÿ”ŒgRPC and RPC systems
Many RPC systems carry a deadline in the request, and the servers can see the time left.
๐Ÿ“ฌQueues and workers
A job that runs longer than its limit is stopped, and retried or sent to a dead letter queue.
๐ŸงฐLoad balancers and proxies
They have their own idle and request timeouts. These must fit with the appโ€™s timeouts.

06Types / Parts / How It Works

Kinds of timeout

TimeoutWhat it limitsTypical problem it solves
Connect timeoutTime to open the connection (handshake)A server that is down or unreachable. This should be short.
Read / response timeoutTime waiting for data after the request was sentA server that accepted the call but is stuck or slow
Write timeoutTime to send the request bodyA very slow client or network
Overall (total) timeoutThe whole call, with retries and waits includedMany small waits that add up to a long one
Idle timeoutHow long a quiet connection may stay openConnections kept open for no reason, or cut by a firewall

Timeout or deadline?

TimeoutDeadline
It isA length of time: wait up to 2 sA point in time: finish by 12:00:03.500
Set byEach caller for its own callThe first caller. Then it is passed on.
Each hopStarts a fresh clockUses the time that is left
After the caller leavesLower services may carry onLower services see the time is up and stop
Best forA single call to one dependencyChains of calls through many services
Time budget shrinks down the chain
โณ3000 msclient budget
โ†’โ†“-200 ms for A
โณ2800 msA passes on
โ†’โ†“-300 ms for B
โณ2500 msB passes on
โ†’โ†“C works
๐ŸCstops at 0
Start Time left Stop
Each hop keeps a little time for itself, so the next hop gets less. When the budget reaches zero, everyone stops.
VisualizerFixed timeouts vs a shared deadlineMake C very slow and the client's patience short. See how fixed timeouts keep working after the client has gone, and how a deadline stops the waste. Then raise the retries and watch the numbers multiply.
Fixed timeout at every hop
Each bar is one call to C. The white line is when the client gives up.
03 s6 s
Client got an answer
No
gave up at 3 s
Calls to C
4
Started too late
1
after client left
Work after client left
3 s
One deadline passed down
Each bar is one call to C. The white line is when the client gives up.
03 s6 s
Client got an answer
No
gave up at 3 s
Calls to C
2
Started too late
0
after client left
Work after client left
none
answered timed out started after the client left
The client left at 3 s, but with fixed timeouts the chain kept working for another 3 s and started 1 more call to C that nobody was waiting for. With a shared deadline, no work starts or continues after 3 s. Warning: one hop alone can spend 4 s (2 s x 2 attempts), which is more than the client's 3 s. The inner time must fit inside the outer time.

A simplified, deterministic model of the chain client, A, B, C. C always needs the same time, network delay between hops is ignored, and the client does not retry. With fixed timeouts, nobody cancels a call after its caller has given up. All times are illustrative.

07How to Use It / Steps / Implementation

Setting timeouts well

  1. 1
    Put a timeout on every network call
    Check the defaults of your HTTP client, database driver and queue client. Many have no limit, or a very long one.
  2. 2
    Measure first
    Look at the latency of the dependency (the p99 is a good start). A timeout just above the p99 is a common start, then adjust.
  3. 3
    Set the connect timeout shorter than the read timeout
    A server that cannot even accept a connection will not get better by waiting.
  4. 4
    Start from the top
    Decide how long the user will wait. Give each deeper hop less than the one above it, with room for retries.
  5. 5
    Pass the deadline down
    Send the remaining time in a header, or use an RPC system that carries deadlines. Each hop subtracts its own work.
  6. 6
    Cancel work when time is up
    Stop database queries and calls to other services as soon as the caller has gone. Free the thread and the connection.
  7. 7
    Retry carefully
    Retry only if there is time left, and only for safe calls. Use backoff, jitter and a retry budget.
โš ๏ธA timeout is not a failure of the work
When a call times out, the other side may still have finished the work. If you retry a payment, you may pay twice. Make such calls idempotent (see Idempotency) before you add retries.
๐Ÿ’กAlert on timeouts
Count timeouts by dependency. A sudden rise in timeouts is often the first sign that a service is in trouble, before the errors begin.

08Key Terms to Know

TermMeaning in easy words
TimeoutThe longest time you will wait for something before giving up
Connect timeoutA limit on how long opening a connection may take
Read timeoutA limit on how long to wait for the answer after sending a request
DeadlineThe point in time by which the whole request must be finished
Deadline propagationPassing the remaining time to every service down the call chain
Time budgetThe time still available for the rest of the request
CancellationStopping work in progress because its result is no longer needed
Cascading failureOne slow or failed service causing its callers, and then their callers, to fail
Retry budgetA limit on how many retries are allowed, so retries do not flood a weak service
Fail fastReturn an error quickly instead of waiting a long time for a likely failure
Tail latency (p99)The slowest 1% of requests, often used to choose a timeout

09Pros, Cons and Trade-offs

โœ… Pros
  • Threads and connections are never stuck forever
  • Failures stay small and visible
  • Work for absent callers is stopped
  • Helps a struggling service to recover
  • Makes SLOs possible to keep
โš ๏ธ Cons
  • Too short: healthy but slow calls fail
  • Hard to choose good values
  • Deadline propagation needs support in every service
  • A timeout hides whether the work finished
  • Retries and timeouts together can multiply load

Trade-offs

ChoiceWe gainWe lose
Short timeoutFast failure, free resourcesMore false failures on a slow day, and more retries
Long timeoutFewer false failuresThreads held longer, and slow failures spread
Fixed timeout per hopSimple to set upWork continues after the caller has left, and the totals do not fit
Shared deadlineNo waste after the caller leaves, and a total that fitsEvery service must pass it on and respect it
Retries inside the deadlineA chance to recover from a short faultLess time per try, and more load on the dependency
Cancelling workSaves resourcesHalf-done work may need clean-up

10Common Problems and Mistakes

Common mistakes

  1. No timeout at all. Many libraries wait forever by default. One slow call can stall a whole service.
  2. The same timeout at every hop. The deeper hop should always get less time than the one above it.
  3. Retries that do not fit. Three tries of 2 seconds is 6 seconds. The caller left at 3.
  4. Retrying a timed-out payment. The first call may have succeeded. Without idempotency you charge twice.
  5. Not cancelling. The caller has gone, but the database query and the downstream calls still run.
  6. Timeouts set by guessing. Without latency data, they are too short on busy days, or too long to help.
  7. Forgetting the proxies. A load balancer with a 60 s idle timeout and an app with a 90 s call will fail in confusing ways.

Things to watch

๐Ÿ”Retry storms
A timeout causes retries, retries add load, load causes more timeouts. Use backoff and jitter.
๐Ÿ•ณ๏ธUnknown outcomes
After a timeout you do not know if the work was done. Design for both cases.
๐ŸงฎSums that do not fit
Add up the timeouts and retries along the chain and compare with the caller's patience.
๐ŸŒSlow starts
A cold cache or a new connection can make the first call slow. Do not set the timeout too tight.

11Real-World Examples

๐Ÿ”ŒgRPC deadlines
gRPC lets a client set a deadline that travels with the call, and servers can see how much time is left.
๐ŸŒHTTP clients and servers
Mature HTTP clients let you set connect, read and overall timeouts. Check the defaults, because they differ a lot.
๐Ÿ—„๏ธDatabase drivers
Query and statement timeouts stop a runaway query from holding a connection from the pool.
๐Ÿ•ธ๏ธService meshes
A mesh can apply timeouts and retry limits to every call in one place.
โ˜๏ธServerless functions
A function has a maximum run time. The callerโ€™s timeout should be a little longer than that.
๐Ÿ“ฌMessage workers
A job that passes its time limit is stopped, and retried or moved to a dead letter queue.
๐Ÿ“Note
Defaults and header names for deadlines differ between libraries and products. Check the documentation of the tools you use, and test with a deliberately slow dependency.
Mini case: checkout with a 3 second deadline
๐Ÿ›’Checkoutdeadline 3.0 s
โ†’โ†“2.6 s left
๐Ÿ“ฆStock check
โ†’โ†“1.8 s left
๐Ÿ’ณPaymentidempotency key
Entry point Time left Careful step
Every hop keeps time for itself, retries only while time is left, and stops when it reaches zero.

12Related Topics to Read Next

Retries with Backoffโ†’

Retries must fit inside the time budget.

Circuit Breakerโ†’

Stops calls to a service that keeps timing out.

Bulkheadโ†’

Keeps a slow dependency from using all the threads.

Connection Poolingโ†’

A stuck call holds a pooled connection until it times out.

Back Pressureโ†’

Another way to stop slow parts from piling up work.

Idempotencyโ†’

Makes it safe to retry a call that timed out.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Rule 1: put a timeout on every network call. No limit means a possible hang.
  • โœ”Kinds: connect, read, overall. Connect can be short.
  • โœ”Choose: a little above the dependency's p99, checked against the caller's patience.
  • โœ”Deadline: the point in time for the whole request. Pass the time left to each hop.
  • โœ”Fit: inner timeout x tries must be smaller than the outer timeout.
  • โœ”Cancel: stop work when the caller has gone, so nothing is wasted.
  • โœ”Retries: only with idempotency, backoff, jitter and time left.
  • โœ”One line: โ€œNever wait without a limit, and tell every hop how much time is left.โ€
โ† Previous
Database per Service
Next โ†’
API Composition