1. Common causes of goroutine leaks
When you first hear “goroutine leak,” your brain paints something like a “memory leak,” only with tiny green gophers running away from the program. That is almost exactly it: a goroutine stays alive because it is waiting for an event that will never happen again, and nobody “cleans it up.” Go is a polite language: if you start a goroutine, it will not kill it by force while the process is alive.
Strictly speaking, a goroutine leak is a situation where a goroutine is stuck waiting (receive/send/range over a channel/waiting for a timer/waiting for something else) and does not have a guaranteed termination condition. This is dangerous even if “nothing crashes”: such goroutines consume memory (stack, runtime structures), sometimes hold resources (for example, waiting on a channel can keep references to data), and sometimes create the effect that “the program seems to work, but gets heavier and heavier.”
The most unpleasant part: goroutine leaks often do not show up immediately. In one-shot tests everything looks fine, but in a long-running application the goroutine count grows, delays increase, and you begin to suspect that the computer is simply tired of your architecture. It is not tired — it is just honestly doing what you wrote.
Blocking send to a channel without a reader
A very human story: you made a channel, started a goroutine, sent a value — and that’s it. But on an unbuffered channel, sending (ch <- v) blocks until someone performs a receive (<-ch). If there is no reader (or it “left” because of a timeout), the sender hangs forever.
A mini example of “how to make it hurt”:
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
ch <- 1 // will hang: nobody is reading
fmt.Println("unreachable") // unreachable
}()
fmt.Println("main ends") // main ends
}
There is one more nuance here: main will finish — the process will exit — and you may not even notice that the goroutine “leaked.” But if this is not main, but a request handler or a background part of a service, then the stuck goroutine will keep accumulating.
There are three basic remedies, and each has its own contract.
- First remedy: guarantee a reader (that is, build the protocol so that the receive definitely happens). This sounds trivial, but in practice it means: “whoever creates the channel is responsible for making sure someone reads from it.”
- Second remedy: a buffer. A buffer lets the sender “put it down and walk away” if the buffer is not full.
- Third remedy: a non-blocking send via select { case ch <- v: default: }, if losing the value is acceptable by contract (this is important!). The default pattern makes sending a try: “if it can go through right now — send it, otherwise — do not wait.”
Blocking read from a channel where nobody writes and nobody closes
The second classic case: you write a consumer that reads from a channel. And the producer somewhere “changed its mind” and stopped writing. If the producer at the same time does not close the channel, the consumer may wait forever.
Code like this looks logical, but it is very fragile:
package main
func reader(in <-chan int) {
v := <-in // if nobody sends, we hang
_ = v
}
func main() {}
The correct idea here is: if you expect an “end of stream,” you must be able to recognize it. And in channels, “end of stream” is expressed by closing the channel and reading in the form v, ok := <-ch.
A tiny snippet that knows how to finish:
package main
func reader(in <-chan int) {
v, ok := <-in
if !ok {
return // channel is closed — exit cleanly
}
_ = v
}
func main() {}
for range ch, but nobody closes the channel
for range ch is a very convenient pattern: “read until the channel is closed.” But this convenience has an implicit contract built in: someone must close the channel. If nobody closes it, the loop is endless.
The bad scenario usually looks like this: “I read range somewhere, and write somewhere else, and someday it will end.” No, it will not end. Channels cannot guess your intentions.
A good scenario looks like “the producer closes the channel”:
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 3; i++ {
ch <- i
}
close(ch) // important contract!
}()
for v := range ch {
fmt.Println(v) // 0, then 1, then 2
}
}
That tiny close(ch) is like the phrase “that’s it, I’m done, you can disperse.” Without it, the consumer will wait for the “rest of the party.”
The timeout fired, but the rest of the scheme did not stop
A timeout in select is a way to stop waiting at the current point. But a timeout does not kill other goroutines automatically. If you started a goroutine that tries to send you a result, and you left on timeout and no longer read, you can easily get a leak through a blocking send.
This idea follows directly from the basic “timeouts + select” pattern: we “drop the read attempt” on timeout, but that changes nothing for the sender.
The mental model of what happens inside the program often looks like this:
flowchart TD
A[main waits for result] --> B{select}
B -->|case v := <-results| C[success: got v]
B -->|case <-time.After| D[timeout: move on]
E[worker goroutine] --> F[results <- v]
F -->|no reader| G[worker hangs forever]
If after a timeout you do not cancel the workers’ work (via ctx.Done() or another signal) and/or do not provide them with non-blocking send, then the workers may get stuck on sending the result.
select { default: ... } in a loop and a busy loop
Sometimes people learn about default and think: “Oh! I can make a loop that constantly checks the channel but does not block.” You can. It will work. And it will burn CPU like a small jet engine.
A busy loop is not always a “goroutine leak” in the sense of “it waits forever.” But it is a very close relative: the goroutine will not finish and at the same time will keep spinning, occupying one core. In a long-running application the effect is similar: a resource leaks, only it is not memory but CPU time.
A mini anti-example:
package main
func main() {
ch := make(chan int)
for {
select {
case <-ch:
// something was received
default:
// nothing is ready — but we are not waiting, we are spinning
}
}
}
If you need to “wait for an event” — use blocking case clauses without default. If you need a “rare check” — usually you add a blocking case (for example, a timer) or reconsider the design. For today it is enough to remember: default inside a fast for is a red flag.
3. The goroutine completion rule
Here we fix the main thinking tool for all future concurrent Go code. This is not magic — it is discipline: before starting a goroutine, you must answer in words the question “when will it finish?”. If there is no answer, you are already on the path to a leak.
The “completion rule” itself is convenient to formulate like this:
Every started goroutine must have at least one guaranteed exit condition:
closing the input channel, cancellation through ctx.Done(), or completing work without the risk of blocking forever.
To make it easier to apply not in theory but in code, keep a small “protocol table” in your head:
| What the goroutine does | What it can block on | How it knows “time to exit” | Who provides the signal |
|---|---|---|---|
| Consumer reads from in | receive <-in | in is closed (ok == false) | Producer (closes in) |
| Worker waits for a command | receive <-jobs | jobs is closed or ctx.Done() | Coordinator/owner of jobs or whoever cancels ctx |
| Producer sends to out | send out <- v | reader reads, or send is non-blocking, or ctx.Done() | Consumer/channel buffer/context |
| Forwarder in fan-in reads+writes | receive and send | input close or context cancellation | Input producer or cancel |
And yes, this is a “contract” discipline. Concurrent code is 80% contracts and only 20% syntax.
4. Mini case: “first answer wins” without leaks
So the examples do not hang in the air, let’s assume we have a simple educational app in the style of a “task manager”: we have several task sources, and we want to find a task by id as fast as possible. We start several goroutines, and we need the first found result.
Bad version: return the first result, and the rest may hang
Let’s make a simplified “search” using delay:
package main
import (
"time"
)
func findSlow(id int) int {
time.Sleep(50 * time.Millisecond)
return id
}
Now the bad “first answer wins” scheme (note out := make(chan int) without a buffer):
package main
import "time"
func firstResult(id int) int {
out := make(chan int) // unbuffered: risk of hangs
go func() { out <- findSlow(id) }()
go func() { out <- findSlow(id) }()
select {
case v := <-out:
return v
case <-time.After(10 * time.Millisecond):
return -1
}
}
What is wrong: we left on timeout, stopped reading out, and the senders will still try to do out <- ... and may hang. This is exactly the class of problems discussed in classic notes about timeouts and “move on”: if you stop waiting, you must think about the fate of those who are still trying to send you something.
Fix: buffer of 1 and non-blocking send
The most compact and practical version for “first answer wins” is out := make(chan int, 1) and sending via select with default. This approach in this form (non-blocking send) is often cited as the standard one.
package main
func firstResultSafe(id int) int {
out := make(chan int, 1) // exactly enough space for the “winner”
go func() {
v := findSlow(id)
select {
case out <- v:
default:
// someone has already won
}
}()
go func() {
v := findSlow(id)
select {
case out <- v:
default:
}
}()
return <-out
}
The important contract here: we intentionally “lose” the results of the losers. That is fine, because the business idea of the function is to get the first one.
Fix: cancellation through context
Sometimes “losing” workers cannot simply “quietly finish computation.” Suppose they are doing heavy work or touching an external resource. Then after the winner is found, we want to tell the others: “stop, no need.”
That is exactly the meaning of cancellation through ctx.Done(): one signal for all participants. Documentation and articles about context explicitly stress that context is important so that operations respect cancellation and deadlines — otherwise the system accumulates work and resources.
Let’s simplify: the worker will “wait” via a timer, but can exit on cancellation.
package main
import (
"context"
"time"
)
func findWithCancel(ctx context.Context, id int) (int, bool) {
select {
case <-time.After(50 * time.Millisecond):
return id, true
case <-ctx.Done():
return 0, false
}
}
Now “first answer wins” with cancellation:
package main
import "context"
func firstResultWithCancel(id int) int {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan int, 1)
go func() {
if v, ok := findWithCancel(ctx, id); ok {
select { case out <- v: default: }
}
}()
go func() {
if v, ok := findWithCancel(ctx, id); ok {
select { case out <- v: default: }
}
}()
v := <-out
cancel() // tell the others “wrap up”
return v
}
Here a goroutine has two exit paths: “success” and ctx.Done(). That is the practical implementation of the “completion rule.”
5. How to suspect a goroutine leak
When you are just learning, you do not always have convenient diagnostics, and sometimes you are just writing a small utility. So it is useful to have a “common sense detector.”
If the program hangs on shutdown and you see that WaitGroup.Wait() never returns, that almost always means that some goroutine did not reach Done(). The reason is usually that it got stuck on send/receive, or is waiting for range over a channel that is never closed.
If over time the program starts to “slow down” or “bloat,” especially in a loop (for example, you run the same operation many times), and you suspect that something background remains after every cycle, then the first thought should be: “am I really letting all goroutines finish?” Yes, it sounds boring. Concurrency is a discipline; the fun starts later, when it works.
6. Typical mistakes when working with goroutines and channels
Mistake #1: “I’ll send to a channel, and someone will read it somehow.”
This is the most common reason for stuck goroutines: an unbuffered send requires a reader right now. If the reader leaves due to a timeout, an error, a return, or context cancellation — the sender hangs. The fix is not “let’s add a buffer of 100500,” but an explicit contract: either a guaranteed reader, or a buffer of sufficient size, or a non-blocking send (if loss is acceptable), or cancellation through ctx.Done().
Mistake #2: for range ch without a clear “who closes the channel.”
range over a channel is the contract “I read until close.” If you cannot quickly answer who and where does close(ch), then you do not have a contract, you have hope. Hope is a bad synchronization strategy. Usually the producer closes it, and closes it exactly once, when it is definitely done writing.
Mistake #3: You made a timeout, but not cancellation.
A timeout via time.After or timer.C stops waiting in one place, but the other participants in the scheme keep living. If after that they try to send a result into a channel that nobody is reading anymore, you get a leak. A good pattern: “left on timeout → canceled the context → everyone listening to ctx.Done() exited cleanly.”
Mistake #4: default in select inside a fast loop, followed by surprise ‘why is CPU loaded?’
default is not “wait a little.” It is “do not wait at all.” In a loop that turns into constant spinning. If you really want to wait for an event — remove default and let select block. If you need to wake up periodically — add a blocking case (for example, a timer) and clearly state why.
Mistake #5: The channel is closed by the “wrong” participant or is closed multiple times.
Closing a channel is the responsibility of the data stream owner (usually the producer). If a consumer closes a channel “so that everything finishes,” it will almost certainly one day hit a panic “close of closed channel” or “send on closed channel” (when the producer is still writing). In a fan-in scheme, the out channel is closed by the coordinator after all forwarders finish, not by the forwarders themselves — otherwise closing becomes a race.
GO TO FULL VERSION