Fix Unbounded Goroutine Spawning with a Bounded Worker Pool
Why launching go handle(item) in a loop exhausts memory and sockets, and how a semaphore or worker pool caps concurrency.
By the end of this tutorial you will know:
- Why spawning a goroutine per item in a large loop can crash a service
- How to cap concurrency with a buffered channel semaphore (
chan struct{}) - How to structure a clean fixed-size worker pool
Prerequisites: Go 1.20+ installed and basic familiarity with goroutines and sync.WaitGroup.
1. The big idea
Goroutines are cheap—about 2 KB of stack each—so it is tempting to write go process(item) inside a for loop. That works for 20 items. At 50,000 items, you suddenly open 50,000 simultaneous database connections, file descriptors, or HTTP sockets, and your server runs out of memory or hits too many open files.
The fix is bounded concurrency: limit how many goroutines can run at the same time.
2. Reproducing the unbounded pattern
// Dangerous when items has 50,000 entries:
for _, item := range items {
go process(item) // no upper limit!
}3. The fix: buffered channel semaphore
A buffered channel of empty structs (sem := make(chan struct{}, maxWorkers)) acts like a parking lot with maxWorkers spaces. Each goroutine takes a space before starting and frees it with defer when done.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
const maxWorkers = 3
sem := make(chan struct{}, maxWorkers)
var wg sync.WaitGroup
for i := 1; i <= 8; i++ {
wg.Add(1)
sem <- struct{}{} // blocks when 3 workers are busy
go func(id int) {
defer wg.Done()
defer func() { <-sem }() // free a slot when finished
fmt.Printf("processing job %d\n", id)
time.Sleep(100 * time.Millisecond)
}(i)
}
wg.Wait()
fmt.Println("all jobs done")
}processing job 1
processing job 2
processing job 3
...
all jobs doneRun go run semaphore.go. You will see jobs execute in waves of 3 rather than all 8 at once.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
Acquiring sem inside go func | Thousands of goroutines still get allocated | Acquire sem <- struct{}{} before go func |
Forgetting defer func() { <-sem }() on early return | Deadlock after maxWorkers errors | Always release the semaphore with defer |
| Passing loop variable by reference (pre-Go 1.22) | Duplicate job IDs | Pass id as a parameter to go func(id int) |
5. What you learned
You now know why unbounded goroutine spawning exhausts system resources and how a buffered channel semaphore caps concurrency cleanly in a few lines of Go.
Video walkthrough
YouTubeClick play to load video (YouTube)