Golang / GoLang Concurrency Mastery Interview Questions
How does sync.Pool reduce GC pressure in high-throughput Go services?
sync.Pool is a concurrent pool of reusable temporary objects. By returning objects to the pool after use instead of discarding them, allocation and GC pressure are significantly reduced — critical for high-throughput services like HTTP servers and JSON encoders.
// Pool of byte buffers reused per request
var bufPool = sync.Pool{
New: func() any {
buf := make([]byte, 0, 4096)
return &buf
},
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
bufPtr := bufPool.Get().(*[]byte) // may be new or recycled
buf := (*bufPtr)[:0] // reset length, keep capacity
// Use buf as scratch space...
buf = append(buf, buildResponse(r)...)
w.Write(buf)
// Return to pool — ALWAYS reset state first!
*bufPtr = buf
bufPool.Put(bufPtr)
}
// KEY RULES:
// 1. GC MAY drain the pool at any time — pool items are NOT permanent
// 2. Get() returns a new object (via New) or a recycled one — both OK
// 3. ALWAYS reset state before Put() — recycled objects carry old data
// 4. Never use a pooled object after Put() — it belongs to the pool
// 5. All objects in the pool must be the same type
// Real usage:
// - encoding/json uses sync.Pool for encoder/decoder state
// - net/http uses it for request/response buffers
// - fmt uses it for print state (pp struct)
// Benchmarks show 40%+ reduction in allocations under sustained load
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...
