goroutine泄漏比性能差更致命,常见于未close channel、无限等待select或time.After未消费channel;应通过pprof监控,避免无限制启goroutine,改用限流worker pool,并确保select含default或case。
高并发下性能上不去,八成不是 CPU 或内存瓶颈,而是 goroutine 没被回收。常见于忘记 close() channel、无限等待 select、或用 time.After 做超时却没消费其 channel。
pprof/goroutines 查看实时 goroutine 数量:启动时加 _ "net/http/pprof",访问 /debug/pprof/goroutine?debug=2
for _, req := range requests {
go handle(req) // ❌ 可能爆炸
}改用带限流的 worker pool(如 semaphore.NewWeighted(10))select 的 goroutine 必须有 default 或 case ,否则可能永久阻塞
channel 不是万能队列,它本质是同步原语。高并发下滥用无缓冲 channel(make(chan int))会导致大量 goroutine 频繁切换和锁竞争。
make(chan *Request, 1024),缓冲大小按 P99 请求处理时长 × QPS 估算sync.Pool 复用send on closed channel

val := ,要判断是否关闭:val, ok := ,否则可能卡死或读到零值
time.After 内部启动一个 goroutine 管理定时器,高频调用(如每毫秒一次)会快速堆积 goroutine;context.WithTimeout 同样依赖底层 timer,但更可控。
time.Timer:timer := time.NewTimer(timeout) ... timer.Reset(timeout) // 重用,不新建 defer timer.Stop()
req.Context(),而非自己 new context;中间件注入 deadline 后,下游 DB/HTTP client 要显式支持该 contextcontext,PostgreSQL 需配 pgx.ConnConfig.RuntimeParams["statement_timeout"] = "5000",MySQL 用 SET SESSION MAX_EXECUTION_TIME=5000
频繁 make([]byte, n) 或构造小结构体(如 http.Header)是 GC 压力主因。sync.Pool 能显著降低分配频次,但要注意生命周期管理。
GODEBUG=gctrace=1)对比 allocs/op,比压测 QPS 更早发现问题var jsonBufPool = sync.Pool{
New: func() interface{} {
return make([]byte, 0, 4096)
},
}
buf := jsonBufPool.Get().([]byte)
buf = buf[:0]
// use buf for json.Unmarshal
jsonBufPool.Put(buf)