Fix Unbuffered Channel Deadlocks & Goroutine Leaks in Go
Why unbuffered channels hang forever without a receiver, and how context.Context + select prevent goroutine leaks.
By the end of this tutorial you will know:
- Why an unbuffered channel blocks until both sender and receiver are ready
- How a slow or cancelled caller silently leaks goroutines in production
- How to combine
context.Contextandselectso every goroutine exits cleanly
Prerequisites: Go 1.20+ installed and basic familiarity with goroutines.
1. The big idea
Think of an unbuffered channel (make(chan T)) like handing a physical parcel directly to another person. You cannot let go until they reach out and take it. If nobody is standing there to receive, you stand frozen forever—and in Go, that frozen goroutine never gets garbage-collected.
When a request times out and your handler returns early, any background goroutine still waiting to send on an unbuffered channel stays stuck in memory until the process restarts.
2. Reproducing the deadlock & leak
Here is a classic pattern that looks harmless at first glance: a worker computes a result and sends it back, while the caller gives up after 50ms.
package main
import (
"fmt"
"time"
)
func fetchSlow() (string, error) {
ch := make(chan string) // unbuffered!
go func() {
time.Sleep(200 * time.Millisecond)
ch <- "result" // blocks forever if the caller already left
}()
select {
case res := <-ch:
return res, nil
case <-time.After(50 * time.Millisecond):
return "", fmt.Errorf("request timed out")
}
}When time.After(50 * time.Millisecond) fires, fetchSlow returns. Nobody will ever read from ch, so the anonymous goroutine hangs on ch <- "result" for the lifetime of your server.
3. The fix: context.Context + select
Pass a context.Context into the worker, and wrap the send inside a select that also listens to <-ctx.Done(). Also remember: only the sender should close a channel, never the receiver.
package main
import (
"context"
"fmt"
"time"
)
func fetchSafe(ctx context.Context) (string, error) {
ch := make(chan string, 1) // buffer of 1 is an extra safety net
go func() {
defer close(ch)
select {
case <-time.After(200 * time.Millisecond):
select {
case ch <- "result":
case <-ctx.Done():
}
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(), 50*time.Millisecond)
defer cancel()
_, err := fetchSafe(ctx)
fmt.Println("Result:", err)
}Result: context deadline exceededRun go run fixed.go. You should see Result: context deadline exceeded, and both goroutines exit immediately without leaking.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
Sending on make(chan T) on the main goroutine | fatal error: all goroutines are asleep - deadlock! | Send from a separate goroutine or use a buffered channel |
| Closing a channel from the receiver | panic: send on closed channel | Always close from the sender side (or use ctx.Done()) |
Ignoring ctx.Done() during send | Silent memory/goroutine growth over days | Wrap sends in select { case ch <- v: case <-ctx.Done(): } |
5. What you learned
You now know how unbuffered channels synchronize sender and receiver, why early returns leak goroutines, and how context.Context + select keeps your concurrent Go services leak-free.