Skip to Content
Skip to content
Catch Goroutine Leaks and Hanging Tests With t.Cleanup and go test -timeout
Advanced
Tutorials

Catch Goroutine Leaks and Hanging Tests With t.Cleanup and go test -timeout

Detect leaked goroutines and deadlocked channels in Go tests using runtime.NumGoroutine, t.Cleanup, and go test -timeout instead of waiting for a 10-minute CI hang. After this, background workers always shut down cleanly before a test exits.

Updated 4 min read GoTesting and Debugging

A unit test that passes in 10 ms can still leak a background goroutine that stays blocked on a channel until the test binary exits. Worse, if a test deadlocks, Go's default test timeout is 10 minutes—meaning one stuck channel stalls your entire CI job for 10 minutes before failing.

You do not need an external library to catch both problems. Combining runtime.NumGoroutine(), t.Cleanup, and go test -timeout catches leaked goroutines immediately and turns deadlocks into fast, readable stack traces.

Skip ahead

Want the reusable helper? Jump to assertNoGoroutineLeak or the CI timeout flags.

Detecting leaked goroutines with t.Cleanup

Snapshot runtime.NumGoroutine() before the test starts its worker, register a t.Cleanup that shuts the worker down, and poll briefly (up to a few hundred milliseconds) for the goroutine count to return to baseline:

package leaks

import (
	"context"
	"runtime"
	"testing"
	"time"
)

func startWorker(ctx context.Context, jobs <-chan int) <-chan struct{} {
	done := make(chan struct{})
	go func() {
		defer close(done)
		for {
			select {
			case <-ctx.Done():
				return
			case _, ok := <-jobs:
				if !ok {
					return
				}
			}
		}
	}()
	return done
}

func assertNoGoroutineLeak(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 TestWorkerShutsDownCleanly(t *testing.T) {
	before := runtime.NumGoroutine()
	ctx, cancel := context.WithCancel(context.Background())
	jobs := make(chan int)
	done := startWorker(ctx, jobs)

	t.Cleanup(func() {
		cancel()
		<-done
		assertNoGoroutineLeak(t, before)
	})

	jobs <- 42
}

Run it with both -race and a tight -timeout:

$ go test -v -race -timeout 10s .
=== RUN   TestWorkerShutsDownCleanly
--- PASS: TestWorkerShutsDownCleanly (0.00s)
PASS
ok  	example.com/leaks	1.007s

Why t.Cleanup beats defer for leak checks

t.Cleanup runs after the test function and any subtests finish, in LIFO order—even if the test calls t.Fatal halfway through. Putting shutdown + leak verification inside t.Cleanup guarantees that a failing assertion earlier in the test still exercises your cleanup path and reports leaks cleanly.

Timeout and concurrency flags to keep in CI

Flag What it catches Recommended CI default
-timeout 30s Blocked channels, missing wg.Done(), deadlocks Fail in 30s with full goroutine dump instead of 10m default
-race Unsynchronized shared reads/writes across goroutines Always on in PR/unit test suites
-count=1 Flaky timing bugs hidden by Go's test result cache Use when reproducing intermittent leaks

💡 Tip

Why wait a few milliseconds in assertNoGoroutineLeak instead of checking once right after cancel()? Even after <-done closes, the Go scheduler may take a brief tick to park or tear down sibling goroutines, and HTTP keep-alive tests using httptest.Server need srv.Close() to finish closing idle client connections first.

Common mistakes

  • Using t.Parallel() with global runtime.NumGoroutine(): Parallel tests share the same process goroutine count, so another test's goroutine triggers false failures. Keep runtime.NumGoroutine() leak checks in non-parallel tests, or use a package like go.uber.org/goleak that inspects stack signatures.
  • Forgetting srv.CloseClientConnections() or client.CloseIdleConnections(): An HTTP client's idle connection pool keeps two background goroutines alive per host until closed.
  • Waiting forever on <-done inside t.Cleanup without -timeout: Always pair blocking waits in tests with go test -timeout so a broken exit path prints the blocked goroutine stack immediately.

⚠ Warning

Never "fix" a flaky goroutine-leak test by adding time.Sleep(500 * time.Millisecond) in production code. If a worker cannot exit deterministically when its context is canceled, the bug is in the worker's select or channel close logic.

What happens if you skip this

Leaked goroutines accumulate silently in long-running services—holding onto request contexts, buffers, and database connections—until memory climbs to the container limit and the process restarts.

Related course: Go Advanced.

About

Detect leaked goroutines and deadlocked channels in Go tests using runtime.NumGoroutine, t.Cleanup, and go test -timeout instead of waiting for a 10-minute CI hang. After this, background workers always shut down cleanly before a test exits.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.