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:

MethodMeaning
Done() <-chan struct{}closed when the context is cancelled or its deadline passes
Err() errornil 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) anyrequest-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:

  1. Cancellation flows down, never up. Cancelling a parent cancels all its children. Cancelling a child does not touch the parent or its siblings.
  2. 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 true when comparing the two deadlines.

Diagram: A request context tree

3. The constructors

ConstructorUse it forSince
WithCancel(parent)stopping work by calling cancel()1.7
WithTimeout(parent, d) / WithDeadline(parent, t)giving up after a duration or at a time1.7
WithValue(parent, key, v)request-scoped data1.7
WithCancelCause(parent) and Cause(ctx)recording why a context was cancelled1.20
WithTimeoutCause / WithDeadlineCausenaming the reason for a timeout1.21
WithoutCancel(parent)keeping the values but dropping the cancellation1.21
AfterFunc(ctx, f)running f in its own goroutine once ctx is done1.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:

  1. Blocking calls that take a context. Use them: http.NewRequestWithContext, db.QueryContext, exec.CommandContext, net.Dialer.DialContext, sem.Acquire(ctx, n). They return ctx.Err() early.
  2. Loops and waits you write yourself. Put ctx.Done() in the select:
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.

  1. Long CPU work. Check ctx.Err() every so many iterations; a tight loop never reaches a select by 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

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:

9. Passing contexts around

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

  1. Not calling cancel (leaks timers and children).
  2. Starting a goroutine with r.Context() that must outlive the request.
  3. Putting optional parameters, config or database handles in context values.
  4. Using string or int keys, which collide between packages.
  5. Loops and sends that never look at ctx.Done().
  6. Treating context.Canceled as a server error.
  7. Storing the context in a struct and reusing it across calls.
  8. Passing nil, or context.Background() deep in a call chain where a context was available.
  9. Relying on the context as the only timeout, with no client or server timeouts.

12. Things to mention in an interview

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

Practise this topic: Go

More guides