How Many Goroutines Can You Run in Go: Limits and Best Practices
You can run millions of
goroutines in Go, limited mainly by your system's memory and scheduler capacity. Go's runtime efficiently manages goroutines with a small stack size, allowing very high concurrency compared to traditional threads.Syntax
To start a new goroutine, use the go keyword followed by a function call. This runs the function concurrently without blocking the current code.
go: keyword to start a goroutinefunction(): the function you want to run concurrently
go
go functionName()
Example
This example launches 5 goroutines that print their number concurrently. It shows how goroutines run independently and the main function waits for them to finish using a channel.
go
package main import ( "fmt" "time" ) func worker(id int, done chan bool) { fmt.Printf("Worker %d starting\n", id) time.Sleep(time.Second) fmt.Printf("Worker %d done\n", id) done <- true } func main() { done := make(chan bool) for i := 1; i <= 5; i++ { go worker(i, done) } for i := 1; i <= 5; i++ { <-done } fmt.Println("All workers finished") }
Output
Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done
All workers finished
Common Pitfalls
One common mistake is starting goroutines without synchronization, causing the main program to exit before goroutines finish. Another is creating too many goroutines without limits, which can exhaust memory.
Always use synchronization tools like channels or sync.WaitGroup to wait for goroutines to complete.
go
package main import ( "fmt" "time" ) func main() { for i := 1; i <= 3; i++ { go func(n int) { fmt.Println("Goroutine", n) }(i) } // Missing wait here causes main to exit early // time.Sleep(time.Second) // Fix: add sleep or sync }
Quick Reference
Key points about goroutine limits and management:
| Topic | Details |
|---|---|
| Goroutine Limit | Millions possible, limited by memory and OS |
| Stack Size | Starts small (~2KB), grows as needed |
| Scheduler | Go runtime multiplexes goroutines on OS threads |
| Common Limitations | Memory exhaustion, CPU limits |
| Best Practice | Use synchronization to avoid premature exit |
Key Takeaways
Go can run millions of goroutines efficiently due to small initial stack size.
The actual limit depends on your system's memory and CPU resources.
Always synchronize goroutines to ensure they complete before program exit.
Avoid creating unlimited goroutines without control to prevent resource exhaustion.
Use channels or sync.WaitGroup to manage goroutine lifecycle safely.