We are going to discuss safe patterns for using context.Context in Go, focusing on:
Setting deadlines (timeouts and absolute deadlines)
Avoiding goroutine leaks by ensuring cancellation
Testing with contexts
Let's break it down.
1. Setting Deadlines
We use context.WithTimeout and context.WithDeadline to set a time limit for operations.
Example with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Example with deadline:
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
defer cancel()
Best practices:
Always defer the cancel function to avoid resource leaks (unless you want to cancel earlier).
If you are setting a deadline based on a time that is in the past, WithDeadline returns an already canceled context.
Be aware that the timeout/deadline is relative to the time of the call to WithTimeout/WithDeadline.
2. Avoiding Goroutine Leaks
Goroutine leaks happen when a goroutine is blocked on a channel send/receive or a system call and never exits.
Using context for cancellation can help avoid leaks:
Pass the context to any goroutine that might outlive the current function.
In the goroutine, select on ctx.Done() to break out when cancellation is requested.
Example:
func worker(ctx context.Context, workCh <-chan Work) {
for {
select {
case work := <-workCh:
process(work)
case <-ctx.Done():
return // exit the goroutine
}
}
}
// In the calling function:
ctx, cancel := context.WithCancel(context.Background())
workCh := make(chan Work)
go worker(ctx, workCh)
// When done, call cancel() to signal the worker to exit.
Important:
Make sure to close channels that the goroutine is reading from when the goroutine might be waiting on them, but note that the context cancellation is a signal to exit and the goroutine should not rely on channel closure if the channel is used for multiple purposes.
If the goroutine is reading from a channel that might be closed by another part of the program, you can handle both the channel and the context in the same select.
3. Testing with Contexts
In tests, we often want to set a timeout to prevent tests from hanging.
Another pattern: using the test's context (if the test framework provides one). In Go 1.20+, testing.T has a Context method that returns a context that is canceled when the test or benchmark times out or fails.
However, note that the test's context might not have a timeout set by default (it depends on the test timeout set by -timeout flag). So if you need a specific timeout, you can wrap it:
But note: if the test already has a timeout (from the -timeout flag) and you set a shorter one, the test might be canceled by the outer context first. It's usually safe to set a timeout within the test's context.
Additional Patterns
Storing context in structs
It is generally not recommended to store a context in a struct because the context should be the first parameter and flow through the call chain. However, if you must, make sure the context is cancelable (i.e., from WithCancel, WithTimeout, or WithDeadline) and that you cancel it when the struct is no longer needed.
But note: if you store a context in a struct and then use it across multiple methods, you might lose the ability to control the cancellation per call. It's better to pass context as a parameter to each method.
Using context.TODO and context.Background
Use context.Background() at the top of your main function or in tests when no context is available.
Use context.TODO() when you are not sure what context to use and you plan to add it later.
Avoid using context.Background() in library code because the library user might want to control the cancellation. Instead, require a context parameter.
Checking ctx.Done() in long-running operations
If you have a loop or a long-running operation, check ctx.Done() periodically to allow cancellation.
Example:
code
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// do work
}
}
But note: checking too frequently might impact performance. Adjust the frequency based on the work.
Propagating context cancellation
When you start a goroutine, pass the context so that the goroutine can be canceled when the parent context is canceled.
Example:
code
func parent(ctx context.Context) {
childCtx, cancel := context.WithCancel(ctx)
go child(childCtx)
// ...
// When we want to cancel the child, we call cancel().
// But note: if the parent context is canceled, the childCtx will also be canceled because it is derived from ctx.
}
However, if you create a child context with WithCancel and then call cancel(), it will cancel the child context but not the parent. If you want to cancel the entire chain, you should cancel the parent context.
Alternatively, you can just pass the parent context to the child without creating a new one if you don't need to cancel the child independently.
Summary
Use WithTimeout and WithDeadline to set time limits.
Always defer cancel() when you create a cancelable context (unless you have a reason not to).
Pass context to goroutines and select on ctx.Done() to exit.
In tests, use a timeout to avoid hanging tests.
Avoid storing context in structs; pass it as a parameter.
Remember: context is for cancellation, deadlines, and passing request-scoped values. Use it for controlling the lifetime of operations.
Here are safe patterns for using Go's context.Context, focusing on deadlines, leak avoidance, and testing:
1. Deadline/Timeout Patterns
Always Call defer cancel()
When creating a cancelable context (WithCancel, WithTimeout, WithDeadline), immediately defer cancel():
go
ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel() // Ensures resources are freed even on early returns
Check ctx.Err() periodically in long-running loops:
go
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// Process batch, but check periodically
if time.Since(start) > ctx.Deadline().Sub(time.Now()) {
return context.DeadlineExceeded
}
// ... work
}
}
2. Goroutine Leak Avoidance
Always Pass Context to Goroutines
go
func startWorker(ctx context.Context, tasks <-chan Task) {
go func() {
for {
select {
case task := <-tasks:
process(task)
case <-ctx.Done():
return // Clean exit
}
}
}()
}
Never Store Context in Structs (Usually)
Context should flow through function parameters, not be stored:
go
// ❌ Avoid:
type Service struct {
ctx context.Context // BAD: Stale context, hard to test
}
// ✅ Prefer:
func (s *Service) Do(ctx context.Context, arg Arg) error {
// ctx passed explicitly
}
Cancel Derived Contexts Explicitly
If you create child contexts, cancel them when no longer needed:
func TestCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done() // Should unblock
}()
cancel() // Trigger cancellation
wg.Wait() // Ensure goroutine exited
}
Use t.Cleanup for Test Teardown
go
func TestResource(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel) // Guarantees cleanup even if test fails
// Use ctx in test
}
4. Common Anti-Patterns to Avoid
❌ Never Ignore ctx.Done()
go
// BAD: Goroutine may leak if parent cancels
go func() {
result := longRunningOperation() // No context check!
send(result)
}()
// GOOD:
go func() {
select {
case result := <-longRunningOpChan:
send(result)
case <-ctx.Done():
return
}
}()
❌ Don't Pass context.Background() Deeply
If a function requires context, pass it from the caller—don't create new Background() contexts mid-stack.
❌ Avoid Channel Closure for Cancellation
Use context cancellation, not channel closure, to signal cancellation:
go
// BAD: Closing channel to cancel can cause panics if multiple senders
close(workChan)
// GOOD: Use context cancellation instead
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()