Context cancel
Cancelling a context closes its Done channel and makes Err return context.Canceled (or DeadlineExceeded if a deadline fired). Child contexts see the same signal. The cancel function returned by WithCancel or WithTimeout releases resources.
Detailed Explanation
ctx, cancel := context.WithCancel(parent) creates a child you can cancel independently. cancel() is idempotent: calling it twice is fine. After cancel, receives from ctx.Done() do not block, and functions should return ctx.Err().
Timeouts and deadlines. WithTimeout(parent, 3*time.Second) cancels automatically when the timer fires. WithDeadline takes an absolute time. Both return a cancel you must still call: it stops the timer if the work finishes early. Forgetting defer cancel() is a documented leak of the timer until it fires.
Who cancels. The function that creates the context owns cancel. HTTP servers cancel the request context when the client goes away. Your worker should not cancel a context it did not create, except to stop its children. Passing cancel down is rarely needed; passing ctx is.
Propagation. I/O helpers (http.NewRequestWithContext, db.QueryContext) stop when ctx is done. A raw time.Sleep does not. A loop that never selects on Done will run to the end. Cancellation is cooperative.
Errors. Return ctx.Err() so callers can tell cancel from deadline. Wrapping is fine: fmt.Errorf("load user: %w", ctx.Err()). Do not invent a new sentinel that hides Canceled.
What it costs. Cancel is a close and a wake of waiters. The leak cost is the timer and the child context object if you never call cancel on a timeout context. The correctness cost is work that continues after the user left.
Code Examples
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(10 * time.Millisecond)
cancel()
}()
<-ctx.Done()
fmt.Println(ctx.Err())
}func withTimeout() error {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
select {
case <-time.After(time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
}func ignore(ctx context.Context) {
time.Sleep(time.Second) // does not stop on cancel
_ = ctx
}Common Gotchas
`Sleep` and tight loops ignore cancel
`select` on `Done` or use APIs that take `ctx`.
Cancelling a parent cancels every child
do not share one cancelable context across unrelated jobs.
`cancel()` after the context is already done is a no-op
`cancel()` after the context is already done is a no-op