CS Fundamentals Trainer · Guides
Go context: cancellation, deadlines, values and causes
How to use the context package correctly: the four methods, the tree of derived contexts, every constructor including WithCancelCause, WithoutCancel and AfterFunc, why you must call cancel, how to honour cancellation in loops and blocking calls, Canceled against DeadlineExceeded, request values, HTTP servers, retry budgets, and the common mistakes.
9 min read
Every Go service that calls a database, another service or a slow function eventually has to answer two questions: "how long am I willing to wait?" and "what stops this work when the caller has gone away?". The context package is the standard answer. It is small, but its rules are easy to get wrong, and the mistakes (leaked timers, work that never stops, values used as hidden parameters) show up only under load. This guide covers what a context is, how contexts form a tree, the constructors including the newer ones, how to honour cancellation, how HTTP servers use it, and the patterns and mistakes that come up in reviews. The outputs shown were produced with Go 1.24.
1. What a context is
context.Context is an interface with four methods:
| Method | Meaning |
|---|---|
Done() <-chan struct{} | closed when the context is cancelled or its deadline passes |
Err() error | nil while active; context.Canceled or context.DeadlineExceeded afterwards |
Deadline() (time.Time, bool) | when the work should be finished, if a deadline is set |
Value(key any) any | request-scoped data attached to the context |
A context is immutable. You never change one; you derive a new one from it. That is what makes it safe to share between goroutines.
2. Contexts form a tree
context.Background() is the empty root, used in main, in tests and at the top of a request. context.TODO() is the same thing with a message to readers: "I have not decided which context belongs here yet". Every other constructor takes a parent and returns a child.
Two rules about the tree:
- Cancellation flows down, never up. Cancelling a parent cancels all its children. Cancelling a child does not touch the parent or its siblings.
- A child cannot outlive its parent's deadline. A child created with a one-hour timeout under a parent that expires in 20 ms gets the parent's deadline; the test printed
truewhen comparing the two deadlines.
Diagram: A request context tree
3. The constructors
| Constructor | Use it for | Since |
|---|---|---|
WithCancel(parent) | stopping work by calling cancel() | 1.7 |
WithTimeout(parent, d) / WithDeadline(parent, t) | giving up after a duration or at a time | 1.7 |
WithValue(parent, key, v) | request-scoped data | 1.7 |
WithCancelCause(parent) and Cause(ctx) | recording why a context was cancelled | 1.20 |
WithTimeoutCause / WithDeadlineCause | naming the reason for a timeout | 1.21 |
WithoutCancel(parent) | keeping the values but dropping the cancellation | 1.21 |
AfterFunc(ctx, f) | running f in its own goroutine once ctx is done | 1.21 |
The newer ones solve real problems. Err() alone cannot tell you why:
ctx, cancel := context.WithCancelCause(context.Background())
cancel(errors.New("shutting down"))
fmt.Println(ctx.Err(), "|", context.Cause(ctx))
// context canceled | shutting down
t, c := context.WithTimeoutCause(context.Background(), 10*time.Millisecond, errors.New("db too slow"))
defer c()
<-t.Done()
fmt.Println(t.Err(), "|", context.Cause(t))
// context deadline exceeded | db too slow
errors.Is(t.Err(), context.DeadlineExceeded) is still true, so existing checks keep working; Cause adds information on top.
WithoutCancel is the answer to "I want to do audit logging or a cleanup after the request ends, but it must keep the trace id". The derived context has no deadline and is never cancelled, yet Value still finds the parent's values:
wc := context.WithoutCancel(parent)
cancelParent()
fmt.Println(parent.Err(), wc.Err(), wc.Value(key{}))
// context canceled <nil> v
Because it never ends, you are responsible for giving that work its own timeout.
4. Always call cancel
WithCancel, WithTimeout and WithDeadline return a cancel function. Calling it releases the timer and removes the child from its parent's list. If you forget, the resources stay until the timeout fires (or forever for WithCancel). Use the pair on the same line:
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
Calling cancel after the work finished normally is correct and expected. go vet has a check, lostcancel, which reports paths where it is not called; in a test it printed "the cancel function is not used on all paths (possible context leak)". Run go vet in CI.
5. Honouring cancellation
A context cancels nothing by itself. It only signals, and code must look at the signal. Three places to look:
- Blocking calls that take a context. Use them:
http.NewRequestWithContext,db.QueryContext,exec.CommandContext,net.Dialer.DialContext,sem.Acquire(ctx, n). They returnctx.Err()early. - Loops and waits you write yourself. Put
ctx.Done()in theselect:
func poll(ctx context.Context, every time.Duration, fn func() error) error {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return context.Cause(ctx)
case <-t.C:
if err := fn(); err != nil {
return err
}
}
}
}
With a 55 ms timeout and a 10 ms ticker it ran fn about five times and returned context deadline exceeded.
- Long CPU work. Check
ctx.Err()every so many iterations; a tight loop never reaches aselectby itself.
Also remember sends and receives: ch <- v blocks forever if no one reads, so in goroutines that can be abandoned use select { case ch <- v: case <-ctx.Done(): return }. This is the main cure for goroutine leaks.
6. Which error do I get
context.Canceled: someone calledcancel(). In a server this usually means the client disconnected. It is normally not your bug and often not worth an error log.context.DeadlineExceeded: a timeout or deadline passed. This may mean slowness, and it is worth a metric.
Compare with errors.Is, because libraries wrap the error. Use context.Cause(ctx) when you recorded a reason, but still return something that matches ctx.Err() if callers rely on it.
7. Values
WithValue attaches data to the context. Use it for data that travels with a request across API boundaries and that functions do not need to declare: trace id, request id, authenticated user, logger with request fields. Do not use it for optional parameters, configuration or dependencies: the compiler cannot check them, they hide from the function signature, and they make tests harder to read.
Define the key as a private type so packages cannot collide:
type ctxKey struct{}
func WithUser(ctx context.Context, u User) context.Context {
return context.WithValue(ctx, ctxKey{}, u)
}
func UserFrom(ctx context.Context) (User, bool) {
u, ok := ctx.Value(ctxKey{}).(User)
return u, ok
}
Lookup walks up the chain one parent at a time, so it is fine for a handful of values and wrong as a general store.
8. Contexts and HTTP
In a net/http server, r.Context() is cancelled when the client's connection closes, when the request is done, or when ServeHTTP returns. Pass it to every call the handler makes, and the work stops when the client gives up. Two consequences:
- Work that must outlive the response (sending an email, audit log) needs
context.WithoutCancel(r.Context())plus its own timeout, or a background queue. Usingr.Context()in a goroutine started by the handler cancels it as soon as the handler returns. - A context does not replace server timeouts. Set
ReadHeaderTimeout,IdleTimeoutand the others onhttp.Server, and set a timeout onhttp.Clientor on each request, becausehttp.DefaultClienthas none.
9. Passing contexts around
- Put
ctx context.Contextfirst and name itctx. - Do not store it in a struct. A context is scoped to a call; kept in a struct it outlives that call and hides what it governs. (
http.Requestis a historical exception.) - Never pass
nil. If you do not have one yet, usecontext.TODO(), which tools can find later. - Do not pass a context just to carry a cancel function around; cancel from where it was created.
10. Patterns
Errgroup with a shared context. errgroup.WithContext returns a group and a context that is cancelled the first time a task returns an error (or when Wait returns). The other tasks must watch it. g.SetLimit(n) bounds concurrency.
Timeout per attempt, deadline for the whole operation. Derive a short context for each retry from a longer parent, so retries cannot exceed the overall budget:
ctx, cancel := context.WithTimeout(ctx, 5*time.Second) // whole operation
defer cancel()
for attempt := 0; attempt < 3; attempt++ {
actx, acancel := context.WithTimeout(ctx, time.Second) // one attempt
err := call(actx)
acancel()
if err == nil || ctx.Err() != nil {
return err
}
}
Cleanup on cancel. context.AfterFunc(ctx, f) runs f when ctx is done and returns a stop function. It avoids starting a goroutine that only waits for Done.
11. Common mistakes
- Not calling
cancel(leaks timers and children). - Starting a goroutine with
r.Context()that must outlive the request. - Putting optional parameters, config or database handles in context values.
- Using
stringorintkeys, which collide between packages. - Loops and sends that never look at
ctx.Done(). - Treating
context.Canceledas a server error. - Storing the context in a struct and reusing it across calls.
- Passing
nil, orcontext.Background()deep in a call chain where a context was available. - Relying on the context as the only timeout, with no client or server timeouts.
12. Things to mention in an interview
- A context is an immutable tree node carrying cancellation, a deadline and values; cancellation goes from parents to children.
- Cancellation is cooperative: code must select on
Done()or call context-aware APIs. - Always
defer cancel();go vetreports forgotten ones. CanceledversusDeadlineExceeded,errors.Is, andCausefor the reason.- Values are for request-scoped data with private key types, not for parameters.
WithoutCancelfor work that must outlive the request;AfterFuncfor cleanup callbacks.
Quick recap
Pass ctx first, derive with a timeout and defer cancel(), and make every wait select on ctx.Done(). Cancellation flows down the tree. Use causes to explain why, values only for request data, and WithoutCancel when work must survive the request.
Sources
- The Go Authors, package context.
- Sameer Ajmani, Go Concurrency Patterns: Context and Contexts and structs.
- The Go Authors, Pipelines and cancellation and package errgroup.
- The Go Authors, Go 1.20 and Go 1.21 release notes (
WithCancelCause,WithoutCancel,AfterFunc).
Practise this topic: Go