当并行线程数超过 cpu 核数时的性能拐点观测

解读

在国内金融、电商、运营商等核心系统中,MariaDB 常被部署在 64C/128C 的裸金属或 32C 的云主机上,并发线程数动辄被业务框架(Spring、Dubbo、Go 微服务)抬到 200+。面试官问“拐点”,不是让你背公式,而是想看你是否:

  1. 亲手在 非统一内存访问(NUMA) 架构上跑过 sysbench / tpcc-mysql 压测;
  2. 能否用 perf + flame graph 定位到 MariaDB 特有的 lock_thread_count 热点;
  3. 是否知道 thread_pool_size、innodb_read_io_threads、innodb_write_io_threads 与 CPU 核数 的量化关系;
  4. 能否给出 可落地的线上阈值公式,并解释为什么云原生场景下拐点会提前。

知识点

  1. CPU 核数 ≠ 硬件线程数:Intel 超线程在数据库场景常关,国产鲲鹏 920 32C 物理核关闭超线程后就是 32 并发度。
  2. MariaDB 线程模型:
    • one-thread-per-connection 模型:线程数 > 核数后,context-switch 开销陡增,%sys 从 3% 涨到 25%+;
    • thread pool(groups = cpu_cores):把 SQL 分阶段放入 worker 队列,epoll 复用,拐点后移;
  3. InnoDB 内部并发:
    • srv_n_read_io_threads + srv_n_write_io_threads 默认 4,超过 8 后 fil_system->mutex 成为瓶颈;
    • buf_flush_page_cleaner 线程在 dirty page > 75% 时触发,核数不足会 sleep 在 buf_flush_event;
  4. Linux 调度器:CFS 在 cfs_rq->load > 0.7 * cpu_cores 时开始 throttle,调度延迟 从 30 µs 涨到 800 µs;
  5. NUMA 陷阱:跨 Node 内存访问延迟 从 90 ns 升到 350 ns,innodb_numa_interleave 打开后拐点右移 15%;
  6. 观测指标:
    • 上下文切换率 > 80 k/s;
    • run-queue > 1.5 × cpu_cores;
    • perf top 中 mutex_spin > 18%;
    • MariaDB 10.6 的 performance_schema.thread_pool_waits 出现 thread_pool_stall 事件。

答案

“我在 32C 的鲲鹏 920 上做过 sysbench oltp_read_write 200 并发 的梯度压测,把 thread_pool_size 从 4 调到 32,记录 QPS 与 95th latency。

  1. 拐点定义:当 并发线程数 = cpu_cores × 1.6 时,QPS 从 24 万降到 21 万,下降 12%,同时 context-switch 从 42 k/s 涨到 95 k/s,%sys 从 4% 涨到 22%,判定为拐点。
  2. 根因:
    • one-thread-per-connection 模型下,pthread_mutex 在 lock_thread_count 热点占比 28%,sched_yield 被频繁调用;
    • InnoDB 的 buf_pool->LRU_list_mutex 在 200 线程时 spin 次数翻倍;
  3. 优化:
    • 开启 thread_pool,thread_pool_size = cpu_cores,thread_pool_stall_limit = 500 ms,拐点推迟到 cpu_cores × 2.4;
    • 把 innodb_read_io_threads 降到 8,innodb_write_io_threads 降到 8,减少 fil_system->mutex 竞争;
    • numactl –interleave=all 绑定,跨 Node 内存下降 40%,拐点再右移 10%;
  4. 线上阈值:最终给业务方的公式是 max_connections = cpu_cores × 2 + 10,超过后强制走 只读副本 或 MaxScale 分流,保证主库 95th latency < 30 ms。”

拓展思考

  1. 云主机 vCPU 被 超卖 时,steal time 3% 即可让拐点提前到 cpu_cores × 1.2,此时 thread_pool_size 应下调到 cpu_cores × 0.8;
  2. Kubernetes 场景下,cgroups cpu.max 限制为 16C,但 Pod 内 GOMAXPROCS 误配成 64,MariaDB 侧 thread_pool_size 仍按宿主机 64C 设置,导致 throttle 严重,需用 automaxprocs 动态感知;
  3. ARM vs x86:鲲鹏 920 的 L3 cache 32 MB 共享,mutex 热点比 Intel 8280 低 18%,拐点可再右移 0.3 倍;
  4. MyRocks 引擎:由于 skip unique check 和 block cache 无 buf_pool mutex,拐点可推迟到 cpu_cores × 3,但 compaction 线程需单独 cpu_set 绑定,防止 noise neighbor;
  5. 金融两地三中心:在 Galera 多主 模式下,gcs_max_throttle 默认 0.2,当 apply slave threads > cpu_cores 时,flow control 触发,writeset 堆积,拐点 表现为 cluster-wide pause,需把 wsrep_slave_threads 设为 cpu_cores / 2,与 thread_pool_size 联动调优。