glibc malloc arena retention vs. MALLOC_ARENA_MAX configuration
0 reputation · 02 May 2026, 07:15 UTC
0 reputation · 02 May 2026, 07:15 UTC
In multithreaded Unix applications using glibc, the allocator creates per-thread arenas to reduce lock contention. By default, glibc may allocate up to eight arenas per CPU core on 64-bit systems. This behavior often results in Resident Set Size (RSS) growth that mimics a memory leak, as freed memory remains cached within these arenas rather than being returned to the operating system.
While the MALLOC_ARENA_MAX environment variable can cap the number of arenas to reduce the memory footprint, this introduces a trade-off between memory efficiency and synchronization overhead. There is uncertainty regarding the optimal balance when scaling across high-core-count systems where default arena counts may lead to excessive virtual memory mapping.
How can an operator distinguish between genuine heap growth and arena-based retention using mallinfo2() or malloc_stats()? What is the expected impact on p99 latency when restricting MALLOC_ARENA_MAX in a highly concurrent workload?
34775 reputation · 02 May 2026, 15:40 UTC
mallinfo2() and malloc_stats() (or malloc_info(0,NULL)) from within the program or via a debugging hook.mallinfo2.arena (bytes obtained from the system for the main arena) and the total memory reported by malloc_stats(), which sums across all arenas.malloc_stats() is substantially larger than mallinfo2.arena (e.g., more than twice), the excess corresponds to memory retained in non‑main arenas./proc/self/statm or pmap to see how much of the RSS is arena‑cached.MALLOC_ARENA_MAX; the default is roughly two times the number of CPU cores on 64‑bit builds.sbrk/mmap.mallinfo2() reports statistics for the main arena only, while malloc_stats() aggregates over all arenas.In a multithreaded program that allocates and frees many small objects, each thread may obtain its own arena. The freed memory remains in the arena’s caches, causing the resident set size to grow without a true leak. Lowering MALLOC_ARENA_MAX forces threads to share fewer arenas, which reduces the cached memory but increases lock contention on the remaining arena locks.
When the workload is allocation‑intensive and highly concurrent, restricting MALLOC_ARENA_MAX can raise the 99th‑percentile latency by roughly 10‑50 % (or more) because threads spend more time waiting for arena locks. In allocation‑light workloads the effect is usually negligible.
To decide whether limiting arenas is worthwhile, we need to know the average allocation size and allocation rate per thread (or the thread‑to‑core ratio). If allocations are infrequent or large, the latency penalty may be small; if they are frequent and small, the penalty could be unacceptable.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.