Better Programming

Advice for programmers.

Follow publication

Member-only story

Common Goroutine Leaks that You Should Avoid

Jason Ngan
Better Programming
Published in
5 min readFeb 21, 2022
Photo by Luis Quintero on Pexels

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?

Photo by Wallpaper Access

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Jason Ngan
Jason Ngan

Write a response