Catch Goroutine Leaks and Slow Tests Early
Write tests that cancel contexts cleanly, use t.Cleanup, and catch leaked goroutines and hangs with go test -timeout. After this, background leaks fail in CI instead of production.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
A Go unit test can pass in 15 milliseconds while quietly leaving a background worker goroutine parked forever on a channel or ticker. Because the test binary exits right after go test finishes, that leak stays completely invisible—until the same component runs inside a long-lived server and slowly leaks thousands of goroutines and connections.
On the flip side, when a channel test deadlocks, Go's default test timeout is 10 minutes—leaving CI jobs frozen for 10 full minutes before printing a stack dump. Combining runtime.NumGoroutine() inside t.Cleanup with go test -timeout catches both bugs immediately.
Skip ahead
If you already verify background goroutine teardown with t.Cleanup and runtime.NumGoroutine() (or goleak) and enforce short -timeout flags in CI, take the section quiz or move on to "Add Retries With Backoff and Jitter."
Experiment 1: Why a passing test can still hide a goroutine leak
Suppose your service starts a background cache refresher using time.NewTicker. If startRefresher forgets to select on <-ctx.Done()—or the caller forgets to cancel ctx—every test run leaves one extra goroutine alive. Even worse, if the refresher returns no done signal, your test cannot prove it actually stopped before checking counts.
Experiment 2: Catching leaks deterministically with done, t.Cleanup, and runtime.NumGoroutine
Look at how three pieces work together below: startRefresher closes a done channel via defer close(done) on exit; the test snapshots before := runtime.NumGoroutine(); and t.Cleanup cancels ctx, waits for <-done, and asserts the goroutine count returned to baseline:
package refresher
import (
"context"
"runtime"
"testing"
"time"
)
func startRefresher(ctx context.Context, interval time.Duration, fn func()) <-chan struct{} {
done := make(chan struct{})
go func() {
defer close(done)
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
fn()
}
}
}()
return done
}
func assertNoLeak(t *testing.T, before int) {
t.Helper()
deadline := time.Now().Add(500 * time.Millisecond)
for time.Now().Before(deadline) {
if runtime.NumGoroutine() <= before {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("goroutine leak: before=%d after=%d", before, runtime.NumGoroutine())
}
func TestRefresherStopsOnCancel(t *testing.T) {
before := runtime.NumGoroutine()
ctx, cancel := context.WithCancel(context.Background())
done := startRefresher(ctx, 5*time.Millisecond, func() {})
t.Cleanup(func() {
cancel()
<-done
assertNoLeak(t, before)
})
time.Sleep(15 * time.Millisecond)
}
$ go test -v -race -timeout 10s .
=== RUN TestRefresherStopsOnCancel
--- PASS: TestRefresherStopsOnCancel (0.02s)
PASS
ok example.com/adv6 1.020s
Experiment 3: Why t.Cleanup + -timeout 10s beats manual cleanup
- Runs even after
t.Fatalf: If an assertion fails halfway through the test body,t.Cleanupstill cancels the background worker and checks for leaks instead of abandoning the goroutine. - Why poll briefly in
assertNoLeak? Even after<-donecloses, the Go scheduler may take a brief millisecond to finish tearing down the exited goroutine's stack (or idle HTTP keep-alive goroutines aftersrv.Close()). A 500 ms polling window avoids false flakes while catching real leaks cleanly. - Fast CI stack traces: If a bug breaks cancellation so
<-doneblocks forever,go test -timeout 10saborts in 10 seconds and prints the exact line where every stuck goroutine is blocked—instead of burning 10 minutes of CI time.
Experiment 4: Finding slow tests before CI drags
As suites grow, a couple of accidental time.Sleep(5 * time.Second) tests quietly slow down every developer's feedback loop. Run go test -v ./... | grep -E "PASS|FAIL" (or gotestsum --format testname) periodically to spot any unit test taking over 500 ms, and pass testing.Short() (go test -short ./...) to guard slow integration tests during tight local iteration.
Common mistakes
- Using global
runtime.NumGoroutine()inside at.Parallel()test: Other parallel tests running in the same process launch and exit goroutines concurrently, causing false failures. KeepNumGoroutinechecks sequential, or usego.uber.org/goleak, which inspects actual goroutine stack signatures. - Forgetting
client.CloseIdleConnections()in HTTP client tests: An*http.Client's transport keeps two background read/write goroutines per host alive until idle connections are closed. - Leaving CI at Go's default 10-minute test timeout: One deadlocked channel stalls the entire PR pipeline for 10 minutes. Always pass
-timeout 30s(or60sfor large suites).
💡 Tip
In Go 1.24+, t.Context() returns a context automatically canceled right before t.Cleanup runs—making it even cleaner to tie background test workers to the test's lifetime.
What happens if you skip this step
Leaked worker goroutines pass every happy-path unit test, then pile up in production holding onto request contexts, buffers, and database connections until the container OOM-restarts.
Why can't you safely put a raw runtime.NumGoroutine() leak check inside a test that calls t.Parallel()?
About
Write tests that cancel contexts cleanly, use t.Cleanup, and catch leaked goroutines and hangs with go test -timeout. After this, background leaks fail in CI instead of production.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.