1.5 KiB
1.5 KiB
Performance Troubleshooting
CPU Profiling
Use pprof CPU profile to capture a 30s sample (see pprof.md for commands), then inspect with top, web, or list funcName.
Common CPU hogs:
- JSON marshal/unmarshal in hot path — preallocate buffers, use faster libraries
- Reflection in critical path
- Unnecessary allocations — use sync.Pool
- O(n^2) hidden in nested loops
- Too many syscalls — batch operations
Memory Profiling
Use pprof heap profile (see pprof.md). Compare heap snapshots over time with go tool pprof -base heap1.prof heap2.prof to find growth. Use escape analysis (see diagnostic-tools.md) to find unexpected heap allocations in hot paths.
Common memory leaks:
- Unbounded cache without eviction
- Growing slices in loops (forgetting to reset)
- Global maps never cleared
- String concatenation in loops (use
strings.Builder) - Large structs passed by value
Lock Contention
Symptoms: CPU high but throughput low, latency increases with load, multiple cores don't help.
Enable profiling in code:
runtime.SetMutexProfileFraction(1)
runtime.SetBlockProfileRate(1)
Then use pprof mutex and block profiles (see pprof.md).
Solutions:
- Reduce critical section — hold lock for minimal time
- Sharding — multiple locks for different data
sync.Map— for read-heavy workloadsatomic— for simple countersRWMutex— when reads >> writes