melkor-lab

Profiling a Go service in production without drama

· 5 min read

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

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.