Go's context package carries cancellation signals, deadlines and request-scoped values across API boundaries and between goroutines. You create a context with context.WithCancel, WithTimeout or WithDeadline, pass it as the first argument to functions that do work, and have each goroutine stop when ctx.Done() is closed. Cancelling the parent cancels every context derived from it, which is how you shut down a whole tree of goroutines at once.
Every context tree starts from a root, and each derived context inherits cancellation from its parent.
| Function | Purpose |
|---|---|
context.Background() | Empty root context for main, tests and top-level code |
context.TODO() | Placeholder when you have not yet decided which context to use |
context.WithCancel(parent) | Returns a context and a cancel function you call to stop work |
context.WithTimeout(parent, d) | Cancels automatically after duration d |
context.WithDeadline(parent, t) | Cancels automatically at time t |
context.WithValue(parent, key, val) | Attaches request-scoped data |
context.WithCancelCause(parent) | Like WithCancel, but records why it was cancelled (Go 1.20+) |
context.WithoutCancel(parent) | Keeps values but ignores the parent's cancellation (Go 1.21+) |
context.AfterFunc(ctx, f) | Runs f in its own goroutine after ctx is done (Go 1.21+) |
Always call the cancel function, usually with defer cancel(), so the context releases its resources even when the work finishes normally. go vet reports a missing cancel call.
One context can be handed to many goroutines, and one cancel() stops them all.
After cancel(), ctx.Done() is closed and ctx.Err() returns context.Canceled. The WaitGroup makes main wait until every goroutine has actually returned, which avoids leaks and half-finished work.
WithTimeout is the standard way to bound an operation, such as a database or HTTP call.
ctx.Err() returns context.Canceled after a manual cancel and context.DeadlineExceeded after a timeout or deadline. Compare them with errors.Is. The standard library uses contexts directly: http.NewRequestWithContext, db.QueryContext and exec.CommandContext all stop when the context ends.
Pass ctx down every call that can block, and derive child contexts when a step needs a shorter limit. Cancelling the parent always cancels the child, but not the other way around.
In an HTTP server, r.Context() is cancelled when the client disconnects or the handler returns, so using it for downstream calls stops wasted work automatically.
For several goroutines that can fail, golang.org/x/sync/errgroup combines a derived context with WaitGroup behaviour: the first error cancels the context for the others.
context.WithValue carries data such as a request ID or authenticated user across layers. Use a private key type to avoid collisions and keep values to request-scoped metadata, not optional function parameters.
ctx as the first parameter, named ctx, and do not store it inside a struct for long-lived use.context.TODO() if unsure.cancel, normally with defer.ctx.Done() in loops and in blocking select statements, otherwise cancellation has no effect.context.WithValue only for request-scoped data crossing API boundaries.No. It only closes ctx.Done(). Goroutines must watch the channel and return, which is why cancellation is called cooperative.
WithTimeout(ctx, d) is shorthand for WithDeadline(ctx, time.Now().Add(d)). Use a timeout for a duration and a deadline for a fixed point in time.
The context holds timers and registrations with its parent. Calling cancel frees them even if the work finishes early; skipping it leaks resources until the parent ends.
It is discouraged for normal use because a context belongs to one call. Pass it explicitly as a parameter instead.
Use context to give goroutines a shared lifetime: derive contexts with WithCancel, WithTimeout or WithDeadline, pass them as the first parameter, watch ctx.Done(), always call cancel, and report ctx.Err() with errors.Is. Use errgroup when several goroutines should stop together on the first failure, and keep WithValue for request-scoped data only.