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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
