Lesson 27 · Senior Go backend engineering

sync.Pool & memory layout

When reuse helps, and why the shape of a struct can affect real backend costs.

Your win: explain when sync.Pool is appropriate, when it is not, and why struct field order can matter once you have enough data in memory that every wasted byte gets multiplied.

In plain English sync.Pool is for temporary reuse, not ownership. Struct alignment is about how the compiler lays fields out in memory, which can quietly change how large each value becomes.

Two separate ideas that meet in performance work

These topics feel different, but they meet in the same place: the moment you are no longer asking “does this code work?” and start asking “what does this code cost when it runs a million times?”

sync.Pool: what it is for

It is not a general cache, a lifetime manager, or a place to hide correctness rules.

Repo example This repository already contains sync.Pool usage in generator code. That is a helpful anchor: the pool exists to reuse an expensive helper object, not to become shared application state that other code must reason about semantically.

Struct alignment

type Bad struct {
    flag bool
    n    int64
    b    bool
}

type Better struct {
    n    int64
    flag bool
    b    bool
}

Reordering fields can shrink the struct because the compiler inserts padding to satisfy alignment rules. When one value is tiny, you rarely care. When millions of values are resident, you suddenly do.

Senior framing Alignment is usually a scale optimization, not a first-day optimization. sync.Pool is usually a hot-path optimization, not a default design pattern. Both are “after measurement” topics.
Common mistake Adding sync.Pool because “allocations are bad.” Pools add complexity and can make ownership less obvious. Measure first, then optimize the hot path you can prove matters.
Read this next

Diagnostics + performance tooling

Use the standard toolchain to find out whether allocation churn or memory density is actually your bottleneck before changing code shape.

go.dev/doc/diagnostics
go.dev/blog/profiling-go-programs

Check yourself (from memory)

Q1. sync.Pool is best for…

It is a performance tool, not an application-state design.

Q2. Why can field order matter in a struct?

Field order can change how much padding the compiler must add.
When would a senior engineer reach for sync.Pool?
recall, then click to reveal
After measurement shows allocation churn on a hot path, and only for temporary reusable objects where the extra complexity is worth the reduction in runtime work.
Want a tiny unsafe.Sizeof demo that shows exactly how field reordering changes struct size? Ask me.

Sources. Go Diagnostics; Profiling Go Programs.