Go & Systems Performance··2 min read

Eliminating Go Garbage Collection Spikes in High-Throughput JSON APIs with sync.Pool and Zero-Copy Streaming

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Eliminating Go Garbage Collection Spikes in High-Throughput JSON APIs with sync.Pool and Zero-Copy Streaming

Why High-Allocation Go Services Suffer P99 Latency Jitter

Go's concurrent garbage collector keeps pause times low, but it is not free. When an API endpoint allocates megabytes of short-lived heap objects per second (via json.Marshal, fmt.Sprintf, or growing slices without capacity hints), the Go runtime spends up to 30% of CPU cycles running background GC mark workers and write barriers.

Using go tool pprof (alloc_space and inuse_space) alongside compiler escape analysis (go build -gcflags="-m"), we eliminated 68% of heap allocations on our hot JSON serialization path.


1. Bounded Buffer Recycling with sync.Pool

When encoding JSON responses directly into json.Marshal(payload), Go allocates a fresh []byte slice on every request. Instead, we stream JSON directly into a reusable *bytes.Buffer leased from a sync.Pool:

package bufferpool

import (
	"bytes"
	"sync"
)

const maxPooledBufferCap = 64 * 1024 // 64 KB guard against pinning huge buffers

var jsonBufferPool = sync.Pool{
	New: func() any {
		return bytes.NewBuffer(make([]byte, 0, 4096))
	},
}

func AcquireBuffer() *bytes.Buffer {
	buf := jsonBufferPool.Get().(*bytes.Buffer)
	buf.Reset()
	return buf
}

func ReleaseBuffer(buf *bytes.Buffer) {
	if buf.Cap() <= maxPooledBufferCap {
		jsonBufferPool.Put(buf)
	}
}

The Critical 64 KB Capacity Guard

Notice the if buf.Cap() <= maxPooledBufferCap check before returning a buffer to the pool. Without that guard, a single outlier request that serializes a 10 MB export grows the buffer's underlying array to 10 MB and permanently pins that memory inside the pool.


2. Pre-Allocating Slice Capacities on Database Scans

Replacing un-sized var items []OrderItem declarations with items := make([]OrderItem, 0, expectedCount) eliminated repeated slice growth copies (runtime.growslice), dropping P99 latency from 48ms to 9.4ms at 12,000 RPS.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles