Go performance cookbook: 4 recipes, 4 short videos
Fast Go code comes down to a few habits.
Measure before you guess. Share work across goroutines. Don’t keep calling a service that’s down. Know where your values live.
Here are four recipes, one for each habit. Every one has code you can run, and a short video if you’d rather watch.
1. Find the slow function: CPU profiling
The analogy: a profiler is like a photographer who snaps your program a hundred times a second. Count which function shows up in the most photos, and you’ve found where the time goes.
Start from a benchmark. Since Go 1.24, b.Loop() is the way to write one:
func Sum(nums []int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func BenchmarkSum(b *testing.B) {
nums := make([]int, 1_000_000)
for b.Loop() {
Sum(nums)
}
}
Run the benchmark with the profiler on. -run='^$' skips the normal tests:
go test -bench=Sum -run='^$' -cpuprofile cpu.out
Then look at the photos:
go tool pprof -top cpu.out
flat flat% sum% cum cum%
940ms 92.16% 92.16% 1020ms 100% cookbook/profiling.Sum (inline)
In a real program, that list has hundreds of functions. The top few are where to start.
For a picture instead of a table, go tool pprof -http=:8080 cpu.out opens the profile in your browser, flame graph included.
2. Share the work: a worker pool
The analogy: a kitchen with three cooks and one order rail. Orders go on the rail. Whichever cook is free takes the next one.
The rail is a channel. The cooks are goroutines.
func worker(id int, jobs <-chan string, results chan<- string) {
for job := range jobs {
time.Sleep(100 * time.Millisecond) // pretend this is real work
results <- fmt.Sprintf("worker %d did %s", id, strings.ToUpper(job))
}
}
func main() {
jobs := []string{"one", "two", "three", "four", "five"}
jobCh := make(chan string)
results := make(chan string, len(jobs))
var wg sync.WaitGroup
for id := 1; id <= 3; id++ { // three workers
wg.Go(func() { worker(id, jobCh, results) })
}
for _, job := range jobs {
jobCh <- job
}
close(jobCh) // no more jobs: workers finish their loops
wg.Wait()
close(results)
for r := range results {
fmt.Println(r)
}
}
Five jobs of 100 ms each take 500 ms one after another. With three workers, they took 200 ms.
wg.Go is new in Go 1.25. On older versions, call wg.Add(1) and start the goroutine yourself.
Why not just start one goroutine per job? With a million jobs, you’d get a million goroutines all fighting over the same database. A pool keeps the work flowing at a pace the rest of your system can handle.
3. Stop calling a service that’s down: a circuit breaker
The analogy: the fuse box in your house. When a fault keeps happening, it trips and cuts the power, so nothing gets damaged. After a while, you flip it back on to test it.
A circuit breaker sits between your service and one it depends on:
- Closed: calls go through as normal.
- Open: too many failed, so calls stop at once with an error. No waiting for timeouts.
- Half-open: after a pause, one test call goes through. If it works, the breaker closes. If not, it opens again.
With sony/gobreaker (v2):
var cb = gobreaker.NewCircuitBreaker[[]byte](gobreaker.Settings{
Name: "service-b",
Timeout: 5 * time.Second, // how long to stay open before one test call
ReadyToTrip: func(c gobreaker.Counts) bool {
failureRatio := float64(c.TotalFailures) / float64(c.Requests)
return c.Requests >= 10 && failureRatio >= 0.6
},
OnStateChange: func(name string, from, to gobreaker.State) {
log.Printf("%s: %s -> %s", name, from, to)
},
})
func get(url string) ([]byte, error) {
return cb.Execute(func() ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return nil, fmt.Errorf("service-b: %s", resp.Status)
}
return io.ReadAll(resp.Body)
})
}
When the breaker is open, get returns gobreaker.ErrOpenState straight away. Check for it with errors.Is, and serve a cached answer or a friendly error instead.
I ran it against a fake service that failed its first 12 requests, with a 200 ms timeout so the demo finishes quickly:
service-b: closed -> open
call 11: skipped, breaker open
service-b: open -> half-open
service-b: half-open -> open
...
service-b: open -> half-open
service-b: half-open -> closed
call 22: hello
Of 25 calls, the struggling service received only 16. The other 9 were stopped before they could add to its load.
4. Keep values off the heap: escape analysis
The analogy: each function call gets a notepad, the stack, and it’s wiped clean the moment the function returns. Anything that must outlive the call goes in the shared storeroom, the heap. The storeroom needs a cleaner, Go’s garbage collector, and the cleaner costs time.
func square(x int) int {
return x * x
}
func newNumber() *int {
n := 42
return &n // n must outlive this function
}
func main() {
fmt.Println(square(4), *newNumber())
}
Ask the compiler what it decided:
go build -gcflags=-m .
./main.go:5:6: can inline square
./main.go:9:6: can inline newNumber
./main.go:10:2: moved to heap: n
newNumber hands out the address of n. A note from a notepad that’s about to be wiped is no use, so n moves to the storeroom.
square is so small that the compiler pastes its body straight into main. That’s inlining, and it saves a function call.
You’ll also see lines saying the values passed to fmt.Println escape. It takes interfaces, which often pushes values to the heap. That’s one reason hot loops avoid fmt.
Most heap allocations are fine. Check escape analysis when a profile shows the garbage collector working hard.
Which recipe when
| Problem | Recipe |
|---|---|
| “It’s slow and I don’t know why” | CPU profiling |
| A big pile of independent jobs | Worker pool |
| A dependency keeps failing or timing out | Circuit breaker |
| A profile shows lots of garbage collection | Escape analysis |
Profile first. The other three are fixes, and the profile tells you which one you need.
For benchmarks and the execution tracer, see my older post, How to check & improve performance in Go program.