Context
context.Context carries a deadline, a cancellation signal, and optional request-scoped values across API boundaries. The first argument of an outgoing call is, by convention, ctx.
Detailed Explanation
A request hits your handler. You query the database, call another service, and wait on a worker. If the client disconnects, all of that work should stop. A Context is the value you pass down so every layer can listen on ctx.Done() and return ctx.Err().
The interface. Done() <-chan struct{} closes when the context is cancelled or the deadline passes. Err() is context.Canceled or context.DeadlineExceeded after that. Deadline() reports a time if one was set. Value(key) looks up a request-scoped value.
Trees, not globals. context.Background() is the empty root. context.TODO() is a placeholder when you have not wired a real context yet. WithCancel, WithTimeout, WithDeadline, and WithValue derive children. Cancelling a parent cancels children. Cancelling a child does not cancel the parent.
Values are for request metadata, not optional parameters. A request ID or a user principal can live in context if the alternative is threading them through twenty unexported helpers. A logger config, a DB pool, or a feature flag should be a function argument or a field on a server struct. Value is untyped and invisible in the signature.
Never store a Context on a struct that outlives a request unless that struct is the request. A background worker should take a context when you start it, not keep the HTTP request's context after the handler returns.
What it costs. Deriving a context is a small allocation. Checking Done in a select is the right cost for cancellable I/O. Ignoring context in a library that can block is the bug: the caller cannot time out.
Code Examples
package main
import (
"context"
"fmt"
"time"
)
func work(ctx context.Context) error {
select {
case <-time.After(50 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
fmt.Println(work(ctx))
}func handler(ctx context.Context, id string) error {
return work(ctx) // pass the same ctx down
}Common Gotchas
`WithValue` is not a typed parameter list
prefer arguments for required dependencies.
Using the request context after the handler returns cancels in-flight work you meant to keep
derive `context.WithoutCancel` (Go 1.21+) or `Background` plus a new timeout for detached work.
Always `defer cancel()` on contexts you create
skipping it leaks a timer for timeout contexts.
`TODO()` is visible in traces as "I did not have a context"
replace it before production paths harden.