Golang / GoLang Concurrency Mastery Interview Questions
What causes goroutine leaks and how do you prevent and detect them?
A goroutine leak occurs when a goroutine starts but never terminates — it blocks indefinitely waiting on a channel, lock, or I/O that will never complete. Leaked goroutines accumulate over time, consuming memory and potentially holding references that prevent GC, causing steady memory growth until OOM.
// LEAK 1: nobody ever sends to ch — goroutine parks forever
func leak1() {
ch := make(chan int)
go func() {
v := <-ch // blocks; function returns; nobody sends → leaked
process(v)
}()
}
// FIX: use context for cancellation
func fixed1(ctx context.Context) {
ch := make(chan int)
go func() {
select {
case v := <-ch: process(v)
case <-ctx.Done(): return
}
}()
}
// LEAK 2: jobs channel never closed
func leak2() {
jobs := make(chan Job)
go func() {
for job := range jobs { process(job) } // waits forever
}()
// forgot close(jobs) → goroutine never exits
}
// LEAK 3: time.Ticker never stopped
func leak3() {
ticker := time.NewTicker(time.Second)
go func() {
for range ticker.C { doWork() } // runs forever
}()
// forgot ticker.Stop() → goroutine and channel leaked
}
// DETECTION:
// runtime.NumGoroutine() — watch for steady growth
// /debug/pprof/goroutine?debug=2 — full goroutine stack traces
// goleak library in tests:
// import "go.uber.org/goleak"
// defer goleak.VerifyNone(t) // fails test if goroutines leak
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
