Kratos 框架无特殊 magic,协程泄漏定位方式与标准 Go 项目一致;需在每个 HTTP handler 入口/出口手动打点 runtime.NumGoroutine(),避免中间件统一打点,并注意健康检查初始化和日志异步刷盘影响。

Kratos 框架本身不掩盖 Go 原生行为,协程泄漏和性能瓶颈的定位方式和标准 Go 项目完全一致——没有 Kratos 特有的 magic,只有更清晰的埋点位置和更易被忽略的框架层陷阱。
runtime.NumGoroutine() 在 Kratos HTTP handler 里怎么打点才有效
Kratos 的 http.Server 和 grpc.Server 都是封装了标准 net/http 和 gRPC-Go,但默认不暴露协程数变化。你不能只在 main() 里打一次日志就完事。
- 在每个 HTTP handler 入口和出口加日志(别用中间件统一打,中间件可能被复用、生命周期不匹配):
log.Printf("goroutines@%s-start: %d", r.URL.Path, runtime.NumGoroutine())log.Printf("goroutines@%s-done: %d", r.URL.Path, runtime.NumGoroutine()) - 如果用了
kratos/pkg/conf/paladin或kratos/pkg/log,确保日志不被异步刷盘阻塞(否则@done日志可能晚于实际退出) - 注意 Kratos 默认启了健康检查 endpoint(
/health),它会常驻几个 goroutine;压测前先 curl 一次/health让它初始化,再记下空闲 baseline
pprof /goroutine?debug=2 抓到大量卡在 kratos/pkg/transport/http.(*Server).ServeHTTP 是不是框架问题
不是。这是典型误判。
-
kratos/pkg/transport/http.(*Server).ServeHTTP是 Kratos HTTP server 的入口函数,所有请求都从这里进,但它本身不创建新 goroutine;真正泄漏的 goroutine 一定出现在你写的 handler 里或其调用链中 - 如果看到几百个 goroutine 卡在这里,99% 是你 handler 里启动了 goroutine 后没等它结束就返回了,比如:
go func() { db.Query(...) }() // 忘了 <-done 或 defer cancel() - 更隐蔽的是 Kratos 的
transport.ServerOption里混入了未关闭的time.Ticker或http.Client(比如自定义RoundTripper里启了后台刷新 goroutine)
goleak.VerifyNone(t) 在 Kratos 单元测试里总漏报或误报
Kratos 测试常见干扰源比普通 Go 项目更多:
-
kratos/pkg/naming(如 etcd resolver)会启后台 watch goroutine,必须显式 ignore:goleak.IgnoreTopFunction("github.com/go-etcd/etcd/clientv3/watch.(*watchGrpcStream).serveWatchClient") -
kratos/pkg/transport/grpc.NewClient默认带重连逻辑,会启长期 goroutine;测试里应传grpc.WithBlock()+grpc.WithTimeout(100ms)避免阻塞 - 使用
t.Parallel()时,defer goleak.VerifyNone(t)必须放在TestXxx函数第一行,否则多个并行测试 goroutine 可能互相污染快照 - 如果测试里调了
app.Run()(比如集成测试),得在app.Stop()后再 verify,否则 Kratos 内部的 graceful shutdown goroutine 还在运行
Kratos 中哪些组件最容易成为协程泄漏“钉子”
Kratos 的模块化设计让泄漏点更集中,但也更难一眼识别:
-
kratos/pkg/cache/redis:如果用了redis.NewClient但没调Close(),底层连接池 goroutine 不会退出 -
kratos/pkg/conf/paladin:watcher 默认每 5 秒轮询一次配置,若测试中没调paladin.Watcher.Close(),它会一直跑 -
kratos/pkg/middleware/tracing:某些 tracing reporter(如 jaeger)启了后台 flush goroutine,需在测试 cleanup 阶段显式tracer.Close() -
kratos/pkg/transport/http.Server的ReadTimeout/WriteTimeout设为 0(即禁用)+ handler 里有阻塞 IO(如无 context 控制的http.Get),会导致 goroutine 卡死在net.Conn.Read
最麻烦的是:这些泄漏往往不体现在 heap profile 里,因为它们钉住的是 []byte、map[string]interface{} 等大对象,而 pprof heap 只显示分配点,不显示谁在持有引用——此时必须回到 /goroutine?debug=2,顺着卡住的 goroutine 往上翻调用栈,找到那个忘了传 context.WithTimeout 的地方。



















