Golang / Golang Internals and Memory Management Interview Questions
How do you profile a Go application using pprof?
Go ships net/http/pprof (for running services) and the runtime/pprof package for programmatic profiling. Profiles are the primary tool for diagnosing CPU hotspots, memory leaks, and goroutine leaks in production.
// Γ’ΒΒΓ’ΒΒ HTTP endpoint (register once, profile on demand) Γ’ΒΒΓ’ΒΒ import _ "net/http/pprof" // blank import registers handlers import "net/http" go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // Profile endpoints: // http://localhost:6060/debug/pprof/goroutine?debug=1 Γ’ΒΒ goroutines // http://localhost:6060/debug/pprof/heap Γ’ΒΒ heap snapshot // http://localhost:6060/debug/pprof/profile?seconds=30 Γ’ΒΒ CPU profile // Γ’ΒΒΓ’ΒΒ CLI usage Γ’ΒΒΓ’ΒΒ // Download and view CPU profile: // go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 // (pprof) top10 Γ’ΒΒ top 10 functions by CPU // (pprof) web Γ’ΒΒ opens flame graph in browser // (pprof) list myFunc Γ’ΒΒ annotated source for myFunc // Heap profile: // go tool pprof http://localhost:6060/debug/pprof/heap // (pprof) top10 -cum Γ’ΒΒ cumulative allocation // (pprof) alloc_space Γ’ΒΒ total bytes allocated (not just live) // (pprof) inuse_space Γ’ΒΒ currently live bytes // Γ’ΒΒΓ’ΒΒ Benchmark profiling Γ’ΒΒΓ’ΒΒ // go test -bench=. -cpuprofile=cpu.out -memprofile=mem.out // go tool pprof cpu.out // Γ’ΒΒΓ’ΒΒ Programmatic (for batch programs) Γ’ΒΒΓ’ΒΒ f, _ := os.Create("cpu.prof") pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() // ... run workload ... // go tool pprof cpu.prof
The execution tracer (go tool trace) complements pprof: it shows fine-grained goroutine scheduling, syscall latency, and GC events on a timeline β useful when pprof shows low CPU usage but latency is still high (often caused by goroutine blocking or GC pauses).
More Related questions...