context#

context is a standard library package used to manage the lifecycle of goroutines and propagate cancellation signals, deadlines, and request-scoped metadata across API boundaries.

Overview#

A raw done <-chan struct{} channel can only signal goroutines to stop, but cannot convey the reason for cancellation (Why), deadline constraints (When), or request-scoped values (What). context.Context unifies these three responsibilities into a single interface.

Context Interface#

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key any) any
}

Design Philosophy#

  • Immutability: The Context interface itself contains no methods to mutate internal state or invoke cancellation (Cancel).
  • Caller Protection: Functions down the call stack are grammatically prevented from canceling or corrupting upstream contexts.
  • Downward Tree Propagation: Cancellation authority belongs solely to the cancel() function retained by the parent stack frame that derived the context. Cancellation flows strictly downward from parent to children. Canceling a child context never affects its parent or sibling branches.
  • Function Signature Rules: A context is bound to the dynamic lifecycle of a request and must not be stored as a struct member variable. Always pass ctx context.Context explicitly as the first parameter of a function.
  • Separation from Session State: A context is completely decoupled from connection or session state (eg. DB connection pools or gRPC channels). Connection state lives inside the client struct (*sql.DB, *grpc.ClientConn), whereas a context is strictly a per-operation stopwatch and cancellation signal. Therefore, creating (Connect), querying (Query), and closing (Close) the same client instance routinely use different contexts.

Factory Functions#

func Background() Context#

Creates an empty, immortal root context (emptyCtx) that has no cancellation mechanism (Done() returns nil) and can never be canceled directly. Used at the top-level entry point of programs (main), initialization, tests, and incoming requests. To cancel operations starting from Background(), derive a cancelable child context using WithCancel or WithTimeout.

func TODO() Context#

Serves as a temporary placeholder when it is unclear which context to use or when upstream code has not yet provided one.

func WithoutCancel(parent Context) Context#

Returns a copy of parent that retains parent values but is detached from the parent’s cancellation signal (Go 1.21+).


Cancellation#

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)#

  • Wraps parent in a new child context and returns a cancellation function.
  • Calling cancel() closes the ctx.Done() channel and sets ctx.Err() to context.Canceled.
  • Built-in HTTP clients and database drivers in the Go standard library observe cancellation signals to terminate in-flight I/O operations immediately.

Resource Cleanup and defer cancel()#

Every context derived via WithCancel, WithTimeout, or WithDeadline registers runtime timers and internal listeners. The returned cancel() function must be called regardless of success or failure.

  • Omitting cancel() causes memory and goroutine leaks.
  • Unlike closing a closed channel which panics, CancelFunc is idempotent and safe to invoke multiple times.
  • Use defer cancel() to ensure cleanup upon exiting the enclosing scope.

Lifecycle Mismatch Pitfall#

Never pass the request context of an incoming HTTP handler directly to background goroutines that outlive the handler. When the handler returns, the HTTP framework automatically cancels the request context.

// Anti-pattern: Handler return automatically cancels req.Context(), causing background RPCs to fail.
func handler(w http.ResponseWriter, req *http.Request) {
    go doAsyncAudit(req.Context())
    w.WriteHeader(http.StatusOK)
}

// Correct pattern: Pass a context detached from the request cancellation via WithoutCancel.
func handler(w http.ResponseWriter, req *http.Request) {
    go doAsyncAudit(context.WithoutCancel(req.Context()))
    w.WriteHeader(http.StatusOK)
}

Deadline#

  • func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc): Cancels automatically after a relative duration
  • func WithDeadline(parent Context, d time.Time) (Context, CancelFunc): Cancels automatically at an absolute point in time
  • Any timeout configured on a child context is bounded by the deadline of its parent context (the tighter deadline always governs).

Deadline Method and Fail-Fast Optimization#

The Deadline() method returns (deadline time.Time, ok bool). When estimated execution duration of subordinate work is known, check whether the remaining deadline is sufficient before initiating expensive operations.

func executeHeavyRPC(ctx context.Context) error {
    if deadline, ok := ctx.Deadline(); ok {
        // Fail fast if remaining time is less than estimated operation time (5s)
        if time.Until(deadline) < 5*time.Second {
            return context.DeadlineExceeded
        }
    }
    return callRemoteService(ctx)
}

Err Method#

  • Returns nil while ctx.Done() remains open
  • Returns context.Canceled upon manual cancellation
  • Returns context.DeadlineExceeded when a deadline expires

Done Method#

  • Returns a delivery channel (<-chan struct{}) for cancellation signals
  • The channel is closed when the context is canceled manually, times out, or when its parent is canceled
  • Goroutines monitor this channel in select statements to exit promptly

Value#

Used to transport request-scoped metadata across API boundaries and goroutines. Parameters essential to business logic must be passed explicitly in function arguments; reserve context values for operational metadata.

func WithValue(parent Context, key, val any) Context#

  • Returns a child context that wraps parent with a key-value pair.
  • Since each child context references a single parent, ctx.Value(key) performs a Linked List traversal (from child upward to the root).
  • Deep context nesting leads to linear search overhead (O(N)).

Key Uniqueness and Type-Safe Accessor Pattern#

Avoid raw string keys (e.g., "userID"). Define unexported key types and provide exported, type-safe helper functions.

type ctxKey int

const (
    ctxUserIDKey ctxKey = iota
)

// Expose only type-safe accessor functions to external packages.
func WithUserID(ctx context.Context, userID string) context.Context {
    return context.WithValue(ctx, ctxUserIDKey, userID)
}

func UserID(ctx context.Context) (string, bool) {
    val, ok := ctx.Value(ctxUserIDKey).(string)
    return val, ok
}

5 Heuristics for Context Values#

  1. Does the data transit process or API boundaries?: Data confined to local function memory belongs in explicit parameters (eg. Request ID and Trace ID are appropriate).
  2. Is the data immutable?: Mutating data stored in context causes data races.
  3. Does the data trend toward simple types?: Storing complex types causes dependency bloat and circular package imports.
  4. Is the data pure data, not behavior?: Methods and business logic belong on the consumer side.
  5. Does the data decorate operations rather than drive them?: If an algorithm changes its core control branch based on context values, the value is an optional parameter and must be an explicit function argument.