Context
Carries deadlines, cancellation signals, and request-scoped values.
Understanding Context
The Context pattern carries deadlines, cancellation signals, and request-scoped values across API boundaries and between goroutines. Go\'s context.Context is a built-in interface that propagates cancellation through a tree of goroutines — when a parent context is cancelled, all derived child contexts are cancelled too, enabling graceful shutdown of entire request processing chains. Every HTTP handler, database query, and RPC call in production Go code should accept a context as its first parameter. This is not just a pattern — it\'s a Go standard practice enforced by linters and style guides.
Key Concepts
- •context.Background() — the root context — never cancelled, used as the top of the tree
- •context.WithCancel() — creates a child context with a cancel function that stops all descendants
- •context.WithTimeout() — automatically cancels after a duration — essential for preventing hung operations
- •context.Value() — carries request-scoped data (trace IDs, auth tokens) — use sparingly, not as a general container
When to Use
- • Every HTTP handler, database query, and RPC call (standard Go practice)
- • You need to propagate cancellation through a chain of goroutines
- • You want to set timeouts for long-running operations
- • You need to pass request-scoped values like trace IDs or auth info
- • You\'re using context.Value() as a general-purpose key-value store (anti-pattern)
- • Passing explicit parameters is clearer than hiding data in context
- • The operation is so simple it doesn\'t need cancellation support
Structure
How It Works
Create Context
Parent creates context with cancel or timeout.
Basic Implementation
Context with cancellation signal:
Real-World Example: Timeout Handling
HTTP-style request with timeout: