Skip to content

内存占用高:glibc 的 80 个 arena 不归还,建议换 mimalloc 并支持限制 worker 线程数 #392

Closed

Description

@sunnysab

一台 80 核服务器上 twcore 0.88.0,几乎没流量(30 分钟日志只有 gate 版本不一致的报错),RSS 645 M;journalctl 里上一个实例跑了 15.5 小时,peak 2.9 G。查下来是分配器 + 线程数,不是业务泄漏:

  • ldd /usr/bin/twcore 只链了 libc,没有 jemalloc/mimalloc → glibc malloc 2.44。
  • 91 个线程,其中 80 个 tokio-rt-worker(nproc = 80,tokio 默认按 CPU 数开)。
  • gdb attach 调 malloc_stats()(不重启):
arenas = 80
system bytes = 687 MB   ← 向内核要的
in use bytes = 151 MB   ← 真正在用的

即 ~536 M 是各 arena 空闲链表里留着的已释放内存。单个 arena 例如 Arena 41: system 63.7 M / in use 17 M;pmap 里一排 64 M 对齐的 anon 段就是这些 heap。

  • 再调一次 malloc_trim(0),RSS 645 M → 381 M,代码一行没动。

两个建议

1. 换分配器:#[global_allocator] 挂 mimalloc(一个 crate,Windows/Linux 都能编,无 autotools 依赖);jemalloc 碎片回收也不错,但 tikv-jemallocator 在 Windows 上要额外工具链。mimalloc 会主动把空闲页还给 OS,80 个线程的 arena 碎片问题基本消失。

2. 支持限制线程数:默认 worker_threads = nproc 在小机器上没问题,在 80 核上等于 80 个线程各绑一个 arena,RSS 只涨不降。希望有个配置项(或 THINKWATCH_THREADS 环境变量)能压低 worker 数,比如:

runtime:
  threads: 8

不写还是 CPU 数,行为不变。顺带可以让 max_blocking_threads 也跟着收敛,现在默认 512。

改完的预期:空闲基线从 ~380 M 继续降到接近 in-use 的量级,长时间跑不再线性上涨。

需要的话我可以直接开 PR(含 systemd 部署里 MALLOC_ARENA_MAX 的临时解法)。@fylorn

Activity

  1. sunnysab commented on Nov 3, 2026

    @sunnysab
    ContributorAuthor

    @fylorn 佬,您好,建议换一个内存分配器。我在服务器上跑 twcore,内存占用好几GB,占用太大了。默认的 glibc 在linux服务器场景不太好用

  2. added
    bug
    on Nov 3, 2026
  3. fylorn commented on Nov 3, 2026

    @fylorn
    Contributor

    I will fix this issue shortly. In the meantime, before the release, you can set the following environment variables: TOKIO_WORKER_THREADS=8
    MALLOC_ARENA_MAX=4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions