Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you profile a Go service in production using pprof?
Go ships a built-in profiler accessible via HTTP when you import net/http/pprof. Adding this to a running service provides CPU profiles, heap snapshots, goroutine dumps, and block profiles without restarting the service.
// Add to main or a dedicated debug server import _ "net/http/pprof" // side-effect import registers /debug/pprof/ handlers // Expose on a separate internal port (never public-facing) go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // Available endpoints: // /debug/pprof/ â index page // /debug/pprof/goroutine â goroutine dump // /debug/pprof/heap â heap snapshot // /debug/pprof/profile?seconds=30 â 30s CPU profile // /debug/pprof/trace?seconds=5 â execution trace // /debug/pprof/block â goroutine blocking // /debug/pprof/mutex â mutex contention // CLI usage: // go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 // > top10 â top CPU-consuming functions // > web â opens flame graph in browser // > list funcName â annotated source code // Heap profile: // go tool pprof http://localhost:6060/debug/pprof/heap // > top10 -cum â cumulative allocations // > alloc_space â total bytes allocated (not just live) // > inuse_space â currently live bytes // Goroutine leak check: // curl http://localhost:6060/debug/pprof/goroutine?debug=2 // Shows full stack traces of all goroutines // Programmatic profiling in tests: // go test -bench=. -cpuprofile=cpu.out -memprofile=mem.out // go tool pprof cpu.out
More Related questions...