Reuse Buffers Without Corrupting Data Using sync.Pool
Cut per-request allocations with sync.Pool without leaking stale bytes across requests or holding onto oversized buffers forever. After this, you know when Reset and max-capacity caps keep pooled buffers safe and fast.
Skip ahead
Already pooling *bytes.Buffer? Jump to Case 2: why forgetting Reset() leaks another user's bytes or Case 3: why the 64 KB capacity cap prevents RSS bloat.
In a busy API or audit-event pipeline writing thousands of JSON lines per second, allocating a fresh 4 KB bytes.Buffer on every request floods the heap with short-lived objects—forcing the garbage collector to burn measurable CPU time sweeping buffers that only lived for a few microseconds.
sync.Pool lets goroutines reuse temporary buffers across requests—cutting per-request allocations by ~100×—as long as you enforce two non-negotiable safety rules: always call Reset() before use, and never return oversized outlier buffers to the pool. Verified on Go 1.27.
Case 1: Real audit-event formatter benchmarked fresh vs. pooled
Look at formatAuditEvent below, paired with an isolation test proving user alice's bytes never leak into bob's event, and a benchmark comparing fresh 4 KB buffers against pooled buffers:
package eventlog
import (
"bytes"
"fmt"
"io"
"sync"
"testing"
)
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func formatAuditEvent(w io.Writer, userID, action string, padding []byte) error {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
fmt.Fprintf(b, `{"user":%q,"action":%q,"pad":%d}`+"\n", userID, action, len(padding))
_, err := w.Write(b.Bytes())
if b.Cap() <= 64*1024 {
bufPool.Put(b)
}
return err
}
func TestPoolIsolatesUsers(t *testing.T) {
var out1, out2 bytes.Buffer
_ = formatAuditEvent(&out1, "alice", "login", nil)
_ = formatAuditEvent(&out2, "bob", "logout", nil)
if bytes.Contains(out2.Bytes(), []byte("alice")) {
t.Fatalf("leaked alice into bob: %s", out2.String())
}
}
$ go test -v -bench=. -benchmem -benchtime=200ms .
=== RUN TestPoolIsolatesUsers
--- PASS: TestPoolIsolatesUsers (0.00s)
BenchmarkFormatFresh-2 450516 615.4 ns/op 4152 B/op 3 allocs/op
BenchmarkFormatPooled-2 2111535 114.9 ns/op 40 B/op 3 allocs/op
Heap churn dropped from 4,152 B/op to 40 B/op (~100× less memory allocated per event) and throughput jumped 5.4×.
Case 2: Why calling b.Reset() right after Get() is mandatory
Without b.Reset(), the second request appends {"user":"bob"...} straight after {"user":"alice"...} inside the reused buffer—silently corrupting responses and leaking one user's data into another user's output! Calling Reset() right after Get() sets length to 0 while preserving the underlying backing array, and defends against any earlier caller that panicked before resetting.
Case 3: Why the b.Cap() <= 64*1024 cap stops RSS memory bloat
Suppose 99.9% of requests format a 4 KB JSON body, and one rare admin export formats a 32 MB report. That single buffer grows its backing array to 32 MB. If you unconditionally call bufPool.Put(b), that giant 32 MB array sits pinned inside the pool across idle periods instead of being freed. Checking if b.Cap() <= 64*1024 drops rare outliers so the GC reclaims them right away.
Case 4: When sync.Pool helps vs. hurts
| Object / Workload | Use sync.Pool? |
Why |
|---|---|---|
Reusable 1 KB–64 KB *bytes.Buffer or JSON/gzip encoders |
Yes | Eliminates repeated multi-KB heap allocations on hot paths |
| Tiny 16-byte strings | No | Get()/Put() overhead can exceed a small stack allocation |
| Database connections, files, or caches | No | GC silently drops sync.Pool items without calling Close() |
💡 Tip
Always store a pointer (*bytes.Buffer or *[]byte) in sync.Pool, never a bare slice value []byte—passing a slice value to Put(any) allocates a 24-byte interface header box on every single Put.
Common mistakes
- Returning
b.Bytes()after callingbufPool.Put(b):b.Bytes()aliases the buffer's internal array—the next goroutine callingGet()overwrites those exact bytes underneath your caller! Always finish writing toio.Writeror copy to astringbefore callingPut. - Using
sync.Poolas an in-memory cache: The runtime clears pools across GC cycles; never store data you expect to survive. - Putting a buffer back after an unhandled corruption or unbounded growth: Always guard
Putwith a capacity cap.
⚠ Warning
Returning a slice alias of a pooled buffer after Put(b) is a subtle data-corruption bug that only appears under concurrent production traffic. Copy out or finish writing before Put.
What happens if you skip this
Without Reset() and a max-capacity cap, pooled buffers either leak sensitive previous-request bytes into subsequent responses or pin rare multi-megabyte allocations in RAM long after a spike ends.
Related course: Go Advanced.
About
Cut per-request allocations with sync.Pool without leaking stale bytes across requests or holding onto oversized buffers forever. After this, you know when Reset and max-capacity caps keep pooled buffers safe and fast.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.