The context package carries cancellation signals, deadlines and request-scoped values across API boundaries and between goroutines. You create a derived context with context.WithCancel, context.WithTimeout or context.WithDeadline, pass it as the first argument (ctx context.Context) to every function that does blocking work, and have that work stop when ctx.Done() is closed.
Cancelling a parent context cancels every context derived from it, which is how one failed request can stop all the goroutines it spawned.
Every context tree starts at a root:
context.Background() is the empty root, used in main, init, tests and top-level code.context.TODO() is a placeholder for code that has not yet been wired to receive a context.Each With... function returns a child context and a CancelFunc. Always call the cancel function, usually with defer cancel(), even if the timeout would fire anyway. Otherwise the child stays registered with its parent and leaks resources until the parent ends. The go vet tool reports a missing cancel call.
WithCancel gives you manual control. Workers watch ctx.Done() in a select:
ctx.Err() returns context.Canceled after cancellation. Waiting on a WaitGroup is more reliable than a fixed time.Sleep, because it proves the goroutines finished.
WithTimeout(parent, d) cancels automatically after the duration d. It is the standard way to bound calls to databases, HTTP services and other slow dependencies.
When a timeout expires, ctx.Err() returns context.DeadlineExceeded. Compare with errors.Is, because libraries often wrap the error.
WithDeadline(parent, t) uses an absolute time instead of a duration. WithTimeout(parent, d) is simply WithDeadline(parent, time.Now().Add(d)). Use a deadline when several steps must finish by one fixed moment, and read it back with ctx.Deadline().
If the parent already has an earlier deadline, the child keeps the earlier one. A child can only shorten the time limit, never extend it.
Standard library and driver APIs accept a context so cancellation reaches the network:
In an HTTP server, r.Context() is cancelled when the client disconnects or the handler returns. Derive your own timeouts from it instead of from context.Background():
Since Go 1.20, context.WithCancelCause lets the canceller record why, and context.Cause(ctx) reads it, while ctx.Err() still returns context.Canceled. Go 1.21 added context.AfterFunc to run a function in its own goroutine once a context is done, and context.WithoutCancel to keep values from a parent while detaching from its cancellation, which is useful for cleanup work that must outlive a request.
context.WithValue attaches request-scoped data such as a request ID or an authenticated user. Use a private key type to avoid collisions, and do not use it for optional function parameters:
Best practices:
ctx as the first parameter, named ctx.context.TODO() if unsure.ctx.Done() in loops and before slow steps so cancellation is honoured promptly.WithTimeout takes a duration from now and WithDeadline takes an absolute time.Time. They produce the same kind of context and return the same error, context.DeadlineExceeded.
No. Cancellation is cooperative: the goroutine must observe ctx.Done() or call APIs that accept the context, and then return.
Calling cancel releases the timer and removes the child from its parent immediately. Skipping it keeps those resources alive until the timeout fires or the parent is cancelled.
No. Keep values to request-scoped metadata such as trace IDs. Pass real inputs as ordinary function arguments.
Use context to propagate cancellation, timeouts and deadlines through every layer of a Go program. Create contexts with WithCancel, WithTimeout or WithDeadline, always defer the cancel function, pass ctx as the first argument, and make long-running code watch ctx.Done(). Compare errors with errors.Is against context.Canceled and context.DeadlineExceeded.