The context package carries cancellation signals, deadlines, and request-scoped values across API boundaries and between goroutines. You use it to tell background work when to stop: when a request ends, a timeout expires, or a parent operation fails. Without it, goroutines can keep running after nobody needs their result, which leaks memory, connections, and CPU.
A context.Context is immutable. You derive child contexts from a parent, and cancelling the parent cancels every child.
context.WithCancelContext is an interface with four methods: Done() returns a channel closed on cancellation or deadline, Err() explains why it ended, Deadline() reports the deadline if one is set, and Value(key) returns a request-scoped value.
You start from one of two roots:
context.Background() for main, initialisation, and tests: the top of a call tree.context.TODO() as a placeholder when you have not yet decided which context to pass.Neither root is ever cancelled. Real lifetimes come from the derived contexts below.
context.WithCancelWithCancel returns a child context and a cancel function. Calling cancel closes the context's Done channel, and every goroutine listening on it can stop.
Always call cancel, usually with defer cancel(), even when the work finishes normally. Skipping it leaks the resources tied to the child context until the parent is cancelled. go vet flags the missing call.
WithTimeout(parent, d) cancels automatically after a duration. WithDeadline(parent, t) does the same at an absolute time. In both cases ctx.Err() returns context.DeadlineExceeded when the time runs out.
Check the cause with errors.Is(err, context.DeadlineExceeded) or errors.Is(err, context.Canceled). A child can only shorten its parent's deadline, never extend it.
Since Go 1.20, context.WithCancelCause lets the canceller record why, and context.Cause(ctx) reads it back. This is useful when Err() alone (context.Canceled) is too vague.
Go 1.21 added context.AfterFunc(ctx, f), which runs f in its own goroutine once the context is done, and context.WithoutCancel(parent), which keeps the parent's values but detaches from its cancellation. The latter is handy for cleanup or audit writes that must finish even after the request was cancelled.
WithValue attaches a key and value to a context. Use it only for data that travels with a request, such as a request ID or the authenticated user, and not for optional function parameters.
Use an unexported custom type as the key to avoid collisions with other packages, and wrap access in typed helper functions as shown.
Every *http.Request carries a context through r.Context(). It is cancelled when the client disconnects or the handler returns, so pass it down instead of creating a new Background.
The same pattern applies to database/sql (QueryContext, ExecContext), net dialers, gRPC calls, and most modern client libraries.
ctx as the first parameter, named ctx, to every function that blocks or does I/O.context.TODO() if unsure.cancel function returned by the With* constructors.ctx.Done() in loops and before blocking operations so goroutines can exit promptly.golang.org/x/sync/errgroup with errgroup.WithContext cancels the rest when one fails.context.Canceled means someone called cancel (or the parent was cancelled). context.DeadlineExceeded means a timeout or deadline expired. Both are returned by ctx.Err().
No. Cancellation is cooperative. The goroutine must check ctx.Done() or call APIs that accept the context. Otherwise it keeps running.
Normally no. Derive from r.Context() so the work stops when the client leaves. Use context.WithoutCancel only when work must outlive the request.
Yes. Contexts are immutable and safe for concurrent use.
The context package gives every operation a shared lifetime: cancel it, give it a deadline, or attach request metadata. Pass it as the first argument, derive children with WithCancel, WithTimeout, or WithDeadline, always call cancel, and make goroutines select on ctx.Done() so they stop when the work no longer matters.