The idea in one minute#
Every network call needs a timeout. Without one, a slow dependency makes your requests wait, waiting requests hold memory, goroutines and connections, and soon your service is out of resources and down too — because of someone else’s slowness.
A timeout on each call is not enough across a chain of services. If the user gives up after 2
seconds, there is no point in a service four hops down still working on that request at second
5. A deadline is an absolute time by which the whole request must finish; it is passed along
with the request, and every hop uses the time remaining. In Go this is context.Context.
An analogy#
A relay race with a total time limit. If the first runner takes most of the time, the last runner should know there is no point starting — not set off at full speed for a race that has already been lost.
A picture#
sequenceDiagram participant U as User (gives up at 2 s) participant G as Gateway participant O as Orders participant P as Pricing U->>G: GET /order (deadline now+2s) G->>O: deadline now+1.9s (100 ms used) O->>P: deadline now+1.4s (500 ms used) Note over P: P is slow today P--xO: deadline exceeded at 1.4 s — stop work O-->>G: 504 / fallback price G-->>U: response at ~1.9 s
How it really works#
What happens without timeouts#
A service handles 200 requests per second, each normally taking 50 ms, so about 10 are in flight (Little’s law: in-flight = rate × time; see 7.e). A dependency starts taking 30 s. Now each request holds its goroutine, memory and connection for 30 s: in-flight grows to 6,000. Connection pools exhaust, memory climbs, and the service fails even for requests that do not use the slow dependency. A 2-second timeout caps in-flight at about 400 — painful, but alive.
Choosing a timeout#
- Start from the dependency’s latency distribution. A timeout slightly above its p99.9 (say 1.5–2× p99) cuts off the pathological tail without failing normal requests.
- Fit within the caller’s budget. The sum of sequential calls (plus retries, 6.b) must fit inside the deadline the caller was given.
- Separate connect and request timeouts. Connecting should take milliseconds inside a data centre; a 1 s connect timeout finds dead hosts fast.
- Never use the default. Go’s
http.Client{}has no timeout;http.DefaultClientwaits forever. Many libraries default to minutes.
| Timeout | Typical value inside a region | Notes |
|---|---|---|
| TCP connect | 100 ms – 1 s | Fast fail on dead hosts |
| TLS handshake | ~1 s | |
| Request (to an internal service) | p99.9 of that service, e.g. 200 ms – 2 s | |
| Idle connection | 30 – 90 s | Below the server’s and load balancer’s idle timeout |
| User-facing request total | 2 – 10 s | The user’s patience |
Deadlines and propagation#
In Go, the deadline lives in the context.Context. Every outbound call uses the request’s
context, so the deadline travels automatically:
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) // at the edge
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", pricingURL, nil)
resp, err := client.Do(req) // aborts when ctx's deadline passesBetween services, the deadline must be sent explicitly. gRPC does this automatically: the
client’s deadline is sent as the grpc-timeout header and becomes the server’s context
deadline. For HTTP, send the remaining time in a header (e.g. X-Request-Deadline or
X-Timeout-Ms) and have the server derive its context from it.
Rules for deadlines:
- Check before expensive work. If
ctx.Err() != nilor there is less time left than the work needs, fail fast instead of starting. - Subtract a margin at each hop for network and serialisation, so the response can get back before the caller gives up.
- Do not extend a deadline downstream. A hop may use a shorter timeout than the time remaining, never a longer one.
- Cancel work when the client goes away.
r.Context()is cancelled when the HTTP client disconnects; database drivers and HTTP clients that take a context stop too.
Timeouts need a fallback decision#
When a timeout fires, decide in advance what happens: return an error, return a cached or default value (soft dependency, 1.b), or retry (6.b) — only if there is time left.
A worked example#
An orders page calls three services in sequence — inventory (p99 80 ms), pricing (p99 120 ms), recommendations (p99 300 ms, soft) — under a 1-second edge deadline.
- Inventory and pricing get timeouts of 250 ms and 300 ms (≈2–3× p99).
- Recommendations get
min(150 ms, remaining − 100 ms), and on timeout the page renders without them. - When pricing degrades to 2 s, requests fail at 300 ms with a clear error instead of hanging, and in-flight requests stay bounded.
- When the user closes the tab at 400 ms, the context is cancelled and pricing stops working on it.
The program simulates a chain of services with and without deadline propagation, under a slow dependency, and counts wasted work and in-flight requests.
Code#
// deadlines.go — a capacity-limited dependency under slight overload, with and without deadline propagation.
package main
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
const (
patience = 300 * time.Millisecond // the user gives up after this
work = 80 * time.Millisecond // pricing's work per request
workers = 15 // pricing's capacity: 15 / 80 ms ≈ 187 requests/s
interval = 4 * time.Millisecond // offered load: 250 requests/s — a third too much
requests = 500
)
type pricing struct {
slots chan struct{}
served, wasted atomic.Int64 // work done for a waiting user / for a user who had left
skipped atomic.Int64 // requests dropped because their deadline had passed
}
// call runs one pricing request. userCtx is the user's request; propagate says whether pricing
// receives that deadline, or (the common bug) runs under its own long timeout.
func (p *pricing) call(userCtx context.Context, propagate bool) error {
ctx := userCtx
if !propagate {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
}
select { // wait for a worker
case p.slots <- struct{}{}:
case <-ctx.Done():
p.skipped.Add(1)
return ctx.Err()
}
defer func() { <-p.slots }()
if dl, ok := ctx.Deadline(); ok && time.Until(dl) < work {
p.skipped.Add(1) // not enough time left to finish: fail fast, keep the worker free
return context.DeadlineExceeded
}
time.Sleep(work)
if userCtx.Err() != nil {
p.wasted.Add(1) // nobody is waiting for this answer any more
return userCtx.Err()
}
p.served.Add(1)
return nil
}
func run(propagate bool) {
p := &pricing{slots: make(chan struct{}, workers)}
var ok atomic.Int64
var wg sync.WaitGroup
begin := time.Now()
for i := 0; i < requests; i++ {
time.Sleep(time.Until(begin.Add(time.Duration(i) * interval))) // keep an exact arrival rate
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), patience)
defer cancel()
if p.call(ctx, propagate) == nil {
ok.Add(1)
}
}()
}
wg.Wait()
mode := "own 10 s timeout (no propagation)"
if propagate {
mode = "user's deadline propagated"
}
fmt.Printf("%-34s users served %3d/%d wasted work %3d skipped early %3d\n",
mode, ok.Load(), requests, p.wasted.Load(), p.skipped.Load())
}
func main() {
fmt.Printf("pricing capacity ≈ %.0f req/s, offered %.0f req/s, user patience %v\n\n",
float64(workers)/work.Seconds(), 1/interval.Seconds(), patience)
run(false)
run(true)
}Pricing is a third overloaded — a busy afternoon, a slow replica, a lost zone. Without propagation it never learns that callers have given up: its queue grows, every request waits longer, and soon it spends almost all of its capacity on answers nobody will read — most users fail. With the deadline propagated, it skips requests that cannot finish in time, so its workers spend their time on users who are still waiting and most of them are served.
Remember this#
- Every network call gets a timeout; Go’s default HTTP client has none.
- Choose timeouts from the dependency’s tail latency and the caller’s budget; separate connect from request timeouts.
- Propagate deadlines (
context.Context, gRPC does it for you); each hop uses the time remaining minus a margin, never more. - Fail fast when there is not enough time; cancel work when the caller goes away.
- Decide in advance what a timeout returns: an error, a fallback, or a retry if time allows.
Try it#
- Run
deadlines.go. Change pricing’s work to 200 ms. Which mode serves users now, and why? - Find an
http.Client{}without aTimeoutin a codebase you know. - Add a header-based deadline to an HTTP service: the client sends remaining milliseconds; the server creates its context from it.
Check yourself#
- How does a slow dependency without a timeout take down the caller?
- Why should a downstream hop never use a longer timeout than the deadline remaining?
- How does gRPC propagate deadlines?
- What should a service do when it receives a request with 5 ms left and the work takes 50 ms?