Leak Detection and Cancellation
Ensuring goroutines exit and preventing leaks
Leak Detection and Cancellation is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is a goroutine leak?
A goroutine leak occurs when a goroutine starts but never terminates. Leaked goroutines accumulate over time, consuming stack memory and CPU until the process is killed.
Common leak: blocked channel receive
A goroutine waiting on a channel receive that never gets a value blocks forever:
go func() {
v := <-ch // leaks if no sender and ch is never closed
use(v)
}()Common leak: no done signal
A goroutine in a for loop with no exit condition or done channel runs forever:
go func() {
for {
work()
// no exit condition — leaks
}
}()Detecting leaks with goleak
go.uber.org/goleak verifies that no goroutines are leaked at the end of a test:
func TestMyFunc(t *testing.T) {
defer goleak.VerifyNone(t)
myFunc() // should not leak goroutines
}Context as the cure
The idiomatic way to stop long-running goroutines is a context. Pass ctx to the goroutine and select on ctx.Done().
go func(ctx context.Context) {
for {
select {
case work := <-workCh:
process(work)
case <-ctx.Done():
return // clean exit
}
}
}(ctx)Done channel pattern
For simpler cases without context, use a dedicated done channel. Close it to broadcast stop to all goroutines reading from it.
done := make(chan struct{})
go func() {
select {
case v := <-data: use(v)
case <-done: return
}
}()
close(done) // stops goroutineDetecting with runtime
Print the number of goroutines to detect growth at runtime:
fmt.Println("goroutines:", runtime.NumGoroutine())HTTP server goroutines
net/http manages goroutines per request automatically and cleans them up when the request finishes. But handlers that launch goroutines without cleanup can still leak.
Testing for leaks
Run your test suite with goleak as a TestMain or per-test defer. Any goroutine not terminated after the test body causes a test failure.
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}Time.After leaks
time.After in a select inside a loop creates a new timer on every iteration that cannot be GC'd until it fires. Replace with time.NewTimer and Reset.
Leak from goroutine returning error
If a goroutine is supposed to send a result on a channel but returns early due to an error without sending, the consumer goroutine blocks forever. Always send or close the channel on all paths.
Quick Check
What is the most idiomatic way to stop a long-running goroutine in Go?
Recap: Leak Detection and Cancellation
Key points:
- Goroutine leaks accumulate; monitor with runtime.NumGoroutine()
- goleak in tests catches goroutine leaks automatically
- Always give goroutines an exit path: context, done channel, or closed input
- time.After in loops leaks timers; use NewTimer+Reset
Frequently asked questions
Is the “Leak Detection and Cancellation” lesson free?
Yes — the full text of “Leak Detection and Cancellation” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Leak Detection and Cancellation”?
Ensuring goroutines exit and preventing leaks You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Leak Detection and Cancellation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Pipeline and Stage Patterns
- errgroup for Concurrent Error Handling
- Semaphore Pattern
- Leak Detection and Cancellation