Go 并发模式与 pprof 性能调优
MrSmy Lv5

写了几年 Go,发现性能问题基本集中在两类:并发组织不当(该限流的没限、该取消的没取消)和内存分配过多(GC 压力大)。前者用模式解决,后者用 pprof 定位。这篇是两个方向的实战记录。

并发模式:worker pool

最简单的需求:处理 10 万条任务,每条要调一次外部接口。

1
2
3
4
// 错误示范:无限制开 goroutine
for _, task := range tasks {
go process(task) // 10 万个 goroutine 同时打下游
}

下游会被打挂,本机也会因为调度和内存出问题。正确做法是固定 workers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func workerPool(tasks []Task, workers int) {
jobs := make(chan Task)
var wg sync.WaitGroup

// 启动固定数量的 worker
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for task := range jobs {
process(task)
}
}()
}

// 投递任务
for _, t := range tasks {
jobs <- t
}
close(jobs) // 关闭后 worker 的 range 退出

wg.Wait()
}

要点:

  • jobs 无缓冲,投递方会被反压(这是好事,避免任务堆积在内存里)
  • close(jobs) 由投递方负责
  • wg.Wait() 等所有 worker 收尾

如果任务可能失败、需要提前中止,用 errgroup + SetLimit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(20)

for _, t := range tasks {
t := t
g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
return process(ctx, t)
})
}

if err := g.Wait(); err != nil {
log.Printf("处理中断: %v", err)
}

SetLimit 是最省事的方式。自己实现信号量版本容易漏 <-sem,导致死锁。

并发模式:批量聚合

高频小请求打到数据库会很难受。常见解法是”攒一批再写”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type Batcher struct {
mu sync.Mutex
buf []Item
maxSize int
flush func([]Item) error
}

func (b *Batcher) Add(ctx context.Context, item Item) error {
b.mu.Lock()
b.buf = append(b.buf, item)
needFlush := len(b.buf) >= b.maxSize
var batch []Item
if needFlush {
batch = b.buf
b.buf = nil
}
b.mu.Unlock()

if needFlush {
return b.flush(batch)
}
return nil
}

生产版本还要加”定时 flush”(避免最后一批永远攒不满)和”flush 失败重试”。这个模式的坑在于错误传播:一批里有一条失败,调用方怎么知道是自己的那条错了?通常是整批重试或者记录死信。

限流:别让重试打垮下游

golang.org/x/time/rate 是最常用的:

1
2
3
4
5
6
7
8
limiter := rate.NewLimiter(rate.Limit(100), 200)   // 100 QPS,突发 200

func handle(ctx context.Context) error {
if err := limiter.Wait(ctx); err != nil {
return err // ctx 超时会返回错误
}
return callDownstream(ctx)
}

Wait 会阻塞直到拿到令牌,Allow 是非阻塞的判断。对外部接口调用,用 Wait 更简单;对”宁可拒绝也别排队”的场景,用 Allow 直接返回 429。

重试必须配限流和退避。见过一个事故:下游超时 → 客户端重试 3 次 → 每个重试又被上游重试 3 次 → 放大 9 倍流量 → 下游彻底挂掉。

1
2
3
4
5
6
7
8
9
backoff := time.Second
for i := 0; i < 3; i++ {
if err := call(ctx); err == nil {
return nil
}
jitter := time.Duration(rand.Int63n(int64(backoff / 2)))
time.Sleep(backoff + jitter) // 加抖动,避免同时重试
backoff *= 2
}

pprof:定位真正的问题

先开 profile 端点:

1
2
3
4
5
import _ "net/http/pprof"

go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()

注意只监听 localhost 或者加鉴权。这个端口暴露了内存、goroutine 等内部信息。

常用命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# CPU(采样 30 秒)
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

# 堆内存(当前存活对象)
go tool pprof http://localhost:6060/debug/pprof/heap

# goroutine(查泄漏)
go tool pprof http://localhost:6060/debug/pprof/goroutine

# 阻塞(查锁等待)
go tool pprof http://localhost:6060/debug/pprof/block

# 互斥锁竞争
go tool pprof http://localhost:6060/debug/pprof/mutex

进入交互界面后:

1
2
3
(pprof) top10            # 前 10 个热点
(pprof) list FuncName # 逐行看耗时
(pprof) web # 生成火焰图(需要 graphviz)

list 是最有用的。top 只能告诉你是哪个函数,list 能告诉你是哪一行。

案例一:JSON 序列化占 40% CPU

一个接口 QPS 上来后 CPU 打满。top 显示:

1
2
flat  flat%   sum%        cum   cum%
38% 38% 38% 42.1% encoding/json.Marshal

list 定位到具体是某个 map[string]interface{} 的序列化。原因是这个接口返回的是动态结构,全部用 map[string]interface{} 拼装。

改法:

  1. 用定义好的 struct 替代 map(JSON 反射路径更快、分配更少)
  2. 对大响应开启 json.Encoder 直接写 ResponseWriter,避免先 Marshal 成 []byte 再写
1
2
3
4
func respond(w http.ResponseWriter, v any) error {
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(v) // 少一次大内存分配
}

优化后 CPU 降到 22%,P99 从 380ms 降到 140ms。

案例二:GC 频繁

go tool pprof 看 heap:

1
2
3
(pprof) top -cum
1.2GB userCache
800MB encoding/json.(*decodeState).literalStore

问题是有个本地缓存 map 无限增长(没有淘汰),以及高频 JSON 解析产生大量临时对象。

逃逸分析能帮上忙:

1
go build -gcflags="-m" ./... 2>&1 | grep "escapes to heap"

被标记 moved to heap 的变量会产生堆分配。常见原因:

  • 返回局部变量的指针
  • 把变量塞进 interface{}
  • 闭包捕获
  • 切片超过栈容量

两个改善手段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1. sync.Pool 复用小对象
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}

func handle() {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)
// 使用 buf
}

// 2. 预分配切片容量
results := make([]Item, 0, len(input)) // 避免多次扩容

sync.Pool 适合”生命周期短、创建成本高、可以丢弃”的对象。注意它在 GC 时会被清空,不能当缓存用。

案例三:goroutine 泄漏

监控显示 goroutine 数量从 200 稳步涨到 8000。

1
2
3
4
go tool pprof http://localhost:6060/debug/pprof/goroutine
(pprof) top
7200 runtime.gopark
7100 chan receive

7000 多个 goroutine 卡在 channel 接收上。定位到一段代码:

1
2
3
4
5
6
7
func watch(ch chan Event) {
go func() {
for e := range ch { // ch 永远不会被关闭
handle(e)
}
}()
}

watch 每次被调用都新开一个 goroutine,但 ch 从不关闭,goroutine 永远不退出。修法是让调用方负责关闭,或者用 ctx.Done() 退出:

1
2
3
4
5
6
7
8
9
10
11
12
13
go func() {
for {
select {
case <-ctx.Done():
return
case e, ok := <-ch:
if !ok {
return
}
handle(e)
}
}
}()

改完后 goroutine 数稳定在 200 左右。

一个性能检查清单

上线前值得过一遍:

检查项 怎么看
HTTP 超时设置了吗 ReadTimeout / WriteTimeout / 客户端 Timeout
有 goroutine 上限吗 worker pool / SetLimit
数据库查询有 context 吗 QueryContext 而非 Query
大响应是流式的吗 json.Encoder 直写
缓存有淘汰策略吗 LRU / TTL,别用裸 map
-race 跑过测试吗 go test -race ./...
benchmark 有基线吗 go test -bench 纳入 CI
容器里 GOMAXPROCS 对吗 Go 1.25 前需要手动设 GOMAXPROCS

最后一条是个经典问题:Go 1.25 之前 GOMAXPROCS 取的是宿主机的 CPU 数,不是容器的 limit。在 4 核 limit 的容器里看到 64 核心,会启动 64 个 P,导致频繁的线程调度和 CPU throttling。Go 1.25 加了容器感知,自动处理了。

小结

Go 的性能调优有两个特点:指标清晰(pprof 直接给出热点行)和手段有限(复用、减少分配、控制并发)。不像是算法优化需要灵感,这里的改进基本都是”把不该做的事去掉”——不该开的 goroutine、不该分配的对象、不该重复的序列化。所以优化的顺序永远是:先量(pprof),再改一处,再量。凭感觉改代码通常会让情况更糟。

  • 本文标题:Go 并发模式与 pprof 性能调优
  • 本文作者:MrSmy
  • 创建时间:2024-06-02 20:35:00
  • 本文链接:https://fengyang.live/2024/06/02/Go并发模式与pprof性能调优/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!