An example of a goroutine leak and how to debug one

When I approach a function that is combining running a piece of code in a goroutine and communication/cancellation using channels, I am usually tempted to look deeper as that is a great place to introduce a goroutine leak pretty easily and these errors are pretty easy to miss even for non-beginner golang developer. And that’s what I did for this piece of code I found in KUDO.

What is a goroutine leak?

Leaking goroutine is basically a type of memory leak. You start a goroutine but that will never terminate, forever occupying a memory it has reserved. To simplify the example I posted from KUDO a bit, this is an example of how one can introduce a goroutine leak into their project.

How to find out if you have a goroutine leak?

Generally speaking, `runtime` package is your friend here. One way is using runtime.NumGoroutine() in a test before and after calling the waitReady function. If number of goroutines before waitReady and after is not the same, you have a leak.

Passionate about traveling, food and programming. Tennis player that works on container orchestration at Mesosphere. Always trying to improve.

Passionate about traveling, food and programming. Tennis player that works on container orchestration at Mesosphere. Always trying to improve.