Common Context Mistakes and Anti-Patterns in Go

Avoid nil contexts, cancelled parents, and missing timeouts to prevent hangs and resource leaks in Go.

Common context mistakes in Go involve passing nil contexts, using parent contexts that are already cancelled, or failing to derive new contexts with timeouts for long-running operations. Always derive a new context with context.WithTimeout or context.WithCancel from a valid parent to ensure proper cancellation propagation and resource cleanup.

ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel()
// Use ctx in function calls
result, err := doWork(ctx)