Go Context: Cancellation, Deadlines, Timeouts, and Context Values
How context cancellation propagates down a call tree, why every CancelFunc must be called, how deadlines negotiate with parents, and what belongs in a context value.

context.Context carries three things across a call tree: a cancellation signal, an optional deadline, and a small set of request-scoped values. It exists because a function that may block needs a way to be told that nobody is waiting for its result any more — the client hung up, a parent operation failed, or the deadline passed. Every blocking call in a Go server should accept one, and the rules around it are stricter than the type suggests.
Quick Summary
context.Background()is the root;context.TODO()is a placeholder to be replaced. Never passnilwhere aContextis expected.WithCancel,WithTimeout, andWithDeadlinereturn a derived context and aCancelFunc. Calling the cancel function is mandatory, even when the deadline expires on its own, or the child leaks.- Cancellation propagates downward only. A parent canceling stops every descendant; a child canceling stops nothing above it.
ctx.Done()returns a channel that is closed on cancellation;ctx.Err()explains why —context.Canceledorcontext.DeadlineExceeded.- Values are for request-scoped metadata (trace IDs, auth principals, request IDs), never for optional function parameters or dependencies.
- A context must be the first parameter, named
ctx, and must not be stored in a struct field. - Deadline propagation is negotiation, not enforcement: a child context gets the earlier of its own deadline and the parent's, and each layer must actually check
<-ctx.Done()for the deadline to bite.
Basic syntax and type signatures
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key any) any
}
func Background() Context
func TODO() Context
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key, val any) Context
type CancelFunc func()func handler(w http.ResponseWriter, r *http.Request) {
// The server cancels r.Context() when the client disconnects.
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel() // always, immediately after creation
rows, err := db.QueryContext(ctx, "select id from users")
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
http.Error(w, "timeout", http.StatusGatewayTimeout)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
// ...
}
// Blocking work must select on Done, not just pass the context along.
func waitFor(ctx context.Context, ch <-chan int) (int, error) {
select {
case v := <-ch:
return v, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}defer cancel() runs immediately after the child is created so that every early return releases the timer and the reference to the parent. go vet's lostcancel check reports a missing call, and it is right to: a WithTimeout whose cancel is dropped keeps a timer alive until the deadline, and in a hot path that is a memory and scheduler cost that grows with traffic volume.
Comparison of the constructors
| Constructor | Adds | Typical parent | Cancel needed | Common misuse |
|---|---|---|---|---|
Background() | nothing; root | program start, main, tests | no | expecting it to ever cancel |
TODO() | nothing; root, marked | code to be finished | no | shipping it to production |
WithCancel | a manual signal | request scopes, goroutine fan-out | yes | cancel never called on error paths |
WithTimeout | deadline from now | outbound calls, per-request budgets | yes | timeout longer than the client's |
WithDeadline | absolute deadline | chained calls that inherit a budget | yes | clock skew between hops |
WithValue | one key/value pair | request metadata | no | dependencies, config, optional args |
WithDeadline and WithTimeout are the same mechanism; WithTimeout is WithDeadline(now+timeout). When a parent already has a deadline, the child's effective deadline is the earlier of the two — never later — so a per-call timeout cannot extend the time the caller allowed.
Practical edge cases and deep dives
1. Fan-out with errgroup and a limited concurrency budget
func fetchAll(ctx context.Context, ids []string) ([]Item, error) {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8) // at most 8 in flight; SetLimit exists since Go 1.20
results := make([]Item, len(ids))
for i, id := range ids {
i, id := i, id
g.Go(func() error {
item, err := fetch(ctx, id) // uses the group's context
if err != nil {
return fmt.Errorf("fetch %s: %w", id, err)
}
results[i] = item
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return results, nil
}errgroup.WithContext returns a context canceled when the first goroutine errors, so one failure stops the rest instead of letting them finish work nobody will read. The results slice is written at distinct indexes by different goroutines, which is safe without a mutex because no element is read until Wait returns. If the caller's context has a deadline, that deadline reaches every fetch unchanged.
2. context.AfterFunc for cleanup tied to cancellation
func watch(ctx context.Context, conn net.Conn) error {
// AfterFunc runs f in its own goroutine when ctx is done (Go 1.21).
stop := context.AfterFunc(ctx, func() {
conn.SetDeadline(time.Now()) // unblock any pending Read
})
defer stop()
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
if ctx.Err() != nil {
return ctx.Err() // cancellation, not a transport error
}
return err
}
handle(buf[:n])
}
}Before Go 1.21 the same effect required a goroutine that selected on ctx.Done() and exited, which leaked whenever the function returned before cancellation. AfterFunc returns a stop function whose boolean result tells you whether the callback was already started, which is the detail that makes double-cleanup avoidable: if !stop() { /* callback may be running */ }.
3. Deadlines that must not outlive the caller's budget
func (s *Service) Lookup(ctx context.Context, id string) (User, error) {
// BAD: a fixed timeout longer than the caller's deadline extends nothing
// but hides how much budget is left.
// child, cancel := context.WithTimeout(ctx, 5*time.Second)
// GOOD: keep the remaining budget, or fail fast if it is nearly gone.
if dl, ok := ctx.Deadline(); ok && time.Until(dl) < 50*time.Millisecond {
return User{}, context.DeadlineExceeded
}
child, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
return s.repo.Get(child, id)
}WithTimeout(ctx, 5s) under a parent with 100 ms left yields a child that still cancels at 100 ms, so the extra 5 s never applies — the danger is the opposite reading, where a layer assumes it has 5 s and writes retry logic that outlives the parent. Reading ctx.Deadline() and budgeting against it is how a service chooses between a fast fallback and a real attempt.
4. Values: keys, scope, and what not to store
// Unexported key type: no other package can collide with it.
type ctxKey int
const (
keyRequestID ctxKey = iota
keyPrincipal
)
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, keyRequestID, id)
}
func RequestID(ctx context.Context) (string, bool) {
id, ok := ctx.Value(keyRequestID).(string)
return id, ok
}
// A typed accessor keeps the assertion in one place.
func Principal(ctx context.Context) *auth.User {
u, _ := ctx.Value(keyPrincipal).(*auth.User)
return u
}The key must be comparable and, for library code, unexported with a package-private type; a plain string key lets unrelated packages overwrite each other. Values are read-mostly and request-scoped: a database handle, a logger configuration, or a feature flag belongs in a struct or a parameter, because a function that needs one cannot be understood from its signature alone.
5. Cancellation inside a loop that does not block
func process(ctx context.Context, items []Item) error {
for i, item := range items {
// Check at the top of each iteration: no blocking call may be reached
// often enough to notice the cancellation on its own.
if err := ctx.Err(); err != nil {
return fmt.Errorf("process stopped at item %d: %w", i, err)
}
if err := handle(item); err != nil {
return err
}
}
return nil
}A loop whose body finishes in microseconds may never reach a select on Done, so a canceled request keeps a CPU busy until the loop ends. ctx.Err() is a non-blocking read and cheap enough to call per iteration; every n iterations is also acceptable when the body is trivial.
Common mistakes and compiler errors
| Symptom | Cause | Fix |
|---|---|---|
context: nil Context panic | nil passed explicitly as the context | pass context.TODO() until a real parent exists |
| Goroutines pile up under load | cancel never called, so children stay registered | defer cancel() right after creation |
newAPI reports the cancel function is not used on all paths | a branch returns before defer cancel() | move the defer next to the constructor call |
| Timeout never fires | the blocking call does not accept a context | use a ...Context variant or select on Done() |
context.DeadlineExceeded reported as a generic error | the error was wrapped without %w | wrap with %w and check with errors.Is |
type assertion failed on ctx.Value | a string key collided with another package's | use an unexported key type |
context canceled in a background job | a request context was stored and reused after the request ended | create a new context with its own lifetime |
| Race detector fires on values written from a goroutine | WithValue used to pass a mutable container | pass an immutable value and copy on write |
Two of these account for most production incidents: reusing a request context in a background goroutine that outlives the request, and a blocking call that takes a context but never checks it. The first is fixed by deriving a fresh context from context.WithoutCancel (Go 1.21) when detached work must continue, and the second by reading the implementation of the callee before trusting that a deadline reaches it.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.