The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
daodan1987

分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容

  •  
  •   daodan1987 · Nov 27 · 966 views

    最近把自用的 Go goroutine 池整理成了 v2.1.3:agilePool。

    起因是 IO 等待型服务:下游从 5ms 变 500ms,CPU 反而降到 10–16%,CPU HPA 不扩;队列深度又会在“队列空、任务还在跑”时误缩容。池自己按 Little's Law 算了个 workers_demand,在 capacity clamp 之前暴露;KEDA metrics-api 直接 sum/budget,不需要 Prometheus adapter 或 sidecar。

    120s、500ms 风暴实测(单节点 kind,60 req/s):

    demand:风暴 SLO 80.7%,p99 18.5s
    CPU HPA:2.7%,p99 132s
    队列深度:59.3%,p99 22s
    固定 6 副本:100%,但副本秒多 50%
    不是银弹:单节点/合成负载,连接重平衡、preStop/drain、下游限流都还得自己做。仓库:https://github.com/Yiming1997/agilePool

    daodan1987
    daodan1987
    OP
    Nov 27
    1

    欢迎各位大佬拍砖

    lesismal
    lesismal
    Nov 28
    2

    感谢分享!

    我让 claude 生成了一份对比 fib-adaptive(claude 生成的)的,修了 fib 的默认协程池在极端积压场景的一个唤醒数量太大的锁竞争消耗导致的效率下降问题,这在 fib 自己内部鼓励的用法中不算问题,但是海量 go func() { submit() } 的极端场景确实会下降,修复性能下降不大,所以就还是修了下。

    claude 生成的完整测试放到这里了:
    https://github.com/lesismal/fib-adaptive_vs_agilePool

    我本地 7800x3D 跑的报告,fib 自己的和 agilePool 的 benchmark 都包括了:
    https://github.com/lesismal/fib-adaptive_vs_agilePool/blob/main/REPORT.md

    claude 生成的代码不知道有没有问题,不同硬件、系统跑的数据可能也不一样,欢迎 OP 一块来搞搞测试和优化,看看还能不能都提升下。

    lesismal
    lesismal
    Nov 28
    3

    fib-adaptive 原版在 agilePool 的 benchmark 出现问题的是 1000 万次 go func() { submit() },这个测试本身也不太合理,应用层不会有这么大量级的并发提交并且都是 sleep/阻塞任务,如果真的并发这么大量级,那说明应用层的并发阻塞任务的数量已经超载,应该首先在应用层上游限流、队列串行化之类的解决。所以我在 benchmark 中让 claude 把这个 1000 万个的提交方式修改了、去掉了 go func()。

    daodan1987
    daodan1987
    OP
    Nov 28
    4

    @lesismal 十分感谢关注项目!我去看看对比报告。

    daodan1987
    daodan1987
    OP
    Nov 28
    5

    @lesismal 看了下报告又自测了一下,AI 给出的大致结论
    「在 5–20 ms 的 IO 密集场景、负载波动的服务里,agilePool 比固定容量池吞吐高 30–45%,且内存只随 worker 数增长(积压百万级任务也不膨胀)。代价是单任务开销更高、空闲时延迟更大——它适合"要弹性"而不是"要极限单点性能"的场景。」

    lesismal
    lesismal
    Nov 29
    6

    @daodan1987

    有没有完整点的测试代码和对比分析,我这边也跑代码+让 AI 分析看看

    固定容量池

    这个是指对比哪个 pool。
    另外,IO 跟咱们 sleep 还不太一样,IO 消耗可能更大些,所以 pool 自己的 CPU 时间也是对整体有更大影响的。可能用实际的 IO 测试看效果好些。
    fib 里面倒是对比过各个网络协议的压测,但是没有做专门的统计和分析。

    积压百万级任务

    我觉得百万级任务本身是个伪命题。

    自定制协程池而不是直接用 go func(),性能不是第一位的,平衡更重要,应该有背压机制、不应该允许无限积压,否则如果重任务对应的 obj 数量要比简单压测的 item 多的多,造成的 gc 压力会大很多。
    而且实际业务,上游应该有请求限流,下游应该也有连接池之类的本质也是限流,整个链条每个环节都不应该存在爆炸的情况,因为整个链条的吞吐取决于木桶短板。积压太多、gc 压力大、整体结果反倒更慢,不如平滑生产和消费。对于海量业务场景,也是需要扩容的。

    我确实没遇到过百万级的任务积压的场景,你有实际的场景有这种需求吗?

    比如字节的 gopool,任务队列虽然用 list、也是没有限制容量,但给 netpoll、herz 之类的用、是限制连接数的、默认只有 1w 个,所以最大也就 1w,或者即使改成更大 size,也不会这么多,因为仍然是一个链接一个协程,太多了可能 mem、gc、stw 都不友好。

    daodan1987
    daodan1987
    OP
    Nov 29
    7

    @lesismal 可以测测 v2.1.4 默认模式已经改成背压

    daodan1987
    daodan1987
    OP
    Nov 29
    8

    @lesismal
    大致 AI 测了一便,AI 的测试代码,供参考
    // Command iochain compares goroutine pools on workloads the earlier synthetic
    // benchmarks could not represent:
    //
    // - real TCP loopback IO instead of time.Sleep, so every task costs syscalls
    // and bytes copied, and the pool's own CPU competes with the work;
    // - process CPU time per task, reported from runtime/metrics, so "the pool is
    // cheap" is measured instead of assumed;
    // - a rate-limited upstream, which is how a real chain looks: the producer is
    // throttled and the question is whether the pool keeps the pipeline stable
    // rather than how deep it can let a backlog grow.
    //
    // Every pool runs the same client code, the same echo server and the same task
    // closure; only the pool differs.
    package main
    import (
    "flag"
    "fmt"
    "io"
    "net"
    "os"
    "runtime"
    "runtime/metrics"
    "sort"
    "sync"
    "sync/atomic"
    "time"
    "github.com/alitto/pond/v2"
    "github.com/panjf2000/ants/v2"
    agilepool "github.com/Yiming1997/agilePool/v2"
    fibpool "github.com/lesismal/fib/taskpool"
    )
    type pool interface {
    submit(func()) bool
    close()
    }
    type nonePool struct{}
    func (nonePool) submit(fn func()) bool { go fn(); return true }
    func (nonePool) close() {}
    type agilePool struct{ p *agilepool.Pool }
    func (a agilePool) submit(fn func()) bool {
    a.p.Submit(agilepool.TaskFunc(func() error { fn(); return nil }))
    return true
    }
    func (a agilePool) close() { a.p.Close(); a.p.Wait() }
    type antsPool struct{ p *ants.Pool }
    func (a antsPool) submit(fn func()) bool { return a.p.Submit(fn) == nil }
    func (a antsPool) close() { a.p.Release() }
    type pondPool struct{ p pond.Pool }
    func (p pondPool) submit(fn func()) bool { return p.p.Go(fn) == nil }
    func (p pondPool) close() { p.p.StopAndWait() }
    type fibPool struct{ p *fibpool.TaskPool }
    func (f fibPool) submit(fn func()) bool { f.p.Go(fn); return true }
    func (f fibPool) close() { f.p.Stop() }
    func newPool(lib string, size int, queue int) pool {
    switch lib {
    case "none":
    return nonePool{}
    case "agile":
    return agilePool{agilepool.NewPool(agilepool.NewConfig(
    agilepool.WithWorkerNumCapacity(int64(size)),
    agilepool.WithTaskQueueSize(int64(queue)),
    agilepool.WithCleanPeriod(500 * time.Millisecond),
    ))}
    case "ants":
    p, err := ants.NewPool(size)
    if err != nil {
    panic(err)
    }
    return antsPool{p}
    case "pond":
    return pondPool{pond.NewPool(size)}
    case "fib":
    return fibPool{fibpool.NewWithMode("iochain", fibpool.ModeAdaptive, size, queue)}
    }
    panic("unknown lib " + lib)
    }
    // cpuSeconds returns the process CPU time. /cpu/classes/total includes idle
    // capacity (it is roughly GOMAXPROCS x wall), so subtract it.
    func cpuSeconds() float64 {
    s := []metrics.Sample{
    {Name: "/cpu/classes/total:cpu-seconds"},
    {Name: "/cpu/classes/idle:cpu-seconds"},
    }
    metrics.Read(s)
    if s[0].Value.Kind() == metrics.KindFloat64 && s[1].Value.Kind() == metrics.KindFloat64 {
    return s[0].Value.Float64() - s[1].Value.Float64()
    }
    return 0
    }
    type hist struct {
    mu sync.Mutex
    v []float64
    }
    func (h *hist) observe(x float64) {
    h.mu.Lock()
    h.v = append(h.v, x)
    h.mu.Unlock()
    }
    func (h *hist) pct(q float64) float64 {
    h.mu.Lock()
    defer h.mu.Unlock()
    if len(h.v) == 0 {
    return 0
    }
    c := append([]float64(nil), h.v...)
    sort.Float64s(c)
    i := int(q * float64(len(c)-1))
    return c[i]
    }
    // startEchoServer runs a plain goroutine-per-connection echo server. It is the
    // same for every pool, so the CPU it consumes is common overhead; it is reported
    // separately from the pool's own cost.
    func startEchoServer(conns int) (addr string, stop func()) {
    ln, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
    panic(err)
    }
    var wg sync.WaitGroup
    go func() {
    for {
    c, err := ln.Accept()
    if tc, ok := c.(*net.TCPConn); ok {
    tc.SetNoDelay(true)
    }
    if err != nil {
    return
    }
    wg.Add(1)
    go func(c net.Conn) {
    defer wg.Done()
    defer c.Close()
    buf := make([]byte, 64)
    for {
    n, err := c.Read(buf)
    if err != nil {
    return
    }
    if _, err := c.Write(buf[:n]); err != nil {
    return
    }
    }
    }(c)
    }
    }()
    return ln.Addr().String(), func() { ln.Close(); wg.Wait() }
    }
    func dialN(addr string, n int) []net.Conn {
    conns := make([]net.Conn, 0, n)
    for i := 0; i < n; i++ {
    c, err := net.Dial("tcp", addr)
    if err != nil {
    panic(err)
    }
    if tc, ok := c.(*net.TCPConn); ok {
    tc.SetNoDelay(true)
    }
    conns = append(conns, c)
    }
    return conns
    }
    func main() {
    scenario := flag.String("scenario", "tcp", "tcp|sleep|fileio|noop")
    lib := flag.String("lib", "agile", "agile|ants|pond|fib")
    size := flag.Int("size", 256, "worker capacity")
    queue := flag.Int("queue", 1024, "handoff/queue size")
    tasks := flag.Int("tasks", 200000, "tasks to submit")
    producers := flag.Int("producers", 32, "concurrent producers")
    taskUs := flag.Int("task-us", 1000, "sleep duration for -scenario sleep")
    conns := flag.Int("conns", 256, "TCP connections (one per concurrent task)")
    fileMB := flag.Int("file-mb", 8, "fileio: size of the scratch file")
    rate := flag.Int("rate", 0, "upstream limit in tasks/s (0 = unthrottled)")
    payload := flag.Int("payload", 16, "request/response bytes for tcp")
    flag.Parse()
    runtime.GOMAXPROCS(runtime.GOMAXPROCS(0))
    var (
    addr string
    stopSrv func()
    connCh chan net.Conn
    scratch *os.File
    )
    if scenario == "fileio" {
    f, err := os.CreateTemp("", "iochain-
    .bin")
    if err != nil {
    panic(err)
    }
    scratch = f
    defer os.Remove(f.Name())
    defer f.Close()
    if err := f.Truncate(int64(*fileMB) << 20); err != nil {
    panic(err)
    }
    _ = f.Sync()
    }
    if *scenario == "tcp" {
    addr, stopSrv = startEchoServer(*conns)
    defer stopSrv()
    cs := dialN(addr, *conns)
    connCh = make(chan net.Conn, len(cs))
    for _, c := range cs {
    connCh <- c
    }
    }
    p := newPool(*lib, *size, *queue)
    defer p.close()
    var off atomic.Int64
    bufPool := sync.Pool{New: func() any { b := make([]byte, 128); return &b }}
    work := func() {
    switch *scenario {
    case "tcp":
    c := <-connCh
    buf := make([]byte, *payload)
    c.Write(buf)
    io.ReadFull(c, buf)
    connCh <- c
    case "sleep":
    time.Sleep(time.Duration(taskUs) * time.Microsecond)
    case "fileio":
    // A real pread syscall plus a copy out of the page cache: the cost
    // the pool has to compete with, without a server goroutine sharing
    // the process.
    bp := bufPool.Get().(
    []byte)
    if _, err := scratch.ReadAt(*bp, off.Add(64)%int64(*fileMB<<20)); err != nil {
    panic(err)
    }
    bufPool.Put(bp)
    }
    }
    var submitted, completed, rejected int64
    var inFlight, peakInFlight int64
    cpu0 := cpuSeconds()
    start := time.Now()
    var wg sync.WaitGroup
    if *rate > 0 {
    // Rate-limited upstream: the producer is throttled and never runs ahead.
    interval := time.Second / time.Duration(*rate)
    deadline := start.Add(time.Duration(int64(*tasks)/int64(*rate)+1) * time.Second)
    tk := time.NewTicker(interval)
    defer tk.Stop()
    wg.Add(1)
    go func() {
    defer wg.Done()
    for i := 0; i < *tasks; i++ {
    <-tk.C
    if time.Now().After(deadline) {
    return
    }
    atomic.AddInt64(&submitted, 1)
    cur := atomic.AddInt64(&inFlight, 1)
    for {
    peak := atomic.LoadInt64(&peakInFlight)
    if cur <= peak || atomic.CompareAndSwapInt64(&peakInFlight, peak, cur) {
    break
    }
    }
    ok := p.submit(func() {
    work()
    atomic.AddInt64(&inFlight, -1)
    atomic.AddInt64(&completed, 1)
    })
    if !ok {
    atomic.AddInt64(&inFlight, -1)
    atomic.AddInt64(&rejected, 1)
    }
    }
    }()
    } else {
    per := *tasks / *producers
    for k := 0; k < *producers; k++ {
    wg.Add(1)
    go func() {
    defer wg.Done()
    for i := 0; i < per; i++ {
    atomic.AddInt64(&submitted, 1)
    cur := atomic.AddInt64(&inFlight, 1)
    for {
    peak := atomic.LoadInt64(&peakInFlight)
    if cur <= peak || atomic.CompareAndSwapInt64(&peakInFlight, peak, cur) {
    break
    }
    }
    ok := p.submit(func() {
    work()
    atomic.AddInt64(&inFlight, -1)
    atomic.AddInt64(&completed, 1)
    })
    if !ok {
    atomic.AddInt64(&inFlight, -1)
    atomic.AddInt64(&rejected, 1)
    }
    }
    }()
    }
    }
    wg.Wait()
    for atomic.LoadInt64(&inFlight) > 0 {
    time.Sleep(time.Millisecond)
    }
    elapsed := time.Since(start)
    cpu := cpuSeconds() - cpu0
    var ms runtime.MemStats
    runtime.ReadMemStats(&ms)
    fmt.Printf("%s/%s size=%d queue=%d conns=%d tasks=%d rate=%d\n",
    *scenario, *lib, *size, *queue, *conns, *tasks, rate)
    done := atomic.LoadInt64(&completed)
    fmt.Printf(" wall=%8.0fms completed=%d throughput=%9.0f tasks/s per-task=%8.2fus\n",
    float64(elapsed.Microseconds())/1000, done, float64(done)/elapsed.Seconds(),
    float64(elapsed.Microseconds())/float64(done))
    fmt.Printf(" cpu=%6.2fs cpu/task=%7.0fns (%.1f%% of one core at this rate)\n",
    cpu, cpu
    1e9/float64(atomic.LoadInt64(&completed)), cpu/elapsed.Seconds()*100)
    fmt.Printf(" peakInFlight=%d rejected=%d\n", atomic.LoadInt64(&peakInFlight), atomic.LoadInt64(&rejected))
    fmt.Printf(" heap peak~%dMB end=%dMB gc=%d\n", ms.HeapSys/(1<<20), ms.HeapAlloc/(1<<20), ms.NumGC)
    if *scenario == "tcp" {
    fmt.Fprintf(os.Stderr, "echo server on %s\n", addr)
    }
    }

    lesismal
    lesismal
    Nov 29
    9

    @daodan1987

    让 claude 分析了下,可以这里来聊:
    https://github.com/lesismal/fib-adaptive_vs_agilePool/issues/1

    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1716 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 00:06 · PVG 08:06 · LAX 16:06 · JFK 19:06
    ♥ Do have faith in what you're doing.