Kiểm tra và ngăn chặn rò rỉ goroutine trong Go · Pattern Quest
#go
#concurrency
#goroutine-leak
#testing
#observability
Kiểm tra và ngăn chặn rò rỉ goroutine trong GoDetecting and Preventing Goroutine Leaks in Go
Cách phát hiện rò rỉ goroutine bằng công cụ, mẫu code và best‑practice để production không sập.Practical ways to spot goroutine leaks, fix common patterns, and keep Go services stable.
Bạn vừa đẩy một thay đổi lên production, nhưng sau một giờ CPU lên 100 % và pprof cho thấy hàng nghìn goroutine treo. Thật là cảnh quen thuộc: một bug nhỏ trong việc quản lý goroutine đã làm dịch vụ sập.
time.Ticker không được Stop() – Khi một ticker được khởi tạo trong vòng đời dài (ví dụ một service singleton) và không được dừng, nó sẽ gửi tín hiệu vô hạn vào channel. Nếu goroutine đang select trên ticker không rời đi, mỗi tick tạo ra một goroutine mới hoặc giữ goroutine hiện tại ở trạng thái blocked.
Goroutine được tạo per‑request mà không truyền context.Context – Khi request timeout hoặc client đóng kết nối, server‑side vẫn còn goroutine đang thực hiện công việc nặng. Vì không có cách nào biết khi nào nên dừng, chúng sẽ tồn tại mãi.
Worker đọc từ channel nhưng kênh không được close() – Khi ứng dụng shutdown, các worker vẫn chờ dữ liệu trên channel mà không bao giờ nhận được nil hoặc close. Kết quả là chúng treo vô hạn.
Go cung cấp một thư viện rất tiện: go.uber.org/goleak. Thêm nó vào test sẽ tự động báo cáo các goroutine còn lại sau khi test kết thúc.
Go
package service_testimport ( "testing" "go.uber.org/goleak")func TestMain(m *testing.M) { // Kiểm tra leak sau khi toàn bộ test chạy xong goleak.VerifyTestMain(m)}
Nếu có leak, goleak in ra stack trace của từng goroutine, giúp bạn xác định nguồn gốc ngay trong CI.
Bạn cũng có thể dùng runtime/pprof trong code production để snapshot goroutine khi load cao:
Always derive new goroutine’s context from the request’s context.
Close every channel you own; nếu không, workers sẽ không biết khi nào dừng.
Run goleak in your test suite để bắt leak trước khi đưa lên production.
Nếu vẫn còn nghi ngờ, chạy go tool pprof trên dump và tìm goroutine có stack “select { case <-time.After … }” – chúng thường là những ticker quên dừng.
Rò rỉ goroutine không phải “điều hiếm” mà là kết quả của một vài thói quen không an toàn. Bằng việc propagate context, đóng ticker/channels, và đưa goleak vào CI, bạn có thể giảm thiểu rủi ro tới mức không còn lo “production sập vì goroutine”. Hãy áp dụng ngay hôm nay và chia sẻ kết quả trong comments!
Dừng ticker bằng defer ticker.Stop() và listen ctx.Done().
Propagate request context.Context và dùng errgroup để tự hủy các goroutine con.
Đóng channel khi không còn công việc; dùng worker‑pool có cancel context.
Kiểm tra leak với go.uber.org/goleak trong test và runtime/pprof trong production.
Thêm -race và goleak vào CI để phát hiện sớm.
Bạn đã từng gặp rò rỉ goroutine nào khiến service dừng? Hãy kể cho mình biết trong phần bình luận nhé!
You just deployed a change and an hour later the CPU spikes to 100 % while pprof shows thousands of idle goroutines. Sound familiar? A tiny oversight in goroutine management can take an entire Go service down.
time.Ticker never stopped – When a ticker lives for the whole lifetime of a service (e.g., a background poller) and you forget to call Stop(), it keeps sending ticks forever. A goroutine that selects on the ticker never exits, effectively holding the goroutine alive.
Per‑request goroutine without context.Context – If you spin up a worker for each HTTP request but don’t tie it to the request’s context, the worker keeps running even after the client disconnects or a timeout occurs.
Workers reading from a channel that is never closed – During graceful shutdown, workers may stay blocked on <-jobs forever because the channel is never closed, leading to a leak.
The Go ecosystem offers a handy library: go.uber.org/goleak. Adding it to your test suite automatically reports any goroutine that remains after a test finishes.
Go
package service_testimport ( "testing" "go.uber.org/goleak")func TestMain(m *testing.M) { // Verify no leaks after all tests run goleak.VerifyTestMain(m)}
If a leak is found, goleak prints a stack trace for each offending goroutine, which is perfect for CI feedback.
You can also take a snapshot with runtime/pprof in production when the load looks abnormal:
Goroutine leaks are rarely mysterious; they are usually the result of a few unsafe habits. By propagating context, stopping tickers, closing channels, and adding goleak to CI, you can shrink the risk to near zero. Try these fixes today and share your experience in the comments!