goroutine泄漏比性能差更致命,常见于未close channel、无限等待select或time.After未消费channel;应通过pprof监控,避免无限制启goroutine,改用限流worker pool,并确保select含default或case。

goroutine 泄漏比性能差更致命
高并发下性能上不去,八成不是 CPU 或内存瓶颈,而是 goroutine 没被回收。常见于忘记 close() channel、无限等待 select、或用 time.After 做超时却没消费其 channel。
- 用
pprof/goroutines查看实时 goroutine 数量:启动时加_ "net/http/pprof",访问/debug/pprof/goroutine?debug=2 - 避免在循环中无条件起 goroutine:
for _, req := range requests { go handle(req) // ❌ 可能爆炸 }改用带限流的 worker pool(如semaphore.NewWeighted(10)) - 所有带
select的 goroutine 必须有default或case ,否则可能永久阻塞
channel 使用不当会拖垮吞吐量
channel 不是万能队列,它本质是同步原语。高并发下滥用无缓冲 channel(make(chan int))会导致大量 goroutine 频繁切换和锁竞争。
- 生产者消费者模型优先用带缓冲 channel:
make(chan *Request, 1024),缓冲大小按 P99 请求处理时长 × QPS 估算 - 不要用 channel 传大对象(如结构体副本),改传指针或
sync.Pool复用 - 关闭 channel 前确认所有发送方已退出,否则 panic:
send on closed channel - 读取 channel 时别只写
val := ,要判断是否关闭:val, ok := ,否则可能卡死或读到零值
context.WithTimeout 和 time.After 的隐藏开销
time.After 内部启动一个 goroutine 管理定时器,高频调用(如每毫秒一次)会快速堆积 goroutine;context.WithTimeout 同样依赖底层 timer,但更可控。
- 高频超时场景,复用
time.Timer:timer := time.NewTimer(timeout) ... timer.Reset(timeout) // 重用,不新建 defer timer.Stop()
- HTTP handler 中必须用
req.Context(),而非自己 new context;中间件注入 deadline 后,下游 DB/HTTP client 要显式支持该 context - 数据库查询超时不能只靠
context,PostgreSQL 需配pgx.ConnConfig.RuntimeParams["statement_timeout"] = "5000",MySQL 用SET SESSION MAX_EXECUTION_TIME=5000
sync.Pool 在高频对象分配中的真实收益
频繁 make([]byte, n) 或构造小结构体(如 http.Header)是 GC 压力主因。sync.Pool 能显著降低分配频次,但要注意生命周期管理。
立即学习“go语言免费学习笔记(深入)”;
- Pool 对象不能含指针到长生命周期数据(如全局 map),否则阻止 GC
- Put 前清空敏感字段(如 token、password),避免下次 Get 时残留数据
- 测试时关掉 GC(
GODEBUG=gctrace=1)对比 allocs/op,比压测 QPS 更早发现问题 - 示例:复用 JSON 解析缓冲
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)











