Go sync.Pool and Object Reuse: Reducing GC Pressure in High-Throughput Services
Originally published on Code Beneath.
If you are running a high-throughput Go service that creates thousands of objects per second, the garbage collector will eventually become your bottleneck. Every allocation triggers heap bookkeeping; every collection pause steals latency from your requests.
The sync.Pool example high throughput garbage collection pattern solves this by letting you reuse allocated objects instead of throwing them away. This article walks through real code that measures the difference, shows you where sync.Pool helps most, and explains the gotchas that trip up most engineers the first time.
The Problem: Allocation Churn in Request Handlers
When a handler processes a request, it often needs temporary buffers, slices, or structs to do its work. Without reuse, that object is garbage after the response is sent.
In a service handling 10,000 requests per second, that is 10,000 short-lived allocations per second. The Go garbage collector has to track, mark, and sweep all of them. Even with a modern concurrent GC, the overhead is real: more time spent in GC means higher latency percentiles and wasted CPU cycles.
sync.Pool is a thread-safe object pool. You put objects into it after use, then grab them back when you need them. If the pool is empty, you allocate fresh. If the pool has an object waiting, you save an allocation and a future collection.
The key insight is that the pool is temporary. The GC can clear it out at any time, so you never rely on it for correctness, only performance.
Measuring the Impact: Before and After
Let us start with a realistic example: an HTTP handler that reads JSON, parses it, and returns a response. We will measure GC stats and latency both without a pool and with one.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"sync"
"time"
)
// Request payload
type Payload struct {
ID int64 `json:"id"`
Name string `json:"name"`
Data string `json:"data"`
}
// Global buffer pool for reuse
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// Handler WITHOUT pool (baseline)
func handlerNoPool(w http.ResponseWriter, r *http.Request) {
var payload Payload
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
json.Unmarshal(buf.Bytes(), &payload)
response := map[string]interface{}{
"id": payload.ID,
"name": payload.Name,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
// Handler WITH pool (optimized)
func handlerWithPool(w http.ResponseWriter, r *http.Request) {
var payload Payload
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
buf.ReadFrom(r.Body)
json.Unmarshal(buf.Bytes(), &payload)
response := map[string]interface{}{
"id": payload.ID,
"name": payload.Name,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func benchmark(handler http.HandlerFunc, name string, iterations int) {
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
start := time.Now()
for i := 0; i < iterations; i++ {
body := bytes.NewReader([]byte(`{"id":42,"name":"test","data":"payload"}`))
req := httptest.NewRequest("POST", "/", body)
w := httptest.NewRecorder()
handler(w, req)
}
elapsed := time.Since(start)
runtime.ReadMemStats(&after)
allocsDiff := after.Alloc - before.Alloc
gcRuns := after.NumGC - before.NumGC
fmt.Printf("%s:\n", name)
fmt.Printf("Iterations: %d\n", iterations)
fmt.Printf("Total time: %v\n", elapsed)
fmt.Printf("Avg per iteration: %.2f us\n", float64(elapsed.Microseconds())/float64(iterations))
fmt.Printf("Heap alloc delta: %d KB\n", allocsDiff/1024)
fmt.Printf("GC runs: %d\n", gcRuns)
fmt.Printf("Allocs per second: %.0f\n", float64(iterations)/elapsed.Seconds())
fmt.Println()
}
func main() {
iterations := 50000
fmt.Println("=== Benchmarking sync.Pool impact ===")
fmt.Println()
benchmark(handlerNoPool, "Handler WITHOUT sync.Pool", iterations)
// Force GC to clear pools
runtime.GC()
time.Sleep(100 * time.Millisecond)
benchmark(handlerWithPool, "Handler WITH sync.Pool", iterations)
}
Run this code twice with different loop counts. On a modern laptop, the pooled handler will be 15-30% faster on average latency and show significantly fewer GC runs.
The difference scales with request rate and object size. In production services processing millions of requests daily, this translates to lower tail latencies and reduced CPU usage.
Building a Practical Buffer Pool
The example above showed the pattern, but real services often need multiple pool types. Here is a production-ready implementation with separate pools for buffers of different sizes, common in services that handle payloads ranging from kilobytes to megabytes.
package main
import (
"bytes"
"fmt"
"sync"
)
// BufferPool holds multiple pools for different buffer sizes
type BufferPool struct {
small *sync.Pool // ~4KB
medium *sync.Pool // ~64KB
large *sync.Pool // ~1MB
}
func NewBufferPool() *BufferPool {
return &BufferPool{
small: &sync.Pool{
New: func() interface{} {
b := new(bytes.Buffer)
b.Grow(4096)
return b
},
},
medium: &sync.Pool{
New: func() interface{} {
b := new(bytes.Buffer)
b.Grow(65536)
return b
},
},
large: &sync.Pool{
New: func() interface{} {
b := new(bytes.Buffer)
b.Grow(1024 * 1024)
return b
},
},
}
}
// Get returns a buffer sized for the given capacity hint
func (p *BufferPool) Get(sizeHint int) *bytes.Buffer {
var b *bytes.Buffer
if sizeHint <= 4096 {
if v := p.small.Get(); v != nil {
b = v.(*bytes.Buffer)
}
} else if sizeHint <= 65536 {
if v := p.medium.Get(); v != nil {
b = v.(*bytes.Buffer)
}
} else {
if v := p.large.Get(); v != nil {
b = v.(*bytes.Buffer)
}
}
if b == nil {
b = new(bytes.Buffer)
b.Grow(sizeHint)
}
b.Reset()
return b
}
// Put returns a buffer to the pool if it is not too large
func (p *BufferPool) Put(b *bytes.Buffer) {
capacity := b.Cap()
if capacity <= 4096 {
p.small.Put(b)
} else if capacity <= 65536 {
p.medium.Put(b)
} else if capacity <= 1024*1024 {
p.large.Put(b)
}
// else: discard buffers larger than 1MB to avoid memory bloat
}
func main() {
pool := NewBufferPool()
// Simulate workload
for i := 0; i < 1000; i++ {
buf := pool.Get(10000)
fmt.Fprintf(buf, "Request %d data\n", i)
pool.Put(buf)
}
fmt.Println("Buffer pool test completed")
}
This design avoids a subtle issue: if you pool very large buffers alongside tiny ones, the small ones get lost because they are too small to be useful after a large allocation uses the slot. By keeping separate pools by size class, you maximize reuse without waste.
The Dangerous Mistake: Storing External References
The most common bug when using sync.Pool is returning an object to the pool while something outside the pool still holds a pointer to it. This violates the fundamental rule: once you put an object in the pool, you must not touch it again. If you do, you have a data race or stale data problem.
package main
import (
"bytes"
"sync"
)
type Message struct {
Data *bytes.Buffer
}
var msgPool = sync.Pool{
New: func() interface{} {
return &Message{Data: new(bytes.Buffer)}
},
}
// WRONG: Bug waiting to happen
func buggyUse() {
msg := msgPool.Get().(*Message)
msg.Data.WriteString("Hello")
// Oops: storing a reference outside the handler
savedRef := msg.Data
msgPool.Put(msg)
// Another goroutine gets this message from pool
msg2 := msgPool.Get().(*Message)
msg2.Data.WriteString(" World")
// Now both savedRef and msg2.Data point to the same buffer
// Reading or writing from savedRef is a race
}
// CORRECT: No external references
func correctUse() {
msg := msgPool.Get().(*Message)
msg.Data.WriteString("Hello")
// Use only within this scope
result := msg.Data.String()
msg.Data.Reset()
msgPool.Put(msg)
_ = result // process result
}
func main() {
correctUse()
}
The fix is simple: never let an object escape the scope where you pool it. Use it, extract any data you need, then return it. If you need to pass data to another goroutine, copy the data or marshal it, do not pass the pooled object itself.
When NOT to Use sync.Pool
sync.Pool is not a cache. It is a GC pressure relief valve. Here are cases where it makes things worse or does not help:
- If your objects are small (under 128 bytes) and not created frequently (less than 1,000 per second per core), the GC can handle them fine. Pooling adds complexity for no benefit.
- If you need to store objects long-term or access them after the handler returns, use a real cache or a database, not a pool.
- If your object has external resources like database connections or file handles, the pool cannot help you manage their lifecycle safely.
- If your workload is bursty with long idle periods, the pool will keep memory around that the GC could have freed.
Pooling Structs, Not Just Buffers
Pools work for any object type. Here is an example pooling custom structs, which is common in request parsing pipelines.
package main
import (
"fmt"
"sync"
)
// RequestContext holds parsed request data
type RequestContext struct {
UserID int64
Method string
Path string
Headers map[string]string
QueryMap map[string]string
}
func NewRequestContext() *RequestContext {
return &RequestContext{
Headers: make(map[string]string, 16),
QueryMap: make(map[string]string, 8),
}
}
func (r *RequestContext) Reset() {
r.UserID = 0
r.Method = ""
r.Path = ""
for k := range r.Headers {
delete(r.Headers, k)
}
for k := range r.QueryMap {
delete(r.QueryMap, k)
}
}
var ctxPool = sync.Pool{
New: func() interface{} {
return NewRequestContext()
},
}
func GetContext() *RequestContext {
return ctxPool.Get().(*RequestContext)
}
func PutContext(ctx *RequestContext) {
ctx.Reset()
ctxPool.Put(ctx)
}
func handleRequest(userID int64, method string, path string) {
ctx := GetContext()
defer PutContext(ctx)
ctx.UserID = userID
ctx.Method = method
ctx.Path = path
ctx.Headers["Content-Type"] = "application/json"
fmt.Printf("Processed: User=%d, Method=%s, Path=%s\n", ctx.UserID, ctx.Method, ctx.Path)
}
func main() {
for i := 0; i < 10; i++ {
handleRequest(int64(i), "GET", "/api/v1/users")
}
}
Notice the Reset() method: it clears all state so the struct can be safely reused. This is essential. If you forget to reset and return a struct with stale data in it, the next request will see that garbage. Reset should be idempotent and cheap.
Comparing Pooling Strategies
| Strategy | Throughput | GC Pauses | Code Complexity | Best For |
|---|---|---|---|---|
| No pooling (naive) | Baseline | High | Low | Low-throughput services |
| sync.Pool (single type) | +15-30% | -50-70% | Medium | Buffer pooling in handlers |
| sync.Pool (tiered by size) | +20-35% | -60-80% | Medium-High | Variable-size allocations |
| Pre-allocation (ring buffer) | +30-40% | -80-95% | High | Known fixed size, low latency |
Common Mistakes
- Pooling a pointer to an object outside the pool while the same pointer is in the pool leads to races.
- Allocating huge objects in the New function defeats the purpose; New should be cheap.
- Forgetting to call
Reset()leaves stale data in pooled objects, causing bugs in the next reuse. - Storing very large objects (over 10 MB) in a pool can lead to memory bloat because the pool survives GC collection and holds references.
- Pooling objects with channels, mutexes, or other synchronization primitives that cannot be safely reused across requests.
Measuring with GODEBUG
To see GC activity without writing custom code, use GODEBUG:
GODEBUG=gctrace=1 ./your-binary 2>&1 | grep gc
This prints a line for each GC run showing heap size, pause time, and wall clock. Run your benchmarks with and without sync.Pool to compare GC frequency and pause times. The gctrace output is a quick sanity check that your pooling strategy is actually reducing collector load.
Integration with Goroutine Pools
Combining sync.Pool with goroutines vs OS threads patterns gives you a complete low-latency architecture. A worker pool of goroutines can each grab buffers or objects from a shared pool, process work, and return them. This avoids both goroutine creation churn and buffer allocation churn.
package main
import (
"bytes"
"fmt"
"sync"
)
type WorkItem struct {
ID int
}
type Worker struct {
id int
work <-chan WorkItem
bufPool *sync.Pool
}
func (w *Worker) Run() {
for item := range w.work {
buf := w.bufPool.Get().(*bytes.Buffer)
defer w.bufPool.Put(buf)
fmt.Fprintf(buf, "Worker %d processed item %d\n", w.id, item.ID)
_ = buf.String() // use result
}
}
func main() {
bufPool := &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
work := make(chan WorkItem, 100)
// Spawn 4 workers
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
w := &Worker{id: i, work: work, bufPool: bufPool}
go func() {
defer wg.Done()
w.Run()
}()
}
// Send work
for i := 0; i < 20; i++ {
work <- WorkItem{ID: i}
}
close(work)
wg.Wait()
fmt.Println("Done")
}
FAQ
How does sync.Pool handle concurrency? Is it safe across goroutines?
Yes, sync.Pool is fully thread-safe. Internally, it uses a lock-free structure per P (logical processor) to minimize contention. When a goroutine calls Get or Put, it accesses its own P's slot first. If that is empty, it steals from other P slots. This design keeps contention low even under high concurrency. You do not need any locks around Po
Comments
No comments yet. Start the discussion.