Learning center

Why does RSS stay high after a service frees its large buffers, and what do glibc's tunables change?

After a program frees a large block, glibc raises its mmap threshold to that size, so later blocks of similar size come from arenas that keep their memory. A service that reads multi-megabyte bodies on several threads therefore climbs to the high point of its largest burst and stays there. Setting glibc.malloc.mmap_threshold fixes the threshold and turns that adjustment off, and glibc.malloc.arena_max caps how many arenas can each hold freed memory.

This guide assumes the growth is already known to be allocator retention, not live native memory or page cache; Memory keeps growing, and the heap profile stays flat shows how to tell those apart.

Two places a block can come from#

glibc's malloc serves a request from one of two places. A small request comes from an arena, a heap that glibc grows and reuses. When no suitable free arena block is available, a request at or above the mmap threshold can get its own anonymous mapping, which free unmaps. Freed arena blocks can stay resident, especially when live allocations prevent trimming.

The threshold starts at 128 KiB, and it moves. mallopt(3) describes the rule: when a program frees an mmapped block larger than the current threshold, up to 32 MiB on 64-bit systems, glibc raises the threshold to that block's size. For a service whose large buffers come in bursts, the first burst can use mappings while later requests of a similar size can come from arenas.

Arenas multiply the effect. To reduce lock contention, glibc gives threads their own arenas, up to a limit derived from the core count. Each arena keeps its own freed memory, so a burst spread over many threads leaves a retained high point in each of them.

The tunables#

glibc reads its malloc settings from the GLIBC_TUNABLES environment variable at process start, with no code change. The memory allocation tunables that matter here are two:

  • glibc.malloc.mmap_threshold sets the threshold in bytes. If the tunable is set, the manual says, dynamic adjustment is disabled and the value is static. It keeps new allocations of that size eligible for a separate mapping when no suitable free block is available.
  • glibc.malloc.arena_max sets the number of arenas regardless of the core count. Fewer arenas means fewer places to retain memory and more contention between threads.

The loader prints what a process will run with. In a rust:1 container, with and without the variable:

docker run --rm -e GLIBC_TUNABLES=glibc.malloc.arena_max=2:glibc.malloc.mmap_threshold=131072 \
  rust:1 sh -c '/lib64/ld-linux-x86-64.so.2 --list-tunables | grep -E "malloc.(arena_max|mmap_threshold)"'
glibc.malloc.arena_max: 0x2 (min: 0x1, max: 0xffffffffffffffff)
glibc.malloc.mmap_threshold: 0x20000 (min: 0x0, max: 0xffffffffffffffff)

Without the variable both read 0x0, which means the defaults: arenas from the core count and a dynamic threshold.

The lab#

The program reproduces one pattern: a request collects a body of 2.6 to 33 MB from 16 KiB chunks, copies it once, holds both for 150 ms and frees them. It runs waves of 4 to 16 concurrent requests on threads and prints resident memory after each wave, when every buffer is free. It uses only the standard library.

use std::{fs, thread, time::Duration};

const MIB: usize = 1 << 20;

fn rss_mib() -> usize {
    let status = fs::read_to_string("/proc/self/status").unwrap();
    let line = status.lines().find(|l| l.starts_with("VmRSS:")).unwrap();
    line.split_whitespace().nth(1).unwrap().parse::<usize>().unwrap() / 1024
}

// One request: collect a body from 16 KiB chunks, copy it once, hold it, free both.
fn read_body(size: usize) {
    let chunk = [7u8; 16 * 1024];
    let mut collected = Vec::new();
    while collected.len() < size {
        collected.extend_from_slice(&chunk);
    }
    let copy = collected.to_vec();
    thread::sleep(Duration::from_millis(150));
    drop((collected, copy));
}

fn main() {
    let mut seed: u64 = 42;
    println!("start: {} MiB", rss_mib());
    for (n, readers) in [4, 8, 8, 12, 16, 8, 4].into_iter().enumerate() {
        let handles: Vec<_> = (0..readers)
            .map(|_| {
                seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
                let size = 2_600_000 + (seed >> 33) as usize % (33 * MIB - 2_600_000);
                thread::spawn(move || read_body(size))
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        println!("wave {} ({readers:2} readers): {} MiB", n + 1, rss_mib());
    }
    thread::sleep(Duration::from_secs(5));
    println!("idle 5 s: {} MiB", rss_mib());
}

Put it in src/main.rs of a new Cargo project named arena and run it four ways:

docker run --rm -v "$PWD":/lab -w /lab rust:1 sh -c 'cargo build -q --release
  for t in "" glibc.malloc.arena_max=2 glibc.malloc.mmap_threshold=131072 \
           glibc.malloc.arena_max=2:glibc.malloc.mmap_threshold=131072; do
    echo "== $t"; GLIBC_TUNABLES=$t ./target/release/arena; done'

On glibc 2.41 with 8 cores, the defaults and the arena cap printed:

== (defaults)                         == glibc.malloc.arena_max=2
start: 2 MiB                          start: 1 MiB
wave 1 ( 4 readers): 2 MiB            wave 1 ( 4 readers): 2 MiB
wave 2 ( 8 readers): 148 MiB          wave 2 ( 8 readers): 61 MiB
wave 3 ( 8 readers): 216 MiB          wave 3 ( 8 readers): 2 MiB
wave 4 (12 readers): 304 MiB          wave 4 (12 readers): 69 MiB
wave 5 (16 readers): 434 MiB          wave 5 (16 readers): 186 MiB
wave 6 ( 8 readers): 445 MiB          wave 6 ( 8 readers): 64 MiB
wave 7 ( 4 readers): 448 MiB          wave 7 ( 4 readers): 66 MiB
idle 5 s: 448 MiB                     idle 5 s: 66 MiB

With the threshold fixed at 131,072 bytes, no wave left more than 4 MiB. With both settings, every line read 2 MiB.

The first wave is the dynamic threshold at work. Its buffers were above 128 KiB, so they were mmapped and returned, and resident memory stayed at 2 MiB. Freeing them raised the threshold, so from the second wave the same sizes came from arenas and stayed: 448 MiB held by a process with nothing allocated. Capping arenas at two keeps less, and some of it comes back when a wave frees the top of an arena. Fixing the threshold returns every large buffer.

In this lab the threshold alone was enough. It may not be in a real service: in the production replay below, run under a two-worker async runtime, the threshold alone left 195 MiB, and only the two settings together brought it down. Measure your own pattern before you choose one setting.

What it costs#

A low fixed threshold can increase the number of large allocations served by mmap and freed by munmap. mallopt(3) lists the cost: the kernel zeroes each new mapping, and freed blocks are not reused. That cost is small for request-sized buffers of megabytes and large for a hot loop that reuses one 200 KiB block. Fewer arenas means more lock contention among threads that allocate at the same time.

The better fix, where you can make it, is not to hold the whole body at all. Streaming a body through a fixed buffer bounds memory by the buffer, not by the largest request. The tunables then cover the large allocations you cannot stream.

The tunables apply only to glibc's malloc. A binary linked against musl, or one that installs jemalloc or mimalloc as its global allocator, ignores them. Pure Go does not use malloc, but cgo code does.

The production case#

In the production case behind this guide, a Rust web service served stored archive parts by collecting each one into a buffer and then copying it, two buffers of up to 33 MiB per read; real parts were 2.6 to 13.7 MB. Each new revision started at 20 to 30% of its 1 GiB limit and rested wherever its first burst left it. One revision held at 40% for two hours, then served 72 parts, 236 MB, in ten minutes and rose to 83%. It stayed there until the platform stopped it with Memory limit of 1024 MiB exceeded with 1112 MiB used.

A replay of that pattern measured 447 MiB retained under glibc's defaults, 195 MiB with the threshold alone, 117 MiB with jemalloc, 274 MiB with mimalloc and 27 MiB with arena_max=2 and a 131,072-byte threshold together. The fix streams the parts and sets the two tunables for the large buffers left, such as webhook bodies of up to 3.1 MB. If the container kills persist after a fix like this, look at in-flight requests next: Containers killed for memory after a deploy.

Where this came from#

Proofline found this in its own web service and shipped the streaming and the tunables in its production release of 25 November 2026. The figures in The production case are that service's memory readings and the replay's results before the change. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

What does MALLOC_ARENA_MAX do?

It caps the number of glibc malloc arenas, the same as glibc.malloc.arena_max in GLIBC_TUNABLES. By default glibc creates arenas up to a limit derived from the core count, and each can keep freed memory.

Why did the first burst return memory and the later ones not?

glibc raises its mmap threshold when a program frees an mmapped block above it, up to 32 MiB on 64-bit systems. Later blocks of similar size may come from arenas, which can retain freed memory. Setting glibc.malloc.mmap_threshold disables that adjustment.

Does GLIBC_TUNABLES work with musl or jemalloc?

No. Only glibc reads it. A musl binary, or a program that installs jemalloc or mimalloc as its global allocator, takes that allocator's own settings.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading