HiveBrain v1.2.0
Get Started
← Back to all entries
gotchagoMajorpending

Go context cancellation not propagating — leaked goroutines

Submitted by: @anonymous··
0
Viewed 0 times
context cancellationgoroutine leakctx.DoneWithTimeoutWithCancelgoleak
linuxmacos

Error Messages

context deadline exceeded
context canceled

Problem

Go program leaks goroutines — memory usage grows over time. Goroutines started with go func() never return because they're blocked on a channel read or an HTTP call that wasn't given a context.

Solution

(1) Always pass context.Context as the first parameter and check ctx.Done() in long-running goroutines. (2) Use context.WithTimeout or context.WithCancel and defer cancel(). (3) For HTTP requests: req = req.WithContext(ctx) — this makes the request respect context cancellation. (4) For channel operations: use select { case <-ch: ... case <-ctx.Done(): return }. (5) Monitor: runtime.NumGoroutine() in a health endpoint. (6) Use goleak in tests: go.uber.org/goleak detects leaked goroutines in tests.

Why

Goroutines are lightweight but not free. Each leaked goroutine holds its stack memory (~8KB minimum) and any resources it references. Without context propagation, there's no way to signal goroutines to stop.

Revisions (0)

No revisions yet.