Go Academy · Lesson

Leak Detection and Cancellation

Ensuring goroutines exit and preventing leaks

Lesson 4 of 413 steps

Leak Detection and Cancellation is a free Go Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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 goroutine

Detecting 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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Leak Detection and Cancellation” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Leak Detection and Cancellation”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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

  1. Pipeline and Stage Patterns
  2. errgroup for Concurrent Error Handling
  3. Semaphore Pattern
  4. Leak Detection and Cancellation
← Back to Go Academy