Golang / Golang Internals and Memory Management Interview Questions
How do goroutine stacks work and how do they grow in Go?
Every goroutine starts with a small stack — only 2 KB by default (as of Go 1.4). This is orders of magnitude smaller than an OS thread's typical 1–8 MB stack, which is why Go can run millions of goroutines concurrently.
Go uses a copy-on-grow (contiguous stack) strategy. When the runtime detects that the current frame needs more space than available (a stack-overflow check inserted at function entry points), it:
- Allocates a new, larger stack (typically double the current size).
- Copies the entire old stack to the new location.
- Updates all pointers that referred into the old stack (pointer fixup).
- Frees the old stack.
// Goroutines start with 2 KB stack â very cheap to spawn for i := 0; i < 1_000_000; i++ { go func(id int) { // Each goroutine starts with a 2 KB stack doWork(id) }(i) } // Deeply recursive function â stack grows automatically func fib(n int) int { if n <= 1 { return n } return fib(n-1) + fib(n-2) // stack grows as needed, up to GOMAXSTACKS } // Maximum goroutine stack size (configurable via GOTRACEBACK env) // Default maximum is 1 GB // Stack size at goroutine creation is visible in stack traces: // goroutine 1 [running]: // main.main() // /path/main.go:10 +0x... [stack: 2048] // runtime.Stack() for diagnostics buf := make([]byte, 1<<20) n := runtime.Stack(buf, true) // all goroutines fmt.Printf("%s", buf[:n])
The older segmented stack approach (Go 1.3 and earlier) allocated stack segments as a linked list. It was abandoned because of the hot-split problem: a function call at the exact segment boundary caused repeated segment allocation and deallocation in a tight loop, causing up to a 10× performance regression. The current contiguous copy model has no such problem, though it does spend time on the copy when growth is needed.
More Related questions...