CodeGym /コース /Go SELF /goroutine leaks — typical causes and the "termination rul...

goroutine leaks — typical causes and the "termination rule"

Go SELF
レベル 67, レッスン 4
使用可能

1. Typical causes of goroutine leaks

When you first hear "goroutine leak," your brain draws something like a "memory leak," only with small green gophers escaping from the program. It is almost exactly that: a goroutine stays alive because it is waiting for an event that will never happen again, and nobody "removes" it. Go is a polite language: if you start a goroutine, it will not force-kill it 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 occupy memory (stack, runtime structures), sometimes hold resources (for example, waiting on a channel can retain references to data), and sometimes create the effect that "the program seems to work, but it gets heavier and heavier."

The most unpleasant part is that goroutine leaks often do not show up immediately. In a single-run test everything is fine, but in a long-running application the goroutine count grows, latency increases, and you start suspecting that the computer is just tired of your architecture. It is not tired — it is just honestly doing what you wrote.

Blocking send to a channel with no 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 does a receive (<-ch). If there is no reader (or it "left" due to a timeout), the sender hangs forever.

A mini-example of "how to cause pain":

package main

import "fmt"

func main() {
	ch := make(chan int)

	go func() {
		ch <- 1 // will block: nobody is reading
		fmt.Println("unreachable") // unreachable
	}()

	fmt.Println("main ends") // main ends
}

There is another nuance here: main will finish — the process will finish — 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 accumulate.

There are three basic remedies, and each has its own contract.

  • The first remedy: guarantee a reader (that is, build the protocol so that the receive definitely happens). It sounds trivial, but in practice it means: "the one who creates the channel is responsible for making sure someone reads from it."
  • The second remedy: a buffer. A buffer lets the sender "put it in and leave" if the buffer is not full.
  • The third remedy: non-blocking send through select { case ch <- v: default: }, if losing the value is allowed by the contract (this is important!). The pattern with default makes sending a try: "if it is possible right now — send it, otherwise — do not wait."

Blocking read from a channel where nobody writes and nobody closes

The second classic: you write a consumer that reads from a channel. And the producer somewhere "changed its mind" and stopped writing. If the producer does not close the channel, the consumer can 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 get stuck
	_ = v
}

func main() {}

The right idea here is: if you expect an "end of stream," you must be able to recognize it. And in channels, the "end of stream" is expressed by closing the channel and reading in the form v, ok := <-ch.

A tiny piece that knows how to terminate:

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 a built-in agreement: someone must close the channel. If nobody closes it, the loop is endless.

The bad scenario usually looks like this: "somewhere I read with range, and somewhere I write, 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
	}
}

This little close(ch) is like the phrase "all right, I'm done, you can disperse." Without it, the consumer will wait for "the rest of the party."

The timeout fired, but the other participants 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 pattern "timeouts + select": we "drop the read attempt" on timeout, but that does not make the sender feel better.

The mental picture of what is happening in 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 stuck forever]

If after a timeout you do not cancel the work of workers (through ctx.Done() or another signal) and/or do not provide them with non-blocking sending, then workers can get "stuck" on sending the result.

select { default: ... } inside 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 terminate and will keep spinning, pinning one core. In a long-running application the effect is similar: a resource leaks, only not memory, but CPU time.

A tiny anti-example:

package main

func main() {
	ch := make(chan int)

	for {
		select {
		case <-ch:
			// something received
		default:
			// nothing is ready — but we do not wait, we spin
		}
	}
}

If you need to "wait for an event" — use blocking case without default. If you need a "rare check" — usually you add a blocking case (for example, a timer) or rethink the design. For today, it is enough to remember: default inside a fast for is a red flag.

3. The goroutine termination rule

Here we fix the main thinking tool for all future concurrent Go code. This is not magic, but discipline: before starting a goroutine, you must answer in words the question "when will it end?". If there is no answer, you are already on the path to a leak.

The "termination rule" itself is convenient to formulate like this:

