Member-only story
Common Goroutine Leaks that You Should Avoid
Never start a Goroutine without knowing how it will stop.

One of the best things about writing in Go is to be able to run your codes concurrently in light-weighted threads, aka Goroutines.
However, with great power comes great responsibilities.
Though handy, Goroutines can easily introduce bugs that are hardly traceable if not handled with care.
The Goroutine leak is one of those. It grows stealthily in the background and might eventually cripple your application without your knowledge.
Hence, this post is all about what a Goroutine leak is and how you can prevent one from hapenning.
Let’s cut to the chase!
What is a Goroutine Leak?

When a new Goroutine is created, computers allocate memories in heap and release them once the execution is finished.
A Goroutine leak is a memory leak that occurs when a Goroutine is not terminated and is left hanging in the background for the application’s lifetime.
Let’s take a look at a simple example.
As the handler returns, the Goroutine continues to live in the background, blocks and waits for data to be sent over the channel — which is never going to happen.
Hence, introducing a Goroutine leak.
In this article, I’m going to walk you through two common patterns that can easily result in Goroutine leaks
- The forgotten sender
- The abandoned receiver
Jacob Walker explained these patterns exceptionally well in his article and I recommend you to check them out. In this post, I will reiterate them with a few more examples.