Reuse Buffers with sync.Pool

Cut per-request allocations by borrowing bytes.Buffer from sync.Pool, copying the encoded JSON, and always returning the buffer.

GoResilience

Code

gosnippet
39 lines
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"sync"
)

var bufferPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}

func EncodeJSON(value any) ([]byte, error) {
	buffer := bufferPool.Get().(*bytes.Buffer)
	buffer.Reset()
	defer bufferPool.Put(buffer)

	if err := json.NewEncoder(buffer).Encode(value); err != nil {
		return nil, err
	}
	out := make([]byte, buffer.Len())
	copy(out, buffer.Bytes())
	return out, nil
}

func main() {
	type payload struct {
		ID   int    `json:"id"`
		Name string `json:"name"`
	}
	encoded, err := EncodeJSON(payload{ID: 1, Name: "Ada"})
	if err != nil {
		panic(err)
	}
	fmt.Print(string(encoded))
	fmt.Println(bytes.Equal(encoded, []byte("{\"id\":1,\"name\":\"Ada\"}\n")))
}

What the code does

Reuse Buffers with sync.Pool is built around the functions EncodeJSON and main.

Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

What to watch for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Applying it

Entry signature: func EncodeJSON(value any) ([]byte, error)

Launch the file; main takes over and steps through EncodeJSON.

Statements that matter

func EncodeJSON(value any) ([]byte, error) {
	buffer := bufferPool.Get().(*bytes.Buffer)
	buffer.Reset()
	defer bufferPool.Put(buffer)
	if err := json.NewEncoder(buffer).Encode(value); err != nil {
		return nil, err
	}
	out := make([]byte, buffer.Len())
	copy(out, buffer.Bytes())
	return out, nil
}
var bufferPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}
if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
Through `error` values — the snippet checks `err != nil` at 2 sites, and the entry flow turns failures into `panic(err)`.
How do you run Reuse Buffers with sync.Pool?
This is a complete program, not a library excerpt — execution starts at the top.