Sobes.tech
Senior

How many goroutines can be created on one machine? How to count?

sobes.tech AI

Answer from AI

The number of goroutines that can be created on a single machine does not have a strict upper limit and depends on several factors: available RAM, the size of each goroutine's stack (default around 2 KB, but can grow), as well as CPU load and the Go scheduler.

To estimate the maximum number of goroutines, you can use the formula:

Maximum number of goroutines ≈ (Available stack memory) / (Average size of a goroutine's stack)

For example, if you have 1 GB of free memory and each goroutine's stack takes 2 KB, theoretically, you can create about 500,000 goroutines. However, in practice, this number will be lower due to other resources and overhead.

It is also important to consider that too many goroutines can lead to performance degradation due to context switching and scheduling.

For monitoring and estimation, profiling and runtime tools can be used, for example, runtime.NumGoroutine() to count the current goroutines.