Running Go natively in the cloud: multi-stage Dockerfiles with distroless images, 12-factor configuration with clean liveness and readiness endpoints, Kubernetes automation with client-go, operators built on controller-runtime and kubebuilder, and sidecars, webhooks & CRDs as extension patterns.
The "Kant & Curves" bookshop's Black Friday stress test is merciless: under 500 concurrent requests, the book search's p95 latency climbs from 40 to over 900 milliseconds. Where to start? Not in the code — in the data. Go ships pprof, a full-grown profiler built right into the runtime: no external tool, no agent, no APM vendor. Two packages are enough: runtime/pprof for batch programs and net/http/pprof for long-running servers.
In practice the profiling endpoint runs on its own port, reachable only from the internal network — for a gRPC service (google.golang.org/grpc) you simply start a second net/http listener next to it and serve both from the same binary.
// cmd/server/main.go — enabling pprof: one blank import is enough
package main
import (
"log"
"net/http"
_ "net/http/pprof" // registers /debug/pprof/* on the DefaultServeMux
)
func main() {
// Profiling server on a separate port — never expose it publicly!
go func() {
log.Fatal(http.ListenAndServe("localhost:6060", nil))
}()
// The actual service runs untouched on :8080
mux := http.NewServeMux()
mux.HandleFunc("GET /search", handleSearch)
log.Fatal(http.ListenAndServe(":8080", mux))
}
// Terminal: list all available profiles
// $ curl -s http://localhost:6060/debug/pprof/
// → /debug/pprof/
// → profiles:
// → 0 block
// → 37 goroutine
// → 7 heap
// → 0 mutex
// → 5 threadcreate
// → full profile:
Every profile answers a different question
The CPU profile (/debug/pprof/profile) samples stack traces ~100 times per second from goroutines that are currently using the CPU — it shows where compute time is burned. The heap profile (heap) shows allocations (by default one sample per ~512 KB of allocated volume — small objects are underrepresented). The goroutine profile counts all live goroutines and is the leak detector. The block and mutex profiles show waiting times on channels, locks, and sync.WaitGroup — they must be enabled first via runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction.
You typically capture the CPU profile under real load — 30 seconds under the stress test say more than an hour of idle profiling:
// Terminal: capture 30 seconds of CPU profile under load and analyze it
// $ go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
// → Fetching profile over HTTP from http://localhost:6060/debug/pprof/profile?seconds=30
// → Saved profile in /home/tobias/pprof/pprof.books.exe.samples.cpu.001.pb.gz
// → Type: cpu
// → Entering interactive mode (type "help" for commands, "o" for options)
// (pprof) top
// → Showing nodes accounting for 2.14s, 89.5% of 2.39s total
// → Dropped 87 nodes (cum <= 0.012s)
// → flat flat% sum% cum cum%
// → 1.21s 50.63% 50.63% 1.21s 50.63% runtime.mallocgc
// → 0.32s 13.39% 64.02% 0.98s 40.92% bookstore.Index.Lookup
// → 0.28s 11.72% 75.73% 0.28s 11.72% runtime.mapaccess2_faststr
flat is the time spent directly inside the function, cum the time including all called functions. Here runtime.mallocgc dominates — the allocation machinery. That is the classic pointer toward lesson 99. The interactive -http=:8080 flag additionally opens a flame graph in the browser.
While the CPU profile shows where time is spent, the heap profile shows where memory originates — crucial for GC load and container limits:
// Terminal: Where does memory come from? And are goroutines leaking?
// $ go tool pprof -sample_index=alloc_space http://localhost:6060/debug/pprof/heap
// (pprof) top 3
// → Showing nodes accounting for 118MB, 90.77% of 130MB total
// → Dropped 17 nodes (cum <= 0.65MB)
// → flat flat% sum% cum cum%
// → 104.02MB 80.02% 80.02% 104.02MB 80.02% bookstore.(*Cart).Serialize
// → 14.15MB 10.88% 90.90% 14.15MB 10.88% encoding/json.Marshal
// $ curl -s "http://localhost:6060/debug/pprof/goroutine?debug=1" | head -4
// → goroutine profile: total 1042
// → 980 @ 0x104a2f 0x104b53 0x12c4d0 0x12c8f1 0x228d90
// → # 0x12c4d0 bookstore.ListenForCartEvents.func1+0x50 cart/events.go:47
980 goroutines with an identical stack in cart/events.go:47 — that is not a load spike, that is a leak: somewhere a goroutine is started whose channel is never closed (how to prevent such leaks with contexts was covered in module 7). For lock contention you switch on the two contention profiles:
// cmd/server/main.go — enabling the block and mutex profiles (minimal overhead)
package main
import "runtime"
func init() {
runtime.SetBlockProfileRate(1_000_000) // 1 sample per 1 ms of block time
runtime.SetMutexProfileFraction(100) // ~1% of all mutex events
}
// Terminal: who is holding others up? Query the contention profile
// $ go tool pprof http://localhost:6060/debug/pprof/mutex
// (pprof) top
// → Showing nodes accounting for 940ms, 93% of 1010ms total
// → flat flat% sum% cum cum%
// → 940ms 93.07% 93.07% 940ms 93.07% sync.(*Mutex).Unlock
// → 0 0% 93.07% 940ms 93.07% bookstore.(*Inventory).Reserve
⚠ Common mistake: Accidentally exposing the pprof endpoints to the public — writing
http.ListenAndServe(":6060", nil)instead oflocalhost:6060publishes stack traces, source paths, and in the heap dump even customer data. Always bind tolocalhostor an internal interface and shield it with network policy. The second classic: capturing the CPU profile while the system is idle and drawing load conclusions from it — 30 seconds of profiling under real request load are part of the deal.
Check: The database handler barely shows up in the CPU profile, even though it takes most of the time. Why?
Answer: The CPU profile only shows time in which goroutines actually use the CPU — waiting on I/O, locks, or channel operations does not appear there
The CPU profile samples ~100 times per second, but only goroutines that are currently on-CPU. A goroutine blocked on the database, a mutex, or a channel is waiting and simply never appears in the samples. For waiting times the goroutine, block, and mutex profiles are responsible — which is exactly why every performance analysis should always look at several profile types.
Takeaways:
pprof is built into the runtime: _ "net/http/pprof" for servers, runtime/pprof for batch jobs — no external tool needed.runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction.go tool pprof -http=... opens the flame graph.Every heap allocation costs three times: runtime.mallocgc to allocate, GC work to clean up, and cache pressure from pointer chasing. Stack allocations are practically free — the stack pointer moves, done. The compiler's escape analysis decides where a variable lives: if an address stays inside the function's stack frame, everything remains on the stack. If the compiler cannot prove that a variable never leaves the frame, it "escapes" to the heap.
In the hot path of the "Kant & Curves" book search, lesson 96 showed over 50% of CPU time inside runtime.mallocgc — before rewriting anything, we need to understand why variables move to the heap at all:
// cmd/escape/main.go — stack or heap? The compiler decides.
package main
import "fmt"
// StackVariant returns a copy — x stays in the stack frame
func StackVariant() int {
x := 42
return x
}
// HeapVariant returns the address of a local variable
func HeapVariant() *int {
y := 42 // escapes: the pointer outlives the stack frame
return &y
}
func constMake() int {
s := make([]int, 8) // constant, small size → stack
s[0] = 1
return s[0]
}
func bigConstMake() int {
b := make([]byte, 128*1024) // 128 KB — above the implicit boundary
return len(b)
}
func varMake(n int) int {
b := make([]byte, n) // size only known at runtime
return len(b)
}
func main() {
fmt.Println(StackVariant(), *HeapVariant(), constMake(), bigConstMake(), varMake(64))
// → 42 42 1 131072 64
}
The compiler lays its decision open — with -gcflags, directly and honestly (output on Go 1.24, slightly different on other versions):
// Terminal: making escape analysis visible (-l disables inlining for clean attribution)
// $ go build -gcflags="-m -l" ./cmd/escape/
// → ./cmd/escape/main.go:14:2: moved to heap: y
// → ./cmd/escape/main.go:19:11: make([]int, 8) does not escape
// → ./cmd/escape/main.go:25:11: make([]byte, 131072) escapes to heap
// → ./cmd/escape/main.go:30:11: make([]byte, n) escapes to heap
// → ./cmd/escape/main.go:35:13: ... argument does not escape
The three size rules of escape analysis
maxImplicitStackVarSize in the cmd/compile compiler. 2. Non-constant sizes like make([]byte, n) always escape — the compiler cannot prove an upper bound. 3. Explicit variables above 10 MB always go to the heap (maxStackVarSize). The values are compiler implementation details, but they have held unchanged for many Go versions.This explains the output above: make([]int, 8) stays on the stack (small, constant, does not escape), make([]byte, 131072) escapes (128 KB exceeds 64 KB), and make([]byte, n) escapes despite n=64 at runtime — the size is unknown to the compiler at translation time. The consequence for hot paths: pass a known maximum size as a constant instead of a parameter, and the compiler can stack-allocate again.
Beyond size, three patterns force variables onto the heap — pointers into escaping containers, boxing into interface{} (every fmt.Println argument!), and addresses that cross function boundaries:
// cmd/escape/traps.go — the three classic escape traps
package main
import "fmt"
type Order struct {
Items []*LineItem
}
type LineItem struct {
Title string
}
// Trap 1: a pointer into a container whose fate the function does not know
func addEscape(o *Order) {
p := &LineItem{Title: "Go book"} // escapes: lands in o
o.Items = append(o.Items, p)
}
// Trap 2: interface boxing — fmt.Println packs every argument into interface{}
func boxingDemo(s string) {
fmt.Println(s) // s escapes: the value must be converted to the interface format
}
// Trap 3: nil slice with append — capacity unknown, grows in steps
func growDemo(n int) []int {
var s []int
for i := 0; i < n; i++ {
s = append(s, i)
}
return s
}
func main() {
boxingDemo("Kant & Curves")
o := &Order{}
addEscape(o)
fmt.Println(len(growDemo(5)), len(o.Items))
// → 5 1
}
// Terminal: go build -gcflags="-m -l" ./cmd/escape/
// → ./cmd/escape/traps.go:16:7: &LineItem{...} escapes to heap
// → ./cmd/escape/traps.go:22:14: s escapes to heap
Important for context: escape analysis is not magic but flow analysis with the burden of proof on the compiler. And the heap is not bad per se — sometimes a *LineItem on the heap is exactly right (lesson 99 shows how to make the remaining allocations cheap). If you want to pin escape messages down in CI, they also show up in go vet reports.
⚠ Common mistake: Believing that
new(T)forces the heap — or conversely, that a value type automatically stays on the stack. What matters is never the spelling but whether the address escapes:p := new(LineItem)stays on the stack ifpnever leaves the frame, while&LineItem{}moves to the heap the moment the pointer lands in an escaping container. Anyone who returns pointers everywhere by default just to save typing pays GC taxes in every hot path.
Check: Why does make([]byte, n) land on the heap even when n is only 64 at runtime?
Answer: Because escape analysis cannot prove an upper bound for n at compile time — non-constant sizes always escape
Escape analysis runs at compile time and is proof-based: with make([]byte, n) where n is a variable, the compiler cannot rule out that the function gets called with n in the billions — so the allocation conservatively goes to the heap. Constant sizes up to 64 KB, on the other hand, can be classified exactly. This is also why helper functions taking a length parameter often cause unwanted heap load in hot paths: moving the size into the make() call as a constant changes the proof situation.
Takeaways:
go build -gcflags="-m -l" makes the decisions visible: does not escape vs. moved to heap / escapes to heap.make([]byte, n)) → always heap; variables above 10 MB → always heap.interface{} boxing (among others in fmt calls), returned addresses of local variables.new(T) does not force the heap and value types do not guarantee the stack — what counts is whether the address leaves the stack frame.After lesson 97 we allocate more consciously — but every real program still allocates, and then the garbage collector works. Go relies on a concurrent mark-and-sweep collector without generations: it marks live objects in parallel with the application and stops the world only for short, usually sub-millisecond phases. Two knobs determine how often it runs: GOGC (the memory-versus-CPU tradeoff) and GOMEMLIMIT (since Go 1.19, OOM protection in containers).
The scenario: the bookshop runs in Kubernetes with a 512 MiB memory limit and keeps getting OOMKilled on Black Friday. Before anyone touches a knob, we measure — with gctrace:
// Terminal: watch GC cycles live
// $ GODEBUG=gctrace=1 ./bookstore
// → gc 3 @3.204s 1%: 0.015+2.1+0.031 ms clock, 0.12+0.53/2.0/0+0.25 ms cpu,
// → 47->49->25 MB, 50 MB goal, 0 MB stacks, 0 MB globals, 8 P
The decisive numbers are 47->49->25 MB: heap size at the start of the cycle (47 MB), at the end of the mark phase (49 MB), and the live heap after cleanup (25 MB). 50 MB goal is the target of the next cycle — and this is exactly where GOGC kicks in.
GOGC and GOMEMLIMIT in one sentence
GOGC (default: 100) defines: the next GC cycle starts once the heap has grown to live heap × (1 + GOGC/100) — with a 25 MB live heap and GOGC=100, that is 50 MB. A higher GOGC means rarer GCs, less CPU, more peak memory. GOMEMLIMIT (Go 1.19+) sets a soft limit on the total runtime-managed memory (heap, stacks, globals) — near it the GC runs noticeably more often instead of blowing through the container limit.
Tuning without the live-heap number is stabbing in the dark: a live heap of 25 MB at GOGC=100 oscillates around 50 MB; a live heap of 300 MB oscillates around 600 MB — no GOGC in the world turns the second case into a 512 MiB budget. At runtime you measure it cleanly with runtime/metrics:
// internal/gcstats/heap.go — reading live heap and GC goal programmatically
package gcstats
import (
"fmt"
"runtime/metrics"
)
// LiveHeapBytes returns the current live heap and the next GC goal.
func LiveHeapBytes() (live, goal uint64) {
samples := []metrics.Sample{
{Name: "/memory/classes/heap/objects:bytes"}, // heap occupied by live objects
{Name: "/gc/heap/goal:bytes"}, // target size of the next cycle
}
metrics.Read(samples)
return samples[0].Value.Uint64(), samples[1].Value.Uint64()
}
func main() {
live, goal := LiveHeapBytes()
fmt.Printf("live=%.0f MB goal=%.0f MB\n", float64(live)/1e6, float64(goal)/1e6)
// → live=25 MB goal=50 MB
}
The metric names are stable API — go doc runtime/metrics lists all of them, including /gc/gogc:percent and /gc/gomemlimit:bytes for verifying the active knobs. For the crucial question of how big the live heap really gets: measure under production load, not in the dev loop. How memory and latency targets translate into an overall architecture is not a Go topic but a scaling topic — the foundations are in Module 7: Scalability of the architecture series.
Only once the memory budget is clear do we turn knobs. As environment variables (GOGC=200, GOMEMLIMIT=480MiB) or programmatically:
// cmd/server/main.go — setting GC knobs programmatically
package main
import "runtime/debug"
func init() {
// 512 MiB container: limit with ~6% headroom — the limit is soft,
// the GC would rather die of its own CPU work than of the OOM kill
debug.SetMemoryLimit(480 << 20)
// GOGC stays at the default of 100 — anyone trying to eliminate ALL
// cycles usually has a live-heap problem (lessons 97/99), not a GOGC problem
}
// Terminal: after tuning — the heap oscillates below the limit
// $ GODEBUG=gctrace=1 go run ./cmd/server
// → gc 9 @7.8s 2%: 0.019+2.4+0.051 ms clock, ..., 361->380->190 MB, 380 MB goal, 0 MB stacks, 0 MB globals, 8 P
Typical recipes: more throughput, RAM available → raise GOGC to 200–500 (doubles to quintuples the distance between cycles). tight container → GOMEMLIMIT just below the cgroup limit. short CLI tools → GOGC=off is legitimate here because the process ends before the GC matters. And with debug.FreeOSMemory() you actively return memory to the operating system after a large batch.
⚠ Common mistake: Setting GOMEMLIMIT exactly to the container limit (or blindly cranking GOGC to 500 because "less GC must be good"). The limit is soft: the GC speeds up its cycles near the limit, but if the live heap itself is too large it spins in circles — the infamous GC death spiral with 80% CPU in
runtime.gcBgMarkWorkerand still rising latency until the OOM. Always leave 5–10% headroom below the container limit and first reduce the live heap (lessons 97 and 99), then touch GOGC.
Check: What happens if you set GOGC=off in a long-running server because the machine has plenty of RAM?
Answer: The heap grows without bound until the process eventually dies at the RAM or container limit — GOGC=off only makes sense for short, terminating processes
GOGC=off disables cycle planning entirely: the collector no longer starts because the target size is infinite. As long as allocation continues, the heap grows — “enough RAM” does not mean the process may take it unboundedly (think cgroup limits in Kubernetes). GOGC=off is deliberately intended for batch jobs and short CLIs that terminate before the first relevant GC cycle. In long-running services GOMEMLIMIT is the right protection knob.
Takeaways:
GODEBUG=gctrace=1 shows cycles live: 47->49->25 MB means start, mark-end, and live heap — the live-heap number is the most important one.live heap × (1 + GOGC/100); higher means less CPU, more peak memory.runtime/metrics (/memory/classes/heap/objects:bytes) before moving any knob — scaling foundations: architecture module 7.The CPU profile from lesson 96 showed it: over 50% of compute time in runtime.mallocgc. The "Kant & Curves" accounting endpoints serialize invoice texts per request — and every string concatenation with += allocates fresh. The goal "zero alloc" does not mean zero allocations in the whole program, but zero allocations in the hot path per request. Three patterns cover 90% of the cases: strings.Builder for strings, preallocation for slices with a known length, sync.Pool for reusable buffer objects.
Pattern 1 — strings.Builder with Grow: instead of allocating a new string on every +=, the builder collects into an internal byte slice, and Grow reserves the space once up front:
// internal/render/invoice.go — invoice lines without an allocation cascade
package render
import "strings"
var items = []string{
"978-3-423-2089-8", "The Trial", "19.90", "Kant & Curves",
"Shelf 4", "Downtown branch", "Discount 3%", "VAT 7%", "Customer 4711", "Reserved",
}
// InvoiceOld: every concatenation allocates a new string
func InvoiceOld() string {
s := ""
for _, it := range items {
s += it + "; "
}
return s
}
// InvoiceNew: Grow reserves up front, WriteString just appends
func InvoiceNew() string {
var b strings.Builder
b.Grow(24 * len(items)) // upper bound for the total need
for _, it := range items {
b.WriteString(it)
b.WriteString("; ")
}
return b.String()
}
// Terminal: go test -bench=. -benchmem ./internal/render/
// → BenchmarkInvoiceOld-10 3015848 403.8 ns/op 760 B/op 10 allocs/op
// → BenchmarkInvoiceNew-10 12158127 117.9 ns/op 240 B/op 1 allocs/op
3.4× faster — and the allocation counts (10 vs. 1) are deterministic, while ns/op varies per machine. The one remaining allocation is the final String() call; it only disappears if you write into a reused buffer instead of returning strings.
Pattern 2 applies wherever the target size is known: make with capacity instead of a nil slice plus append growth. The same goes for map sizes (make(map[string]int, n)) and for pre-computing entire batch structures — database drivers like github.com/jackc/pgx/v5 use the pattern internally too, for example when pgx.CollectRows with generic row mappers avoids the classic []any boxing allocations:
// internal/inventory/titles.go — one allocation instead of log-n many
package inventory
import "fmt"
type Book struct {
Title string
}
// TitlesOld: nil slice, append doubles capacity in steps
func TitlesOld(books []Book) []string {
var titles []string
for _, b := range books {
titles = append(titles, b.Title) // ~log2(len) re-allocations
}
return titles
}
// TitlesNew: capacity up front — exactly one heap allocation
func TitlesNew(books []Book) []string {
titles := make([]string, 0, len(books))
for _, b := range books {
titles = append(titles, b.Title)
}
return titles
}
func main() {
b := []Book{{Title: "The Trial"}, {Title: "Siddhartha"}}
fmt.Println(len(TitlesOld(b)), len(TitlesNew(b)))
// → 2 2
}
For expensive objects (buffers, encoders, large slices) that are needed per request and thrown away afterwards, sync.Pool is the standard tool. The pool is GC-aware: on every GC cycle it may be emptied — it is a reuse mechanism, not a cache with guarantees:
// internal/render/pool.go — buffers from the pool instead of the heap
package render
import (
"bytes"
"fmt"
"io"
"sync"
)
var bufPool = sync.Pool{
New: func() any { return bytes.NewBuffer(make([]byte, 0, 4096)) },
}
// RenderRow writes into a pooled buffer and returns it after use
func RenderRow(w io.Writer, nr int, title string) error {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset() // mandatory! Otherwise old data and capacity linger forever
bufPool.Put(buf)
}()
fmt.Fprintf(buf, "%d. %s\n", nr, title)
_, err := w.Write(buf.Bytes())
return err
}
func main() {
var out bytes.Buffer
for i, title := range []string{"The Trial", "Siddhartha", "Steppenwolf"} {
RenderRow(&out, i+1, title)
}
fmt.Print(out.String())
// → 1. The Trial
// → 2. Siddhartha
// → 3. Steppenwolf
}
Combined with strconv.AppendInt and strconv.AppendQuote instead of fmt.Sprintf, entire serialization paths can be pushed to zero allocations per request — the pattern that also drives the hot paths in encoding/json alternatives and in gRPC marshalling libraries (google.golang.org/protobuf). Anchor the budget as a test so a refactor cannot silently break it:
// internal/render/alloc_test.go — allocation budget as a regression test
package render
import "testing"
func TestInvoiceNewAllocBudget(t *testing.T) {
allocs := testing.AllocsPerRun(100, func() { InvoiceNew() })
if allocs > 1 {
t.Fatalf("InvoiceNew needs %.0f allocations, budget is 1", allocs)
}
}
// Terminal: go test -run TestInvoiceNewAllocBudget ./internal/render/
// → ok bookstore/internal/render 0.012s
⚠ Common mistake: Putting objects back into the pool without a reset.
bufPool.Put(buf)without a precedingbuf.Reset()means: the next user gets stale data — and the buffer keeps its maximum capacity forever, even if a Black Friday spike once grew it to 4 MB. The second casualty: pooling tiny objects. For a 32-byte buffer the pool overhead (lock-free but not free Get/Put logic plus type assertion) costs more than the allocation itself — pooling pays off only for object costs in the microsecond range or expensive initializations.
Check: Why is sync.Pool not a replacement for a cache with a fixed retention time?
Answer: Because the pool may be emptied on every GC cycle — there is no guarantee that a pooled object survives until the next Get
sync.Pool is deliberately built GC-friendly: since Go 1.13 the pool cleans up via a victim cache — after at most two GC cycles, old entries are gone for good. A Get right after a GC phase therefore often hits an empty pool. Anyone who wants to hold objects longer and reliably — say, expensively loaded data — needs a real cache such as a map with TTL, but not a sync.Pool. Its single job is: smoothing allocation pressure during burst phases.
Takeaways:
strings.Builder with Grow instead of += cascades — 10 allocations versus 1 in the example, plus a 3.4× speedup.make(..., 0, len(src)) and map sizes — one allocation instead of log-n many.sync.Pool for expensive buffer objects — but always Reset before Put, and the pool is not a cache (GC may empty it).testing.AllocsPerRun as regression tests — pgx (github.com/jackc/pgx/v5) and protobuf use these patterns internally too.After the Black Friday debacle, the bookshop's management says: "Make the search faster." Where to begin? This is exactly where engineering separates from guesswork: the optimization workflow is a loop with four steps — measure (create a reproducible baseline), understand (read profiles until the bottleneck is proven), fix (remove the found bottleneck, not the most suspicious code), repeat (measure again, prove the improvement, then continue or stop). Everything from lessons 96 to 99 — pprof, escape analysis, GC knobs, zero-alloc patterns — are tools within this loop.
Measure → Understand → Fix → Repeat
The loop protects against two expensive mistakes: optimizing without measuring (feeling instead of proof) and optimizing the wrong spot (micro gains while the real bottleneck remains). Amdahl's law supplies the hard math: if you make a 10% share of runtime 100 times faster, the whole program is only ~9% faster. The leverage is always at the largest share — and only measurement shows where it is.
Benchmarks with testing.B and -count=10 plus benchstat (from golang.org/x/perf/cmd/benchstat) make improvements provable instead of asserted:
// Terminal: baseline under statistical noise, fix, compare
// $ go test -bench=. -benchmem -count=10 ./internal/search/ | tee old.txt
// $ # ... implement the fix (see step 3) ...
// $ go test -bench=. -benchmem -count=10 ./internal/search/ | tee new.txt
// $ benchstat old.txt new.txt
// → │ old.txt │ new.txt │
// → │ sec/op │ sec/op vs base │
// → Search-10 8.146µ ± 3% 1.003µ ± 2% -87.69% (p=0.000 n=10)
A single benchmark run is noisy (thermal throttling, background processes, scheduler); only benchstat with confidence intervals and a p-value turns two measurement series into a statement. Without this baseline, no fix gets committed.
The pprof flame graph from lesson 96 showed for the search: 80% of time in bookstore.CategoryMatch — and not, as suspected, in JSON rendering. The code behind it: for every article, a linear scan over all 10,000 categories — O(n·m). Step 3: fix — the categories belong in a set:
// internal/search/match.go — the proven bottleneck and its fix
package search
import "fmt"
// CategoryMatchOld: linear search over all categories for every article
func CategoryMatchOld(articles, categories []string) int {
n := 0
for _, a := range articles {
for _, c := range categories {
if a == c {
n++
break
}
}
}
return n
}
// CategoryMatchFast: categories into a set once — O(n+m)
func CategoryMatchFast(articles, categories []string) int {
set := make(map[string]struct{}, len(categories))
for _, c := range categories {
set[c] = struct{}{}
}
n := 0
for _, a := range articles {
if _, ok := set[a]; ok {
n++
}
}
return n
}
func main() {
articles := []string{"The Trial", "Siddhartha", "Unknown"}
cats := []string{"Siddhartha", "The Trial"}
fmt.Println(CategoryMatchOld(articles, cats), CategoryMatchFast(articles, cats))
// → 2 2
}
Note the order: first the algorithmic fix (O(n·m) → O(n+m), −87.7% in the benchstat above), then — if still needed — the micro-optimizations from lesson 99. The other way around would be micro-polishing the wrong hill. Step 4: repeat — the next benchstat run proves the gain, the allocation budget from lesson 99 secures it permanently, and only then comes the next round — or the measurement says: good enough, stop.
Performance work never ends "done" but at defined targets: p95 below 100 ms, zero allocations per request in the rendering path, GC pause below 500 microseconds. Such budgets belong in CI as tests (testing.AllocsPerRun, testing.B) — then the build alarms when a refactor breaks them, instead of Black Friday doing it. How to derive latency and load targets for whole systems (caching, read replicas, asynchronization) is the subject of the architecture series — the foundations in Module 7: Scalability: performance is the base that every scale-up stands on.
This concludes both module 20 and the entire Go course — 100 lessons from go mod init to GC tuning. The arc: language and type system (modules 1–6), concurrency and error handling (7–8), testing and HTTP (9–10), architecture and frameworks (11–15), distributed systems with gRPC, cloud-native, and security (16–18), data pipelines (19) — and now performance as a cross-cutting discipline. The optimization workflow ties it together: measure, understand, fix, repeat — for code just as much as for careers.
Weekly check: do you master the following points?
go build -gcflags="-m" tell you why a variable lands on the heap — including the 64 KB rule?runtime/metrics?sync.Pool is not a cache)?benchstat — and do you know when stopping is the right result?⚠ Common mistake: Claiming "faster" without a baseline and comparison measurement. Anyone who optimizes by feel sometimes commits code that is slower and notices only at the next Black Friday — individual benchmark runs fluctuate by double-digit percentages. And the reverse trap is just as real: micro-optimizing cold paths (startup code, one-time initialization) is pure waste of lifetime. Without a
benchstatcomparison and an identified bottleneck from the profile, every optimization is only a hypothesis.
Check: Which step does every correct performance optimization begin with?
Answer: With a reproducible measurement: a benchmark baseline under realistic load, against which the later fix gets compared
Without a baseline there is nothing to compare against — the claim “faster” becomes unprovable, and benchstat cannot make a significance statement. The flame graph belongs in the understand step: it shows on-CPU shares, but the widest bar is not automatically the bottleneck (it might be uncritical while the real latency lies in waiting). The loop is measure → understand → fix → repeat — and the first step is always the measurement.
Takeaways:
-count=10 and comparison with benchstat (golang.org/x/perf/cmd/benchstat): only significance with a p-value counts, single values are noise.Course navigation: ← Module 19 · All 20 modules