Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#Go#Concurrency#Backend
3D illustration of Go goroutine branches propagating cancellation signals down a tree hierarchy with stopwatch timers

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 pass nil where a Context is expected.
  • WithCancel, WithTimeout, and WithDeadline return a derived context and a CancelFunc. 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.Canceled or context.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

go
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()
go
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

ConstructorAddsTypical parentCancel neededCommon misuse
Background()nothing; rootprogram start, main, testsnoexpecting it to ever cancel
TODO()nothing; root, markedcode to be finishednoshipping it to production
WithCancela manual signalrequest scopes, goroutine fan-outyescancel never called on error paths
WithTimeoutdeadline from nowoutbound calls, per-request budgetsyestimeout longer than the client's
WithDeadlineabsolute deadlinechained calls that inherit a budgetyesclock skew between hops
WithValueone key/value pairrequest metadatanodependencies, 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

go
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

go
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

go
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

go
// 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

go
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

SymptomCauseFix
context: nil Context panicnil passed explicitly as the contextpass context.TODO() until a real parent exists
Goroutines pile up under loadcancel never called, so children stay registereddefer cancel() right after creation
newAPI reports the cancel function is not used on all pathsa branch returns before defer cancel()move the defer next to the constructor call
Timeout never firesthe blocking call does not accept a contextuse a ...Context variant or select on Done()
context.DeadlineExceeded reported as a generic errorthe error was wrapped without %wwrap with %w and check with errors.Is
type assertion failed on ctx.Valuea string key collided with another package'suse an unexported key type
context canceled in a background joba request context was stored and reused after the request endedcreate a new context with its own lifetime
Race detector fires on values written from a goroutineWithValue used to pass a mutable containerpass 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 tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.