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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
