Go Profiling dan Observability
Definisi
Go punya tooling observability bawaan: net/http/pprof (CPU/mem/goroutine profile), expvar (metrik JSON di /debug/vars), dan runtime/trace (timeline eksekusi). Digunakan untuk menemukan bottleneck tanpa APM eksternal.
Kapan dipakai
Pakai saat produksi lambat, memory leak, atau goroutine bocor. Jangan enable pprof di public endpoint tanpa auth — itu info sensitif.
Cara kerja
Enable pprof
import _ "net/http/pprof"
// di main: go func() { http.ListenAndServe("localhost:6060", nil) }()go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30expvar
var hits = expvar.NewInt("hits")
hits.Add(1)
// GET /debug/vars -> {"hits": 1, ...}trace
f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()
// jalankan beban, lalu: go tool trace trace.outStruktur alur
Loading diagram...
Catatan implementasi
- pprof listen di localhost saja; jangan bind ke 0.0.0.0 publik.
- Profile CPU default 30 detik; naikkan bila perlu.
expvarotomatis exposememstats; tambah metric bisnis viaexpvar.New*.- Di production, lebih baik kirim ke OTLP collector daripada expose endpoint.
Kesalahan umum
- pprof terbuka publik: kebocoran info internal; bind localhost + auth.
- Profile terlalu singkat: data tidak representatif; sesuaikan durasi.
- Lupa stop trace: file raksasa; selalu defer Stop.
- Over-profile di dev: cukup saat ada gejala nyata.