Performance Optimization
Go is fast by default, but production services need deliberate optimization: pprof profiling, reducing allocations, connection pooling, and caching.
Introduction
Go is fast by default, but production services need deliberate optimization: pprof profiling, reducing allocations, connection pooling, and caching. Premature optimization wastes time — profile first, optimize hot paths proven by data.
Tools: go tool pprof for CPU/heap, trace for goroutine analysis, benchstat for benchmarks. sync.Pool reuses allocated objects; escape analysis hints at stack vs heap allocation. Interviewers ask how you'd diagnose a slow API under load.
This lesson demonstrates pprof endpoints, allocation reduction, and connection pool tuning — skills expected at mid-level Go backend roles.
The story
Google's Bigtable client and Cloudflare's edge proxies optimize hot paths with sync.Pool to reuse byte buffers, avoid allocations in tight loops, and profile with pprof before optimizing. A payment service cut P99 latency 40% by pooling JSON encode buffers — not by rewriting in Rust, but by removing GC pressure identified in a CPU profile.
Measure first: go test -bench, net/http/pprof, and execution traces reveal where time and allocations actually go.
Understanding the topic
Key concepts
- net/http/pprof exposes /debug/pprof/ on admin port.
- CPU profile: go tool pprof http://localhost:6060/debug/pprof/profile.
- Heap profile finds allocation hotspots.
- sync.Pool reuses temporary objects reducing GC pressure.
- GOMAXPROCS defaults to NumCPU — rarely change.
- Compiler inlines small functions; escape analysis in -gcflags=-m.
Step-by-step explanation
- Reproduce slowness under load (hey, k6, vegeta).
- Capture CPU profile during load test.
- Identify top functions in pprof flame graph.
- Reduce allocations in hot loop — biggest GC win.
- Tune DB pool, HTTP client pool, cache hot reads.
- Re-benchmark to verify improvement.
Practical code example
pprof server and sync.Pool for buffer reuse:
package mainimport ("fmt""net/http"_ "net/http/pprof""sync")var bufPool = sync.Pool{New: func() any {b := make([]byte, 0, 4096)return &b},}func handleRequest(w http.ResponseWriter, r *http.Request) {bufPtr := bufPool.Get().(*[]byte)buf := (*bufPtr)[:0]defer func() {*bufPtr = buf[:0]bufPool.Put(bufPtr)}()for i := 0; i < 100; i++ {buf = append(buf, byte(i%26+'a'))}w.Write(buf)}func main() {go func() {fmt.Println("pprof on localhost:6060")http.ListenAndServe("localhost:6060", nil) // DefaultServeMux holds the pprof handlers}()api := http.NewServeMux() // separate mux keeps /debug/pprof off the public portapi.HandleFunc("/data", handleRequest)fmt.Println("api on :8080")http.ListenAndServe(":8080", api)}
Line-by-line code explanation
var bufPool = sync.Pool{creates a pool of reusable objects. A sync.Pool keeps spare values so they can be reused instead of being allocated again for every request, and Go may drop them during garbage collection.b := make([]byte, 0, 4096)runs inside the pool's New function when the pool is empty. It makes an empty byte slice with room for 4096 bytes, and the function returns a pointer to it.bufPtr := bufPool.Get().(*[]byte)takes a buffer from the pool, or creates one with New, and uses a type assertion to turn the stored any value back into a *[]byte. The next line, buf := (*bufPtr)[:0], resets its length to 0 for use.*bufPtr = buf[:0]runs in a deferred function. It stores the slice back through the pointer, in case append had to grow it, with its length reset to 0. The deferred function then returns the pointer to the pool with Put.buf = append(buf, byte(i%26+'a'))adds 100 lowercase letters, cycling through a to z. After the loop, w.Write(buf) sends them as the response body._ "net/http/pprof"is a blank import. Importing the package registers the profiling endpoints under /debug/pprof on the default mux, even though nothing in the code uses the package by name.http.ListenAndServe("localhost:6060", nil)runs in a goroutine and serves the default mux, which now holds the pprof handlers, on localhost only. It first prints pprof on localhost:6060.api := http.NewServeMux()creates a separate router for the public API. Since the pprof handlers were registered on the default mux, they are not reachable through this one.http.ListenAndServe(":8080", api)serves the /data route on port 8080 using that separate router, after printing api on :8080.
Key takeaway: Importing net/http/pprof registers handlers on DefaultServeMux, so serve DefaultServeMux only on localhost and give the public API its own ServeMux. sync.Pool reduces GC from repeated buffer allocation. Profile before optimizing.
Real-world use
Where you'll use this in production
- API latency reduction under 10K RPS load.
- Memory leak diagnosis in long-running workers.
- JSON serialization optimization in hot handlers.
- Database query optimization after pprof shows wait time.
Best practices
- Profile production-like load, not idle servers.
- Reduce allocations before micro-tuning CPU.
- Cache immutable read-heavy data with TTL.
- Use connection pools — DB and HTTP.
- Separate admin/pprof port from public API.
- Document baseline benchmarks in repo.
Common mistakes
- Optimizing without profiling data.
- sync.Pool storing objects with lingering references — memory leak.
- Leaving pprof on public port — security risk.
- Ignoring database as bottleneck — optimizing JSON while SQL slow.
- Setting GOMAXPROCS incorrectly on container with CPU limits.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionGo profiling tools?+
Answer
2BeginnerQuestionsync.Pool purpose?+
Answer
3IntermediateQuestionDiagnose high memory usage?+
Answer
4IntermediateQuestionOptimize handler doing JSON + DB?+
Answer
5AdvancedQuestionAPI 500ms p99 — investigation steps?+
Answer
Summary
Profile with pprof before optimizing — data drives decisions. Reduce allocations in hot paths for GC improvements. sync.Pool reuses buffers; tune connection pools. Keep pprof on admin port only; secure in production. Next lesson: security best practices.