Thousands of goroutines: waiting on the network vs computing

Read the explanation
What if

5,000 goroutines each wait on a TCP connection. They park in the netpoller: a handful of OS threads, both Ps idle.

Predict first

5,000 goroutines each wait on their own TCP connection, with GOMAXPROCS 2. Roughly how many OS threads does the program have?

012345678910main: dial 5,000 connectionsreaders: Read(), parkP0: readers: Read(), parkpark5,000 readers parkedmain: print the counts

Tap any block to see what that thread is doing.

  • Running
  • Waiting / parked
Step 1/4

main dials 5,000 TCP connections and starts a reader goroutine for each. GOMAXPROCS is 2: two Ps.

1func main() {2    runtime.GOMAXPROCS(2) // two Ps: at most two goroutines run Go code at once3    addr := server()      // accepts connections, never sends anything4    for range 5000 {5        conn, err := net.Dial("tcp", addr)6        if err != nil {7            panic(err)8        }9        go func() {10            buf := make([]byte, 1)11            conn.Read(buf) // no data yet: the goroutine parks, no thread waits12        }()13    }14    settle() // wait until the thread count stops changing15    fmt.Println("goroutines:", runtime.NumGoroutine())16    fmt.Println("OS threads:", osThreads())17}

Explanation

What just happened

5,000 goroutines each called Read on a socket with no data. Each parked, and Go’s netpoller watched all 5,000 sockets for them.

Try the what-if switch

Why

A P is the right to run Go code, and GOMAXPROCS is how many there are. A parked goroutine needs neither a P nor a thread. A goroutine in a blocking syscall gives up its P but keeps its thread.

When it matters

Realtime servers with many connections: waiting is cheap, so one goroutine per connection is fine. Keep CPU-heavy work in a pool smaller than GOMAXPROCS.

Watch out

Go stops a program that needs more than 10,000 OS threads, which blocked syscalls can reach.

Common questions

How many OS threads do thousands of goroutines need?

It depends on what they wait for. 5,000 goroutines waiting on TCP reads ran on fewer than 20 OS threads; 1,000 blocked in raw read syscalls needed over 1,000.

What does GOMAXPROCS limit?

How many goroutines run Go code at once. With 1,000 busy goroutines, the scheduler ran exactly 2 at a time with GOMAXPROCS 2, and 4 with GOMAXPROCS 4. It does not limit goroutines blocked in syscalls: each still holds its own thread.

Does GOMAXPROCS above my CPU count make Go faster?

No. With twice as many Ps as cores, busy goroutines still used no more than every core.

Why does my Go server answer slowly under CPU load?

A goroutine woken by the network still waits for a free P. With 1,000 CPU-heavy goroutines on 2 Ps, a request was handled only after over 90% of them finished.

Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us