Go: Fix a goroutine leak in a timeout wrapper — learn buffered channels and select


Go goroutine leak debugging exercise — identify why a timeout wrapper that calls a slow upstream function leaks one goroutine per timed-out request, causing unbounded memory growth in production. The root cause is an unbuffered channel: when the timeout fires and the caller exits the select, no receiver is left for the goroutine's send, which blocks forever. A goroutine blocked on a channel send cannot be garbage collected. Learn the difference between buffered and unbuffered channels, why capacity-1 buffered channels are the standard fix for this pattern, and how runtime.NumGoroutine helps detect leaks. Covers goroutine lifecycle management, select statement behavior, time.After usage, and the cost of leaked goroutines under sustained load. Both the leaking and fixed implementations are provided with explanation.

Comments

No comments yet. Be the first to share your thoughts.
Advanced
0.0 (0)

Author

Software engineer and the creator of the Bytestark learning platform