Context cancellation is easy to add and easy to get subtly wrong. These are the rules I keep coming back to.

Pass it, do not store it

context.Context is a request-scoped value. Pass it as the first argument to functions that do I/O; do not put it in a struct that outlives the request. If a type needs a context for every method, the context probably belongs to the caller.

Every blocking call gets one

Database queries, HTTP requests, file operations, and channel waits should all accept a context or have a timeout. A loop that checks ctx.Err() only between iterations can still block for a long time inside one iteration.

Cancel siblings with errgroup

errgroup.WithContext gives you a context that is cancelled when the first goroutine returns an error. That is usually the behaviour you want for parallel work.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return server.ListenAndServe() })
g.Go(func() error {
    <-ctx.Done()
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    return server.Shutdown(shutdownCtx)
})
if err := g.Wait(); err != nil && !errors.Is(err, http.ErrServerClosed) {
    log.Fatal(err)
}

Distinguish cancellation from failure

When a request is cancelled, the caller usually does not want an error page or a retry. Check ctx.Err() before logging a failure as a bug. Conversely, a deadline exceeded is not the same as a user closing the tab; both are cancellations, but only one deserves an alert.

Result

The goal is not to cancel everything. The goal is to make cancellation explicit, so shutdown and timeouts behave the same way in development and production.

← All notes