Go Developer interview question

How do you prevent goroutine leaks?

A goroutine leak happens when a goroutine blocks forever on I/O, a channel, a lock, or a timer. Give it cancellation, bounded work, and a clear owner that waits for shutdown.

Direct answer

What a strong answer covers

How it works

A goroutine leaks when nothing will ever unblock it: a receive on a channel nobody closes, a send into a full channel with no reader, or a lock held by a goroutine that already exited. Prevention is structural: every goroutine needs an owner that decides when it ends, a cancellation signal it selects on, and bounded work so it cannot run forever. Leaks show up as slowly growing goroutine counts and memory that the garbage collector cannot reclaim.

Example

Pass context.Context into request work and select on ctx.Done(); use a WaitGroup to make lifecycle ownership visible. In a fan-out that queries three backends, a buffered result channel sized to the number of workers lets late responders finish sending even after the caller has returned with the first answer.

Common mistakes

  • Starting a goroutine with go func() and no way to stop it.
  • Sending on an unbuffered channel after the receiver has given up.
  • Ignoring runtime.NumGoroutine in tests that exercise cancellation paths.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Go Developer interview questions