What is a context in Go and how is it used for cancellation and deadlines?
Learn what context.Context is in Go and how to use it for cancellation, timeouts, and deadlines across goroutines, with code examples and interview tips.
Expected Interview Answer
A context.Context carries cancellation signals, deadlines, and request-scoped values across API boundaries and goroutines, letting you stop work cleanly when it is no longer needed.
You derive a child context with context.WithCancel, context.WithTimeout, or context.WithDeadline, then pass it as the first argument to functions. Long-running or blocking operations select on ctx.Done(), which closes when the context is cancelled or its deadline passes; ctx.Err() then reports why. Cancellation propagates down the tree, so cancelling a parent cancels all children, freeing goroutines, connections, and other resources without leaks.
- Propagates cancellation across goroutine trees
- Enforces timeouts and deadlines on operations
- Prevents goroutine and resource leaks
- Carries request-scoped values like trace IDs
- Standard first-argument convention across Go APIs
AI Mentor Explanation
A context is like the captain's power to declare an innings closed: one signal from the top ends the batting for everyone still padded up, and the message travels instantly to the crease so no batter keeps playing pointlessly. A deadline is the overs limit that ends the innings automatically. In Go, cancelling a context is that declaration, telling every goroutine down the field to down tools at once.
Step-by-Step Explanation
Step 1
Start from a root
Begin with context.Background() at the top of a request or main, or context.TODO() when unsure.
Step 2
Derive a child
Use WithCancel, WithTimeout, or WithDeadline to get a child ctx and a cancel function.
Step 3
Pass ctx first
Thread the context as the first parameter into functions and goroutines.
Step 4
Select on Done
In blocking work, select on ctx.Done() to return early when cancelled or timed out.
Step 5
Always call cancel
defer cancel() to release resources even if the operation finishes normally.
What Interviewer Expects
- Context carries cancellation, deadlines, and values
- Deriving children with WithCancel/WithTimeout/WithDeadline
- Selecting on ctx.Done() and checking ctx.Err()
- Passing context as the first argument by convention
- Calling cancel to avoid leaks
Common Mistakes
- Forgetting to call the cancel function, leaking resources
- Storing a context in a struct instead of passing it explicitly
- Using context.Value for optional parameters instead of request-scoped data
- Ignoring ctx.Done() in long-running loops
- Passing nil context instead of context.TODO()
Best Answer (HR Friendly)
“A context in Go is a small object passed through a request that lets you signal 'stop now' or set a time limit, so background work can be cancelled cleanly. It prevents wasted effort and leaks by telling every part of an operation to shut down when the work is no longer needed.”
Code Example
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case res := <-doWork(ctx):
fmt.Println("result:", res)
case <-ctx.Done():
fmt.Println("failed:", ctx.Err())
}func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return // stop when cancelled or timed out
default:
doChunk()
}
}
}Follow-up Questions
- What is the difference between WithTimeout and WithDeadline?
- When should you use context.Value and when should you avoid it?
- How does cancellation propagate through a context tree?
- Why is context passed as the first argument by convention?
- What does ctx.Err() return after cancellation versus timeout?
MCQ Practice
1. What is the primary purpose of context.Context in Go?
Context propagates cancellation, deadlines, and request-scoped values across API boundaries and goroutines.
2. What does ctx.Done() return?
ctx.Done() returns a channel that is closed when the context is cancelled or its deadline passes, so goroutines can select on it.
3. Why should you defer the cancel function returned by WithCancel?
Calling cancel releases the context's resources; deferring it ensures cleanup even when the operation completes normally.
Flash Cards
What is context.Context? — A value carrying cancellation, deadlines, and request-scoped data across goroutines and APIs.
What does ctx.Done() do? — Returns a channel that closes when the context is cancelled or its deadline passes.
WithTimeout vs WithDeadline? — WithTimeout sets a duration from now; WithDeadline sets an absolute point in time.
Why defer cancel()? — It releases the context's resources and prevents leaks even on normal completion.
Continue Learning
Related Interview Questions
What is the select statement in Go and when do you use it?
medium
How does context cancellation propagate through a Go call tree, and where does propagation typically break?
hard
What is a Mutex in Go and how does it differ from a channel for synchronization?
medium
What is a goroutine leak and how do you detect one in production?
hard