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
More Related questions...