03 / 05

How would you profile and optimize a Go service that has high GC pressure?

Start with pprof heap and CPU profiles to find top allocators, then reduce allocations using sync.Pool, pre-allocated slices, and avoiding interface boxing in hot paths.

Profiling setup and analysis
Optimization techniques
  1. 1

    sync.Pool: reuse short-lived objects (byte buffers, encoder/decoder instances) across requests

  2. 2

    Pre-allocate slices: make([]T, 0, knownSize) avoids repeated doublings

  3. 3

    Avoid fmt.Sprintf in hot paths: use strings.Builder or strconv for string construction

  4. 4

    Avoid interface{} boxing: passing concrete types to interface{} parameters allocates on heap

  5. 5

    Flat data structures: avoid deep pointer graphs — GC must trace every pointer

  6. 6

    Use GODEBUG=gctrace=1 to monitor GC frequency and pause times in production

sync.Pool example