Every started goroutine must have at least one guaranteed exit condition:
closing the input channel, cancellation via ctx.Done(), or finishing work without the risk of getting blocked forever.

To make it easier to apply this not in theory but in code, keep a small "protocol table" in mind:

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 commands 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+sends receive and send input closure 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 response wins" without leaks

To keep the examples from hanging in the air, let's assume we have a simple educational app in the style of a "task manager": we have several sources of tasks, and we want to find a task by id as quickly 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" with a delay:

package main

import (
	"time"
)

func findSlow(id int) int {
	time.Sleep(50 * time.Millisecond)
	return id
}

Now the bad "first response wins" scheme (note the out := make(chan int) without a buffer):

package main

import "time"

func firstResult(id int) int {
	out := make(chan int) // unbuffered: risk of hanging

	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 exact class of problems is 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 response wins" is out := make(chan int, 1) and sending through select with default. This approach in this form (non-blocking send) is often presented as the reference pattern.

package main

func firstResultSafe(id int) int {
	out := make(chan int, 1) // space exactly for the "winner"

	go func() {
		v := findSlow(id)
		select {
		case out <- v:
		default:
			// someone already won
		}
	}()

	go func() {
		v := findSlow(id)
		select {
		case out <- v:
		default:
		}
	}()

	return <-out
}

The important contract here is that we deliberately "lose" the results of the losers. That is fine, because the business idea of the function is to get the first.

Fix: cancellation via context

Sometimes the "losing" workers cannot just "finish silently." Suppose they are doing heavy work or accessing an external resource. Then after the winner is found, we want to tell the others: "stop, do not continue."

That is the meaning of cancellation via ctx.Done(): one signal for all participants. The documentation and articles about context separately emphasize 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" through a timer, but will be able to 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 response 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 "finish up"
	return v
}

Here the goroutine has two exit paths: "success" and ctx.Done(). This is the practical implementation of the "termination 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 exit and you see that WaitGroup.Wait() does not return, this 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 a range over a channel that is not closed.

If over time the program starts to "slow down" or "bloat," especially in a loop (for example, you start the same operation many times), and you suspect that something background remains after each cycle, then the first thought should be: "am I really letting all goroutines finish?" Yes, it sounds boring. Concurrency is discipline; the fun starts later, when it works.

6. Typical mistakes when working with goroutines and channels

Mistake #1: "I'll send to the channel, and someone will read it somehow."
This is the most common cause of stuck goroutines: an unbuffered send requires a reader right now. If the reader left due to a timeout, an error, return, or context cancellation — the sender hangs. The cure 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 via ctx.Done().

Mistake #2: for range ch without a clear "who closes the channel".
range over a channel is the agreement "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 added a timeout, but no cancellation.
A timeout via time.After or timer.C stops waiting in one place, but the other participants remain alive. If after that they try to send a result into a channel that nobody is reading anymore, you get a leak. A good pattern is: "left on timeout → canceled the context → everyone listening to ctx.Done() exited cleanly."

Mistake #4: default in select inside a fast loop, and then surprise "why is CPU load high".
default is not "wait a little." It is "do not wait at all." In a loop this 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 closed multiple times.
Closing a channel is the responsibility of the owner of the data flow (usually the producer). If a consumer closes the channel "so that everything finishes," it will almost certainly eventually hit the 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 have finished, not by the forwarders themselves — otherwise closure becomes a race.

1
タスク
Go SELF, レベル 67, レッスン 4
ロック未解除
デッドロックしない合計
デッドロックしない合計
1
タスク
Go SELF, レベル 67, レッスン 4
ロック未解除
リークのないタイムアウト
リークのないタイムアウト
1
タスク
Go SELF, レベル 67, レッスン 4
ロック未解除
待機なしでの送信
待機なしでの送信
1
タスク
Go SELF, レベル 67, レッスン 4
ロック未解除
勝者とクリーンアップ
勝者とクリーンアップ
1
アンケート/クイズ
Concurrency 3: select、レベル 67、レッスン 4
使用不可
Concurrency 3: select
Concurrency 3: select
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION