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.profThe 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).
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...
