context.Context carries deadlines, cancellation signals, and request-scoped values across API boundaries—essential in HTTP handlers and gRPC services.
Cancellation
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
}
Pass ctx as the first parameter to functions that may block—never store contexts in structs long-term.
Production usage
Kubernetes operators, cloud SDKs, and microservices propagate cancellation when clients disconnect—prevents goroutine leaks.
Important interview questions and answers
- Q: Why context first parameter?
A: Convention for cancellation propagation—tools and linters expect it. - Q: context.WithValue abuse?
A: Use sparingly for request metadata—not a general dependency injection bag.
Self-check
- What does WithTimeout return?
- Why defer cancel()?
Context tree
Derive child contexts with WithCancel, WithTimeout, or WithDeadline. Cancelling a parent cancels children—propagate from HTTP request context downward.
Avoid context.WithValue for optional parameters—use explicit function args. Values are for request-scoped IDs traceable across middleware.
Tip: Pass context.Context as the first parameter—never store it in structs; cancel propagates down the call tree.
Interview prep
- Context first param?
Convention for cancellation/deadline propagation—linters and stdlib expect it.
- WithValue abuse?
Use sparingly for request-scoped metadata—not a general DI container.