Why context matters
In most real applications, operations don't run in isolation. An HTTP handler spawns a database query, which might trigger a cache lookup, which calls an external API. These operations are chained, so if the original request is cancelled (the user closes the browser, for example), every downstream operation should stop too.
The context package gives you a standard way to carry cancellation signals, deadlines and request-scoped values across API boundaries and between goroutines.
Without it, you would need to invent your own cancellation channels, pass them everywhere and coordinate teardown by hand. The context package puts all of that behind one standard interface.
The Context interface
The context package defines a single interface:
type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key any) any}Each method represents one capability:
| Method | What it tells you |
|---|---|
Deadline() | Returns the time when the context will be cancelled, if one was set |
Done() | Returns a channel that is closed when the context is cancelled or times out |
Err() | Returns context.Canceled or context.DeadlineExceeded after Done is closed |
Value(key) | Returns the value associated with a key stored in the context |
You rarely implement this interface yourself. Instead, you use the functions the package provides to create and derive contexts.
Root contexts
Every context tree starts from a root. The package provides two constructors for this:
ctx := context.Background()ctx := context.TODO()context.Background() is the conventional starting point. You call it at the top of your program (in main, in a server's request handler setup, or at the root of a test) and then derive child contexts from it.
context.TODO() signals that you haven't decided what context to use yet. It behaves identically to Background() at runtime, but it marks code that needs revisiting. It's a useful placeholder when you're adding context support to existing code incrementally.
General rules
The context package comes with a few conventions that the Go community treats as firm rules.
Context should be created at the top of the call. Don't create a context deep inside a function and let it escape upward. The context's lifecycle should reflect the lifecycle of the operation it governs, which starts at the entry point.
Context is the first parameter of a function. By convention, if a function accepts a context, it is always the first parameter and always named ctx:
func fetchUser(ctx context.Context, id int) (*User, error) { // ...}With that convention, you can tell at a glance which functions take part in cancellation and deadlines.
Never store context in a struct field. Contexts are request-scoped. Storing them in a struct implies they could outlive the request or be reused across requests, and both lead to bugs. Pass context as an explicit parameter every time.
Never mutate a context. Each derivation function (like WithCancel or WithValue) returns a new context. The original is never modified. This immutability makes it safe to pass contexts across goroutines without synchronization.
Deriving contexts
You don't use root contexts directly for most operations. You derive a new context from them (adding cancellation, a deadline or a value) and pass the derived context downstream. Each derived context is a child of its parent; cancelling a parent cancels all its children automatically.
WithCancel
context.WithCancel returns a child context and a cancel function. Calling cancel closes the context's Done channel, signalling all receivers that they should stop work:
ctx, cancel := context.WithCancel(context.Background())defer cancel()go func() { select { case <-ctx.Done(): fmt.Println("goroutine cancelled:", ctx.Err()) return case <-time.After(5 * time.Second): fmt.Println("goroutine finished work") }}()time.Sleep(2 * time.Second)cancel() // fires before the 5s timer, so the goroutine exits earlyDon't skip the defer cancel(). If you never call cancel, you leak resources: the runtime holds onto internal state associated with the context until it's cancelled or its parent is cancelled. Always defer cancel() immediately after calling WithCancel.
WithTimeout and WithDeadline
context.WithTimeout is the most common way to enforce a maximum duration on an operation:
ctx, cancel := context.WithTimeout( context.Background(), 3*time.Second,)defer cancel()url := "https://api.example.com/data"req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)resp, err := http.DefaultClient.Do(req)if err != nil { // err wraps context.DeadlineExceeded if the timeout fires first fmt.Println("request failed:", err) return}defer resp.Body.Close()context.WithDeadline does the same thing, but you specify an absolute point in time instead of a duration:
deadline := time.Now().Add(3 * time.Second)ctx, cancel := context.WithDeadline(context.Background(), deadline)defer cancel()Both functions return the same kind of context: WithTimeout is just a shorthand for WithDeadline(parent, time.Now().Add(timeout)).
When the deadline passes, ctx.Done() is closed and ctx.Err() returns context.DeadlineExceeded. Well-behaved libraries (like the standard net/http client) check the context and return promptly when this happens.
WithValue
context.WithValue lets you attach a value to a context that can be retrieved anywhere downstream:
type contextKey stringconst requestIDKey contextKey = "requestID"func middleware(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { id := generateRequestID() ctx := context.WithValue(r.Context(), requestIDKey, id) next.ServeHTTP(w, r.WithContext(ctx)) } return http.HandlerFunc(fn)}func handler(w http.ResponseWriter, r *http.Request) { id := r.Context().Value(requestIDKey).(string) fmt.Fprintf(w, "request ID: %s", id)}A few details about WithValue:
- The key must be a comparable type. Use a private named type (like
contextKeyabove) instead of a barestringto avoid collisions with other packages that might use the same string literal. - Values stored in context should be request-scoped: request IDs, authentication tokens, tracing metadata. Don't use context as a way to pass optional function parameters.
Valuetraverses the context chain from child to parent, so a value set in a parent context is visible to all its descendants.
Context in practice
HTTP request handling
Every *http.Request carries a context accessible via r.Context(). When the client disconnects, Go's HTTP server cancels that context automatically. Any database query or downstream call made with that context is cancelled too, without extra wiring:
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) { ctx := r.Context() user, err := h.db.QueryUser(ctx, r.PathValue("id")) if err != nil { if errors.Is(err, context.Canceled) { // client disconnected — no point writing a response return } http.Error(w, "internal error", http.StatusInternalServerError) return } json.NewEncoder(w).Encode(user)}Database queries
Most database drivers for Go accept a context. Passing the request context to your queries means they're automatically cancelled when the caller goes away:
func (db *DB) QueryUser( ctx context.Context, id string,) (*User, error) { const q = "SELECT id, name FROM users WHERE id = $1" row := db.pool.QueryRowContext(ctx, q, id) var u User if err := row.Scan(&u.ID, &u.Name); err != nil { return nil, err } return &u, nil}Long-running goroutines
Background workers and other long-running goroutines can use the context as their shutdown signal:
func worker(ctx context.Context, jobs <-chan Job) { for { select { case <-ctx.Done(): fmt.Println("worker shutting down:", ctx.Err()) return case job, ok := <-jobs: if !ok { return } process(job) } }}The select statement checks both the job channel and ctx.Done() on every iteration. When the context is cancelled, whether by a timeout, a manual cancel() call or a parent cancellation, the goroutine returns without polling or busy-waiting.
Passing a context through every call can feel like overhead at first. Once cancellation flows from the outermost request into your goroutines and database calls, though, ending the request stops all of that work without leaking resources.