patterngoMajorpending
Go context propagation and cancellation patterns
Viewed 0 times
contextcancellationtimeoutgoroutinecleanup
Problem
Need to properly propagate cancellation signals through goroutine hierarchies and clean up resources.
Solution
Use context.WithCancel/WithTimeout/WithDeadline for hierarchical cancellation.
Rules:
func processRequest(ctx context.Context) error {
// Create child context with timeout
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel() // Always defer cancel
// Pass context to all downstream calls
result, err := fetchData(ctx)
if err != nil {
return err
}
// Check cancellation in long loops
for _, item := range result.Items {
select {
case <-ctx.Done():
return ctx.Err()
default:
process(item)
}
}
return nil
}Rules:
- Always pass context as first parameter
- Always defer cancel()
- Check ctx.Done() in loops
- Never store context in structs
Why
Context cancellation prevents goroutine leaks and ensures resources are freed when parent operations complete or time out.
Gotchas
- Forgetting defer cancel() leaks resources
- context.Background() should only be used at top level
- context.TODO() is for code that hasn't decided on context yet
Context
Any Go application with concurrent operations or HTTP handlers
Revisions (0)
No revisions yet.