context树节点本身不泄漏内存,真正泄漏的是context.Value持有的大对象或未调用的cancelFunc——后者导致timer、channel及闭包变量长期驻留堆上。

Go 里 context 树节点本身不直接泄漏内存,真正泄漏的是被 context.Value 持有的大对象,或 context.WithCancel/WithTimeout 返回的 cancelFunc 被长期持有却未调用——导致其内部 timer、channel、闭包变量全被钉在堆上。
为什么 context.Value 不该存大结构体
context.Value 是 map[interface{}]interface{} 的浅层封装,但它的生命周期由 parent context 决定。一旦你把 *bytes.Buffer、[][]byte 或自定义大结构体塞进 ctx.Value(key, hugeObj),只要 context 还活着(比如 context.Background() 或 HTTP server 启动时创建的根 context),hugeObj 就永远不可回收。
常见错误现象:pprof -inuse_space 显示大量 *bytes.Buffer 或 []uint8 占用高位,调用栈指向 http.serverHandler.ServeHTTP → yourMiddleware → ctx.WithValue;但你根本没在 middleware 里显式 new 这些 buffer。
- 只存轻量标识:用户 ID、trace ID、request ID 等字符串或整数,别存结构体指针
- 避免嵌套传递:不要在中间层反复
WithValue构建新 context,而应一次性注入必要字段 - 用
context.WithValue(ctx, key, &smallStruct{})比context.WithValue(ctx, key, smallStruct{})更危险——前者让整个 struct 被强引用,后者只传值拷贝(但依然不推荐)
cancelFunc 泄漏:timer 和 channel 被卡住
context.WithCancel 和 context.WithTimeout 返回的 cancel 函数不是“用完即焚”的无状态函数,它内部持有一个未关闭的 chan struct{} 和(对 WithTimeout)一个未 Stop 的 *time.Timer。如果你把 cancel 存进全局 map、结构体字段,或作为回调参数传给第三方库后就不管了,这些资源就永远泄漏。
错误现象:pprof -goroutine 里看到大量 runtime.timerproc 或 runtime.selectgo 状态 goroutine;pprof -heap 中 *time.Timer 和 chan struct{} 实例数随请求线性增长。
- cancel 函数必须成对调用:有
WithCancel就得有明确调用点,不能只声明不执行 - 绝不在结构体中保存 cancel 函数:比如
type Service struct { cancel context.CancelFunc }—— 这会让 Service 生命周期绑定 cancel,而 cancel 又拖着 timer - HTTP handler 中启动 goroutine 时,若用了
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second),必须确保 handler 返回前调用cancel(),哪怕提前 return
context.WithValue 配合 defer 导致的隐式长生命周期
很多人写中间件时习惯这样:
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, _ := getUserFromToken(r)
ctx := context.WithValue(r.Context(), userKey, user) // ← user 可能是 *User,含大量字段
r = r.WithContext(ctx)
defer func() {
log.Info("request done") // ← defer 在 handler 返回后才执行,但 ctx 已注入到 r,且可能被下游 handler 传给 goroutine
}()
next.ServeHTTP(w, r)
})
}
问题在于:如果 next 启动了一个后台 goroutine,并把 r.Context() 传了进去(比如日志上报、异步审计),那 user 就被这个 goroutine 闭包捕获,直到 goroutine 结束——而这个结束时间完全不可控。
- 避免在 defer 作用域外传递 context.Value 数据:所有依赖 value 的逻辑必须在当前 handler 函数内完成
- 改用显式参数传递:把
user.ID提出来,作为参数传给下游函数,而不是塞进 ctx - 如果必须跨 goroutine 传递,用
context.WithValue(context.Background(), ...)构造全新短生命周期 context,而非复用 request context
如何验证 context 相关泄漏是否已修复
光看代码没用,得用 pprof 抓两次快照比对。重点不是内存总量,而是对象存活链路是否切断。
- 启动服务后等 1 分钟,执行
curl -s "http://localhost:6060/debug/pprof/heap?debug=1" | grep -E "(heap_inuse|heap_objects)"记下 baseline - 发 100 次请求,再等 30 秒,抓第二次 heap;对比
heap_objects增量是否回落——若不回落,说明有对象没被 GC - 用
go tool pprof -http=:8080 your_binary heap.pb.gz,在 Web UI 中 Focus 输入*time.Timer或你怀疑的结构体名,看 Call graph 是否还指向context.WithTimeout或context.WithValue - 给关键结构体加
runtime.SetFinalizer(仅调试):如果 finalizer 从不触发,说明它仍被 context 树某处强引用着
最易被忽略的一点:context 泄漏往往不表现为内存暴涨,而是“稳定缓慢上涨 + 大量 timer/goroutine 堆积”,因为每个泄漏的 cancelFunc 只占几 KB,但累积几百个就足以拖垮服务。











