Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # 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 ```go 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. ```go // 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. ```go 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. ```go 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.