← All writing

context.Context cancellation is a contract, not a hint

5 min readgo

When a function takes a context.Context, it is promising the caller something: if the context is cancelled, I will stop soon and return. Most goroutine leaks I've debugged come down to a function that accepted the context and then quietly ignored it.

The classic leak

func worker(ctx context.Context, jobs <-chan Job) {
    for job := range jobs {   // blocks forever if nobody closes jobs
        process(job)
    }
}

If the producer exits without closing the channel, this goroutine lives until the process dies. The fix is to wait on both:

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

Three places I check in review

  1. Every blocking channel operation inside a long-lived goroutine sits in a select with ctx.Done().
  2. Outbound calls use the context. http.NewRequestWithContext, db.QueryContext — not the variants without it.
  3. Nobody stores a context in a struct to use later. A request's context belongs to that request; background work gets its own, derived from the application's lifetime.

Returning the right error

When you stop because of cancellation, return ctx.Err() (or wrap it). Callers can then tell "I gave up" apart from "it failed" with errors.Is(err, context.Canceled), and they won't log a cancelled request as an incident.

None of this is new, but it is the kind of thing that only shows up as a slowly climbing goroutine count on a dashboard three weeks after the change shipped.