How to do pprof for gRPC service

Summary

To perform pprof profiling on a gRPC service, which lacks direct HTTP access, developers can launch an asynchronous HTTP server alongside the gRPC server. Importing net/http/pprof automatically registers the necessary debug routes on the default ServerMux. For custom ServerMux implementations, these routes must be manually registered to expose endpoints like /debug/pprof/profile. This setup allows accessing profiling data via the dedicated HTTP server, enabling analysis of CPU usage and other performance metrics for the gRPC application.

gRPC is a RPC framework based on HTTP and is frequently used for communications among micro service inside the same organization network. However,  the service functions cannot be accessed via normal HTTP URL as it's not a WEB framework. In this case, how to do pprof on a gRPC service?

The trick is starting a HTTP server asynchronously while starting the gRPC service. This HTTP server can be accessed to run prrof debug.

go func(){
	http.ListenAndServe(":10001", nil)
}()

Since it uses the default ServerMux, the pprof related routes will be registered automatically after importing the package net/http/pprof.

import _ "net/http/pprof"

If you are using customized ServerMux, can register below routes in your code.

r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/heap", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)

The complete code logic structure looks like:

func main () {
  go func() {
    http.ListenAndServe(":10001", nil)
  }()
  
  lis, err := net.Listen("tcp", 10000)
  grpcServer := grpc.NewServer()
  pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
  grpcServer.Serve(lis)
}

Now once the service is started, can access {server_ip}:10001/debug/pprof/profile to trigger pprof generation. 

With this, you can check CPU usage and other metrics.

Reference: Golang程序性能分析(三)用pprof分析gRPC服务的性能 (qq.com)

GOLANG PPROF GRPC

  RELATED

  COMMENTS

0

No comment for this article.