vvek

Go's context package, used well: cancellation, deadlines and the values you should not put in it

How context.Context carries cancellation and deadlines through a Go program, the habits that avoid leaks, and a short list of what not to store in it.

If you write Go services, you meet context.Context in the first hour and then see it in every function signature for years. It is easy to use it by habit without knowing exactly what it promises. This article goes through the three jobs it does, the mistakes that cause leaks, and the question of what belongs inside it.

The material here follows the Go team's own blog post on the subject, which is still the clearest explanation I know.

What a context is for

A Context carries three things across API boundaries and between goroutines:

  1. A cancellation signal: someone no longer needs the result, so stop.
  2. A deadline: stop at this time at the latest.
  3. Request-scoped values: a small amount of data tied to one request.

The first two are the important ones. The third is where people get into trouble, and we will come back to it.

Cancellation

The Done method returns a channel that is closed when the context is cancelled or times out. Code that can block or run for a while should watch it:

func fetch(ctx context.Context, url string) ([]byte, error) {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        return nil, fmt.Errorf("build request: %w", err)
    }
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, fmt.Errorf("fetch %s: %w", url, err)
    }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}

If the caller's context is cancelled, the HTTP client aborts the request and the error you get back wraps context.Canceled or context.DeadlineExceeded. After Done closes, ctx.Err() tells you which one.

For your own loops, use select:

for {
    select {
    case <-ctx.Done():
        return ctx.Err()
    case job := <-jobs:
        process(ctx, job)
    }
}

A context has no Cancel method, on purpose

You cannot cancel a context you were handed. The Go team explains why: the function that receives a cancellation signal is usually not the one that sends it, and a sub-operation should not be able to cancel its parent. To get the power to cancel, you create a child with WithCancel:

ctx, cancel := context.WithCancel(parent)
defer cancel()

A single context can be shared by many goroutines, and cancelling it tells all of them.

Deadlines

WithTimeout and WithDeadline give you a context that cancels itself:

ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()

data, err := fetch(ctx, "https://example.com/report")

Two details are worth remembering.

First, the deadline you get is the sooner of "now plus timeout" and the parent's deadline. A child can tighten a deadline but never extend it. That is what lets a request-level budget flow down through every layer without anyone being able to break it.

Second, Deadline lets you read the deadline. If less time remains than an operation needs, you can fail fast instead of starting work you cannot finish. This idea is central to keeping a busy system healthy, and it is one of the four habits in why one slow service takes down the rest.

Always call cancel

Every WithCancel, WithTimeout and WithDeadline returns a cancel function. Call it when the work is finished, usually with defer. If you do not, the context holds on to resources until its timer fires or its parent is cancelled. With a long-lived parent, that is a leak.

The go vet tool has a check that flags a dropped cancel function, so run it.

ctx, cancel := context.WithTimeout(parent, time.Second)
defer cancel() // even if the timeout fires on its own

Calling cancel more than once is safe.

The tree

Contexts form a tree. context.Background() is the root: it is never cancelled, has no deadline and carries no values. You normally use it in main, in tests, and as the top-level context for incoming work. Everything else derives from something above it, and cancelling a node cancels all of its descendants.

For an HTTP server, the request already has a context, available as r.Context(). It is cancelled when the client goes away or the handler returns. Pass it down:

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    user, err := store.LoadUser(ctx, r.PathValue("id"))
    // ...
}

Google's internal rule, mentioned in the Go blog post, is that a Context is passed as the first argument to every function on the call path between an incoming request and an outgoing one. That is why the convention is func Do(ctx context.Context, ...): first parameter, named ctx, and never stored in a struct for later use.

Note

Passing the context explicitly can feel repetitive. The payoff is that cancellation and deadlines work everywhere without any extra wiring, including in code you wrote months ago.

Values: use sparingly

WithValue attaches a key and a value. It is meant for request-scoped data that crosses API boundaries, such as a request ID or the authenticated user, not for optional function arguments.

Two rules from the Go team:

  • Use an unexported key type, so that keys from different packages cannot collide.
  • Wrap access in typed helper functions instead of exposing raw keys.
type ctxKey struct{}

func WithRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, ctxKey{}, id)
}

func RequestID(ctx context.Context) (string, bool) {
    id, ok := ctx.Value(ctxKey{}).(string)
    return id, ok
}

Values must also be safe for simultaneous use by many goroutines, so store immutable things.

What not to put in a context

A good test: would the function still be correct if I called it with an empty context? If it needs a database handle, a logger configuration or a feature flag to do its job, pass that as a normal parameter or struct field. Hidden dependencies make code hard to read and hard to test.

Request IDs and trace identifiers are the classic good fit, because they exist only to be attached to logs and spans. If you are adding trace IDs to your logs, the post on structured logging with slog shows how a context-aware logger picks them up.

A checklist you can paste into a code review

  • Is ctx the first parameter, and is it passed down rather than replaced with context.Background() midway?
  • Does every blocking call or long loop respect ctx.Done()?
  • Is every cancel function called, usually with defer?
  • Are context keys an unexported type with typed accessors?
  • Is anything in the context that should be an ordinary argument?
  • Do the errors wrap ctx.Err() so callers can check with errors.Is(err, context.DeadlineExceeded)?

A last small habit

When a function starts a goroutine, ask who will stop it. Give the goroutine the context, make it watch Done, and make sure the parent waits for it (an errgroup or sync.WaitGroup does this). Goroutines that nobody can tell to stop are the usual source of slow memory growth in long-running services.

Context is a small API with a big effect. Use it for cancellation and deadlines first, values rarely, and you will find that timeouts and shutdowns start to behave the way you expected from the beginning.

Sources

Keep reading

A short email when we publish. Confirm once, unsubscribe any time.