Skip to main content
InterviewHubPRO
Section Overview
Q20

Question 20 of 50

Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)

40%
Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)

How do you prevent Goroutine Leaks in production Go services?

senior LevelCode ExampleGolang

In Simple Words: A Goroutine leak occurs when a goroutine is launched but can never terminate, consuming 2KB–MBs of memory and remaining in memory forever.

Common causes and fixes:

  1. Sending to an unbuffered channel with no receiver: Use a buffered channel of size 1 if only the first response is needed.
  2. Missing cancellation: Always propagate context.WithCancel or context.WithTimeout.
  3. Forgotten ticker cleanup: Always call ticker.Stop() to release runtime resources.
go
// BUG: Leaked goroutine if context times out before response
func leak() {
	ch := make(chan int) // Unbuffered!
	go func() {
		ch <- doSlowWork() // BLOCKS FOREVER if receiver gave up!
	}()
	select {
	case res := <-ch:
		use(res)
	case <-time.After(50 * time.Millisecond):
		return // Leaks the goroutine!
	}
}

// FIX: Buffer of 1 allows sender to write and exit cleanly
ch := make(chan int, 1)