Skip to content

Instantly share code, notes, and snippets.

@slok
Last active November 4, 2024 01:07
Show Gist options
  • Save slok/33dad1d0d0bae07977e6d32bcc010188 to your computer and use it in GitHub Desktop.
Save slok/33dad1d0d0bae07977e6d32bcc010188 to your computer and use it in GitHub Desktop.
Go pprof cheat sheet

Enable profiling

Default http server

import (
    _ "net/http/pprof"
    "net/http"
)

//...

return http.ListenAndServe(":8081", nil)

Non-default server

import (
  	"net/http"
	"net/http/pprof"
)

//...

mux := http.NewServeMux()

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

// ...

server := &http.Server{
  Addr:    ":8081",
  Handler: mux,
}

return server.ListenAndServe()

Memory

Gain access to pprof data in the Go service (e.g from Kubernetes)

kubectl -n my-ns port-forward svc/my-app 8081:8081

Get the memory profile

curl -s http://127.0.0.1:8081/debug/pprof/heap > ./heap.out

Load and read profile

As an alternative you can use speedscope.

go tool pprof -http=:8080 ./heap.out
Additional info for reading
  • inuse_space: Amount of memory allocated and not released yet (Important).
  • inuse_objects: Amount of objects allocated and not released yet.
  • alloc_space: Total amount of memory allocated (regardless of released).
  • alloc_objects: Total amount of objects allocated (regardless of released).

CPU

Gain access to pprof data in the Go service (e.g from Kubernetes)

kubectl -n my-ns port-forward svc/my-app 8081:8081

Get the CPU profile

By default will be 30s of CPU profile:

curl -s http://127.0.0.1:8081/debug/pprof/profile > ./cpu.out

Customize the time with ?seconds=N:

curl -s http://127.0.0.1:8081/debug/pprof/profile?seconds=60 > ./cpu.out

Load and read profile

As an alternative you can use speedscope.

go tool pprof -http=:8080 ./cpu.out

CPU trace

Gain access to pprof data in the Go service (e.g from Kubernetes)

kubectl -n my-ns port-forward svc/my-app 8081:8081

Get the CPU trace profile

By default will be 1s of CPU trace profile:

curl -s http://127.0.0.1:8081/debug/pprof/trace > ./cpu-trace.out

Customize the time with ?seconds=N:

curl -s http://127.0.0.1:8081/debug/pprof/trace?seconds=60 > ./cpu-trace.out

Load and read profile

go tool trace -http=:8080 ./cpu-trace.out
@paulburlumi
Copy link

This site recommends only exposing pprof on loopback which I think would improve this solution.
https://docs.boostsecurity.io/rules/code-debugging-interface-publicly-exposed.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment