How does `sync.WaitGroup` work?

Updated Apr 28, 2026

Short answer

sync.WaitGroup is used to wait for a collection of goroutines to finish executing.

Deep explanation

It uses a counter. You call Add(n) before launching n goroutines. Inside each goroutine, you call Done() (usually deferred) when it finishes. The main thread calls Wait(), which blocks until the counter goes back to zero.

Real-world example

Waiting for 5 independent microservice REST calls to finish concurrently before aggregating the results and responding to a client.

Common mistakes

  • Calling `Add()` inside the goroutine instead of before launching it. This creates a race condition where `Wait()` might execute before `Add()` is called.

Follow-up questions

  • What happens if you call `Done()` more times than `Add()`?

More Golang interview questions

View all →