Safe Go Context Patterns
Go's context package is essential for cancellation, deadlines, and request-scoped values, but misuse can lead to goroutine leaks, unbounded waits, or flaky tests. Below are idiomatic patterns for deadlines, leak avoidance, and testing, with code examples. These follow Go best practices (e.g., from context docs, Effective Go, and Go team talks like "Context is for cancellation").
1. Deadlines: Propagate Timeouts Down the Call Stack
- Why? Prevents hanging operations; deadlines are absolute (e.g., wall-clock time).
- Pattern: Use
context.WithDeadline (preferred over WithTimeout for sub-contexts, as it inherits parent's deadline). Always check ctx.Err() early and often.
- Safe Example (HTTP handler with DB query):
package main
import (
"context"
"database/sql"
"fmt"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Set deadline 5s from now.
ctx, cancel := context.WithDeadline(r.Context(), time.Now().Add(5*time.Second))
defer cancel() // Always defer cancel!
user, err := getUser(ctx, 123)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "User: %s", user.Name)
}
func getUser(ctx context.Context, id int) (*User, error) {
// Propagate ctx to DB.
row := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id=?", id)
var u User
if err := row.Scan(&u.Name); err != nil {
return nil, fmt.Errorf("query failed: %w (ctx err: %v)", err, ctx.Err())
}
return &u, nil
}
- Pitfall Avoided: No infinite waits;
QueryRowContext cancels on deadline.
2. Leak Avoidance: Select on ctx.Done() + Proper Propagation
- Why? Unchecked goroutines leak memory/CPU; root context must be canceled.
- Pattern:
- Never spawn goroutines without a context.
- Use
select with ctx.Done() as first case.
- Defer
cancel() on every WithCancel/Deadline/Timeout.
- Pass ctx to all children; check
ctx.Err() before/after blocking ops.
- Safe Example (Concurrent fetch with fan-out):
func fetchAll(ctx context.Context, urls []string) ([]string, error) {
ctx, cancel := context.WithCancel(ctx) // Inherit parent.
defer cancel()
results := make(chan string, len(urls))
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
u := url // Capture loop var.
go func() {
defer wg.Done()
select {
case <-ctx.Done(): // First! Drain if canceled.
return
default:
}
data, err := httpGetWithTimeout(ctx, u, 2*time.Second)
if err != nil {
return // Or log; don't block.
}
select {
case results <- data:
case <-ctx.Done():
}
}()
}
go func() {
wg.Wait()
close(results) // Signal done.
}()
var all []string
for data := range results {
all = append(all, data)
}
if ctx.Err() != nil {
return nil, ctx.Err() // Propagate cancellation.
}
return all, nil
}
- Detection Tool: Use
runtime/trace or pprof to spot leaks; go vet warns on ignored contexts.
- Pitfall Avoided: No zombie goroutines; everything cancels cooperatively.
3. Testing: Mock Contexts + Assert on Errors
- Why? Ensures cancellation propagates; catches leaks in CI.
- Pattern:
- Use
context.WithCancel + time.AfterFunc for timeouts.
t.Cleanup(cancel) for auto-cleanup.
- Assert
ctx.Err() != nil and specific errors (context.DeadlineExceeded, context.Canceled).
- Race detector:
go test -race.
- Safe Example (Table-driven tests):
func TestFetchAll(t *testing.T) {
tests := []struct {
name string
urls []string
setup func(ctx context.Context)
wantErr string
}{
{
name: "cancels on timeout",
urls: []string{"https://example.com"},
setup: func(ctx context.Context) {
// Simulate slow op; cancel after 100ms.
time.AfterFunc(100*time.Millisecond, ctx.Cancel)
},
wantErr: context.Canceled.Error(),
},
{
name: "deadline exceeded",
urls: []string{"https://example.com"},
setup: func(ctx context.Context) {
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(-1*time.Second))
t.Cleanup(cancel)
},
wantErr: context.DeadlineExceeded.Error(),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
tt.setup(ctx)
_, err := fetchAll(ctx, tt.urls)
if err == nil || err.Error() != tt.wantErr {
t.Fatalf("expected %q, got %v", tt.wantErr, err)
}
})
}
}
- Advanced: Use
testify/assert for assert.ErrorIs(err, context.Canceled); go test -timeout=10s -race ./....
Quick Checklist
| Aspect | Do ✅ | Don't ❌ |
|---|
| Deadlines | WithDeadline(ctx, t) | Hardcode timeouts |
| Leaks | select { case <-ctx.Done(): } | go func() { ... }() w/o ctx |
| Testing | t.Cleanup(cancel) | Background w/o asserts |
These patterns scale to microservices (e.g., gRPC). For more, see Go Blog: context or Dave Cheney: Context Was Not Made For Signals. Got a specific code snippet to debug? Paste it! 🕵️