A single carelessly written go keyword is enough to bring down a production service through a silent memory leak. Many Go developers are lulled by how cheap goroutines are to create, then fire them into the background with no clear plan for termination. The result is server RAM creeping up for no visible reason, Out-Of-Memory (OOM) kills in the middle of peak hours, and repeated emergency restarts. As Dave Cheney points out, every goroutine still has a real, finite memory footprint. Before you write your next go statement, make sure you know exactly how and when that goroutine will stop.
The illusion that goroutines are free
The Go runtime is built to handle tens to hundreds of thousands of goroutines efficiently. They are far lighter than traditional OS threads, so many engineers treat them as nearly free.
Light does not mean free. Each goroutine needs stack memory (starting at around 2 KB in modern Go, and growing as needed) plus scheduling overhead in the Go scheduler. If your application creates thousands of goroutines every minute and some of them never finish, the leftover memory piles up until the server runs out of room.
Anatomy of a goroutine leak
Consider a pattern that shows up often in production code (adapted from Dave Cheney's example):
ch := someFunction()
go func() {
for val := range ch {
process(val)
}
}()At a glance this looks clean and idiomatic. Now ask one critical question: when does this goroutine exit?
It only stops if the channel ch is closed with close(ch). But ch is created and returned by someFunction(). If an error, an early return, or a later logic change inside someFunction() means the channel never gets closed, the goroutine waits forever. It raises no error, triggers no panic, and quietly eats your server's memory.
The very rare exceptions
Some goroutines are meant to live as long as the application runs, such as a worker watching a config file or the main listener.Accept() loop of an HTTP/TCP server. There are very few of them, and their lifetime is tied directly to the main process (program exit). Outside those cases, every goroutine needs an explicit exit.
How to give a goroutine an exit
To prevent orphaned goroutines, apply these two basic patterns whenever you work with concurrency in Go:
- Use
context.Contextfor cancellation. Always passctxinto the goroutine so it stops as soon as the request finishes, a timeout is hit, or the system performs a graceful shutdown. - Use
selectinside loops. Never block on a channel read or send without an alternative way out.
func startWorker(ctx context.Context, ch <-chan int) {
go func() {
for {
select {
case <-ctx.Done():
// Explicit exit when the context is cancelled
return
case val, ok := <-ch:
if !ok {
// Exit when the channel is closed
return
}
process(val)
}
}
}()
}Conclusion
Writing concurrent code in Go is enjoyable because the syntax is simple. But a Go engineer's discipline is measured not by how quickly they start goroutines, but by how cleanly they stop them.
References
- Dave Cheney, Never start a goroutine without knowing how it will stop (22 December 2016).
