Profiling a Go service in production without drama
Every Go binary I ship can be profiled live. It costs almost nothing while idle, and the one time a service starts eating CPU at 3 a.m. it pays for itself.
Keep pprof off the public port
Importing net/http/pprof registers its handlers on the default mux. If your public server also uses the default mux, you have just published your heap. I always serve the profiler on its own loopback listener:
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
go http.ListenAndServe("127.0.0.1:6060", mux)
Then reach it through an SSH tunnel when needed. Nothing new is exposed.
The three profiles I actually use
- CPU:
go tool pprof -http=:8081 'http://127.0.0.1:6060/debug/pprof/profile?seconds=30'. The overhead while sampling is a few percent. - Heap:
/debug/pprof/heap, compared against a snapshot taken an hour earlier with-base. - Goroutines:
/debug/pprof/goroutine?debug=2when something is stuck. Leaked goroutines show up as thousands of identical stacks.
One habit that helps
Label the work you care about with pprof.Do and a couple of labels such as the queue name. The flame graph then tells you not only which function is hot, but for whom.