Stop Goroutine Leaks With select, close(ch), and ctx.Done()
Prevent blocked producer and consumer goroutines from leaking forever by closing channels on the sender side and selecting on ctx.Done(). After this, background pipelines exit cleanly on cancellation.
Skip ahead
Already closing channels from producers? Jump to Case 2: why unbuffered sends leak after timeouts or Case 3: disabling closed branches with ch = nil.
Go makes starting a goroutine trivial, and never garbage-collects a goroutine that is still blocked on a channel. That creates Go's most common concurrency leak: an HTTP handler spawns a background goroutine, times out after 50 ms and returns, and the goroutine finishes at 200 ms only to block forever trying to send its result on an unbuffered channel nobody is reading anymore.
Four concrete channel rules stop every goroutine leak before it reaches production. Verified on Go 1.27 with -race.
Case 1: Producer ownership—only the sender closes a channel
Sending on a closed channel panics, and closing an already-closed channel panics. Keep one strict ownership rule across every package: the goroutine that sends into a channel is the only goroutine allowed to close it (usually via defer close(ch)). Receivers simply range with for v := range ch and exit automatically when the channel closes.
Case 2: Stopping send leaks when a caller times out
Compare an unbuffered channel (make(chan string)) against pairing a capacity-1 buffered result channel with select + ctx.Done():
package main
import (
"context"
"fmt"
"time"
)
func fetchWithTimeout(ctx context.Context, delay time.Duration) (string, error) {
ch := make(chan string, 1) // buffer of 1 lets worker exit even if caller timed out
go func() {
select {
case <-time.After(delay):
ch <- "ok"
case <-ctx.Done():
return
}
}()
select {
case res := <-ch:
return res, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
defer cancel()
_, err := fetchWithTimeout(ctx, 100*time.Millisecond)
fmt.Println("timed out:", err)
}
$ go run -race .
timed out: context deadline exceeded
Why use both case <-ctx.Done() and make(chan string, 1)? Checking ctx.Done() wakes the worker immediately at 15 ms instead of waiting 100 ms; the buffer of 1 protects against the race where the worker completes at the exact same microsecond as the timeout—it drops "ok" into the buffer and exits cleanly so the GC reclaims both the goroutine and the unread channel.
Case 3: Draining two channels without CPU spin using ch = nil
Receiving from a closed channel never blocks—it returns the zero value immediately with ok == false. If a for { select { ... } } loop reads from channels a and b and a closes first, case v, ok := <-a fires millions of times per second unless you disable that branch by assigning a = nil (because a nil channel blocks forever inside select):
package main
import "fmt"
func main() {
a := make(chan string, 1)
b := make(chan string, 1)
a <- "from-a"
b <- "from-b"
close(a)
close(b)
var seen []string
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil // disables this select branch!
continue
}
seen = append(seen, v)
case v, ok := <-b:
if !ok {
b = nil
continue
}
seen = append(seen, v)
}
}
fmt.Println("drained:", len(seen))
}
$ go run -race .
drained: 2
Case 4: Guarding streaming producers with select on every send
In a multi-item pipeline (sending 10,000 items to workers), a capacity-1 buffer is not enough if workers stop early on cancellation. Wrap every send in select:
for _, item := range items {
select {
case jobs <- item:
case <-ctx.Done():
return ctx.Err()
}
}
💡 Tip
Enforce channel ownership at compile time using directional types: func consume(jobs <-chan Job, results chan<- Result). The compiler refuses to let consume call close(jobs).
Common mistakes
- Adding
default:inside afor { select { ... } }loop: Turns blocking waits into a 100% CPU busy-spin loop. - Checking
len(ch) == 0to decide whether a channel is empty before receiving: Another goroutine can change the channel between the check and the receive; useselectinstead. - Forgetting to close a channel consumed by
for v := range ch: Leaves the receiver goroutine parked forever.
⚠ Warning
Before spawning any goroutine, answer one question: "How and when will this goroutine exit?" If you cannot point to the exact channel close or <-ctx.Done() return path, you have a goroutine leak waiting to happen.
What happens if you skip this
Leaked goroutines accumulate silently across timed-out HTTP calls—pinning request contexts, buffers, and stack memory until RSS climbs to the container limit and Kubernetes restarts the pod.
Related course: Go Intermediate.
About
Prevent blocked producer and consumer goroutines from leaking forever by closing channels on the sender side and selecting on ctx.Done(). After this, background pipelines exit cleanly on cancellation.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.