When you create a cancelable context using functions like context.WithCancel, context.WithTimeout, or
context.WithDeadline, these functions return two values: a new context and a cancel function.
The cancel function is crucial for proper resource management. It releases resources associated with the context, such as timers and goroutines. If
you don’t call the cancel function, these resources may leak, leading to memory consumption and potential performance issues.
The Go runtime cannot automatically clean up these resources because it doesn’t know when you’re done with the context. Only your code knows the
appropriate time to release these resources.
Using defer cancel() immediately after creating the context ensures that cleanup happens automatically when the function returns,
regardless of how the function exits (normal return, early return, or panic). This follows the Go idiom of acquiring resources and immediately
scheduling their cleanup.
What is the potential impact?
Failing to call the cancel function can lead to:
- Memory leaks: Uncanceled contexts may hold references to resources that cannot be garbage collected
- Goroutine leaks: Background goroutines associated with timeouts may continue running indefinitely
- Resource exhaustion: In high-traffic applications, accumulated leaks can consume significant system resources
- Performance degradation: Leaked goroutines and timers can impact application performance over time