---
title: "Memory keeps growing, and the heap profile stays flat. What holds it? | Proofline"
description: "A heap profile misses native memory from C libraries, memory the allocator kept after a free, and page cache that a container's memory figure counts."
url: https://proofline.sh/learn/rss-grows-heap-flat/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Memory keeps growing, and the heap profile stays flat. What holds it?

A heap profile misses native memory from C libraries, memory the allocator kept after a free, and page cache that a container's memory figure counts. Read the process's RssAnon and RssFile and the cgroup's anon and file counters beside the heap size. Page cache moves only the cgroup's file, native memory moves RssAnon while the heap stays flat, and an allocator that keeps freed memory shows the heap falling while RssAnon holds still.

Capacity overruns The Proofline team November 24, 2026 8 min read

## The symptom and the explanations

The example is fictional. A Python service, `pdf-render`, shipped `v2.14` at 08:00 UTC with a newer PDF library. By 14:00 its container's memory figure had climbed from 600 MiB to 1.7 GiB, with the limit at 2 GiB. A `tracemalloc` snapshot taken at 14:05 showed about 180 MiB of Python allocations, the same as at 09:00. Three explanations fit:

-   A C library holds native memory. The PDF library is a C extension. Its buffers come from `malloc` and never pass through Python's allocator, so a profiler of Python objects cannot see them.
-   The allocator keeps freed memory. The service renders large documents in bursts. Python's allocator serves objects of up to 512 bytes from memory mappings called arenas, 1 MiB each on 64-bit platforms, and an arena with any live object in it stays mapped. [Python memory management](https://docs.python.org/3/c-api/memory.html) glibc's `malloc` can trim its main heap only from the top, and the more arenas it keeps to reduce contention between threads, the more memory it uses. [mallopt(3)](https://man7.org/linux/man-pages/man3/mallopt.3.html)
-   Page cache counts as memory. `v2.14` writes each rendered PDF to local disk before uploading it. The kernel caches those file pages, and the cgroup memory controller counts page cache along with anonymous memory. [cgroup v2 memory](https://docs.kernel.org/admin-guide/cgroup-v2.html)

The container's memory figure rises under all three, and the heap profile is flat under all three. If memory instead climbs in the heap profile too, or follows requests in flight, the question is a different one. [Containers killed for memory after a deploy](/learn/container-memory-kills-after-deploy/)

## What each explanation predicts

| Observation | Native memory | Allocator keeps freed memory | Page cache |
| --- | --- | --- | --- |
| Container memory figure | rises | rises | rises |
| Language heap (`tracemalloc`, heap profile) | flat | flat, or falls after a burst | flat |
| `RssAnon` in `/proc/PID/status` | rises | stays at its high point | flat |
| cgroup `anon` | rises | stays at its high point | flat |
| cgroup `file` | flat | flat | rises |
| Shape of the growth | steady, with use of the library | steps at bursts, then flat | with files written or read |

The cgroup's `file` counter separates page cache from the other two in one read. Between native memory and allocator retention, the shape decides: a burst that pushes `RssAnon` up a step that never comes down, while the heap returned to its baseline, is retention; steady growth with the heap flat is native. The heap profile everyone opened first predicts the same flat line for all three.

The kernel documents `anon` as memory in anonymous mappings such as `brk()` and `mmap(MAP_ANONYMOUS)`, and `file` as memory used to cache filesystem data, including tmpfs and shared memory. [cgroup v2 memory.stat](https://docs.kernel.org/admin-guide/cgroup-v2.html) `RssAnon` and `RssFile` split a process's resident memory the same way. [proc\_pid\_status(5)](https://man7.org/linux/man-pages/man5/proc_pid_status.5.html)

## The lab: four worlds, one heap profile

The script allocates about 200 MiB in one of four ways and prints the Python heap as `tracemalloc` sees it, the process's `RssAnon` and `RssFile`, and its cgroup's anonymous and file memory. Run it in a container so that the cgroup counters belong to it alone. Save it as `rss.py`.

```
import ctypes, os, sys, tracemalloc

MiB = 1 << 20
if len(sys.argv) < 2 or sys.argv[1] not in ("python", "native", "fragmented", "pagecache"):
    sys.exit("usage: python3 rss.py python|native|fragmented|pagecache")
world = sys.argv[1]   # python, native, fragmented or pagecache

def status(key):
    with open("/proc/self/status") as f:
        return int(next(l.split()[1] for l in f if l.startswith(key + ":"))) // 1024

def cgroup():
    # cgroup v2 names the counters anon and file; v1 calls them rss and cache
    for path, anon, file in (("/sys/fs/cgroup/memory.stat", "anon", "file"),
                             ("/sys/fs/cgroup/memory/memory.stat", "rss", "cache")):
        if os.path.exists(path):
            stat = dict(l.split() for l in open(path))
            return int(stat[anon]) // MiB, int(stat[file]) // MiB

def report(label):
    anon, file = cgroup()
    print(f"{label:>7}: tracemalloc {tracemalloc.get_traced_memory()[0] // MiB:4d} MiB | "
          f"RssAnon {status('RssAnon'):4d} | RssFile {status('RssFile'):3d} | "
          f"cgroup anon {anon:4d} | cgroup file {file:4d}")

tracemalloc.start()
report("before")
if world == "python":
    keep = [bytearray(MiB) for _ in range(200)]            # Python objects
elif world == "native":
    libc = ctypes.CDLL(None)
    libc.malloc.restype = ctypes.c_void_p
    for _ in range(200):                                    # a C library's buffers
        p = libc.malloc(MiB)
        ctypes.memset(p, 1, MiB)
elif world == "fragmented":
    objs = [i.to_bytes(8, "little") * 56 for i in range(450_000)]  # 481-byte objects
    report("filled")
    del objs[::2]                                           # free every other one
elif world == "pagecache":
    with open("/tmp/data.bin", "wb") as f:                  # write, then read, a file
        for _ in range(200):
            f.write(os.urandom(MiB))
    with open("/tmp/data.bin", "rb") as f:
        while f.read(MiB):
            pass
report("after")
```

```
for w in python native fragmented pagecache; do
  docker run --rm -v "$PWD":/lab:ro python:3.12-slim python3 /lab/rss.py "$w"
done
```

Write the prediction down first. `python` moves the heap and `RssAnon` together; `native` moves `RssAnon` and cgroup `anon` with the heap at zero; `fragmented` halves the heap and leaves `RssAnon` where it was; `pagecache` moves only cgroup `file`. Python 3.12.16 printed, on a Docker host with cgroup v1, where the script reads `rss` and `cache` in place of `anon` and `file`:

```
 before: tracemalloc    0 MiB | RssAnon    9 | RssFile   6 | cgroup anon    9 | cgroup file    0
  after: tracemalloc  200 MiB | RssAnon  209 | RssFile   6 | cgroup anon  209 | cgroup file    0

 before: tracemalloc    0 MiB | RssAnon    9 | RssFile   6 | cgroup anon    9 | cgroup file    0
  after: tracemalloc    0 MiB | RssAnon  209 | RssFile   6 | cgroup anon  209 | cgroup file    0

 before: tracemalloc    0 MiB | RssAnon    9 | RssFile   6 | cgroup anon    9 | cgroup file    0
 filled: tracemalloc  209 MiB | RssAnon  271 | RssFile   6 | cgroup anon  271 | cgroup file    0
  after: tracemalloc  105 MiB | RssAnon  271 | RssFile   6 | cgroup anon  271 | cgroup file    0

 before: tracemalloc    0 MiB | RssAnon    9 | RssFile   6 | cgroup anon    9 | cgroup file    0
  after: tracemalloc    0 MiB | RssAnon    9 | RssFile   6 | cgroup anon    9 | cgroup file  200
```

The `python` and `native` worlds look identical in every column except the heap. The `fragmented` world freed 104 MiB of objects and gave none of it back, because every arena still held live objects. The page cache world never touched the process's own memory. Part of the gap between 209 MiB of heap and 271 MiB of `RssAnon` in that world is `tracemalloc`'s own bookkeeping, about 21 MiB here, which `tracemalloc.get_tracemalloc_memory()` reports. [tracemalloc](https://docs.python.org/3/library/tracemalloc.html)

The prediction fails if the `native` world raises the heap figure, if freeing half the small objects lowers `RssAnon` by a similar amount, or if the page cache world raises `RssAnon`. Change the count or the `del objs[::2]` stride and `RssAnon` should still hold while any object in each arena lives; replace it with `del objs` and `RssAnon` falls, from 271 MiB to 48 MiB when we ran it, because whole arenas empty.

## Read it on a real system

These commands read only. `/proc/PID/status` is cheap but approximate; `smaps_rollup` sums the same figures exactly and costs more to read. [proc\_pid\_statm(5)](https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html) · [/proc/PID/smaps\_rollup](https://docs.kernel.org/filesystems/proc.html)

```
grep -E '^(VmRSS|RssAnon|RssFile|RssShmem|Threads):' /proc/PID/status
cat /proc/PID/smaps_rollup
grep -E '^(anon|file|shmem|active_file|inactive_file) ' /sys/fs/cgroup/memory.stat   # cgroup v2, inside the container
```

Sample them every few minutes alongside the heap figure. For Python, `tracemalloc.get_traced_memory()` gives the current and peak size of traced blocks, and snapshot comparisons say which lines allocated them. [tracemalloc](https://docs.python.org/3/library/tracemalloc.html) For the JVM, Native Memory Tracking reports the VM's own native memory with `jcmd PID VM.native_memory summary` when the JVM started with `-XX:NativeMemoryTracking=summary`; it does not track allocations by third-party native code. [Native Memory Tracking](https://docs.oracle.com/en/java/javase/21/vm/native-memory-tracking.html)

Which figure the platform calls memory matters. Kubernetes' kubelet leaves `inactive_file` out of `memory.available` for eviction, treating it as reclaimable. [Node-pressure eviction](https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/) At `memory.max`, the kernel tries to reclaim before it invokes the OOM killer, so cached file pages are given up first. [cgroup v2 memory.max](https://docs.kernel.org/admin-guide/cgroup-v2.html)

To test glibc's retention without a restart, `malloc_trim(0)` asks glibc to release free memory from its heap. [malloc\_trim(3)](https://man7.org/linux/man-pages/man3/malloc_trim.3.html) Calling it changes the process, so do it in staging or on one instance. A drop in `RssAnon` after the call is memory glibc was holding free; no drop leaves live native memory, or another allocator's arenas, as the explanation.

## Where the check misleads

tmpfs and shared memory count as `file` in the cgroup, but the kernel lists them under `shmem` as swap-backed, so without swap they stay in memory until the files are deleted. [cgroup v2 memory.stat](https://docs.kernel.org/admin-guide/cgroup-v2.html) A service that writes to `/dev/shm` or a memory-backed `emptyDir` shows `file` growth that behaves like a leak. Read `shmem` before calling `file` growth harmless.

Thread stacks are memory outside any heap profile. A service whose `Threads` count climbs has a native memory explanation of its own. [Fork fails with Resource temporarily unavailable](/learn/fork-resource-temporarily-unavailable-pids-limit/)

Native memory and retention can look alike when bursts are frequent. If `RssAnon` grows in steps that line up with the largest requests and never with time, it is retention; if it grows between bursts too, it is live native memory.

A heap that grows in the profile is a different case: then the question is whether it ever stops. [Memory rises after a deploy: leak or bounded cache?](/learn/memory-grows-leak-or-bounded-cache/) [Choose the observation where explanations disagree](/learn/which-observation-separates-two-explanations/)

## Questions

### Does page cache count toward a container's memory limit?

Yes. The cgroup memory controller counts page cache and anonymous memory together, so files a container writes or reads raise its memory usage. When usage reaches the limit, the kernel tries to reclaim memory, cache included, and invokes the OOM killer only if it cannot.

### Why does RSS not go down after Python frees memory?

Python keeps objects of up to 512 bytes in 1 MiB arenas, and an arena stays mapped while anything in it is alive. In the lab, freeing every other object returned nothing, and freeing all of them returned most of it. Larger objects come from `malloc`, which by default serves requests of 128 KiB or more with `mmap` and can always release those independently. [mallopt(3)](https://man7.org/linux/man-pages/man3/mallopt.3.html)

### How do I see native memory that the heap profiler misses?

Compare `RssAnon` in `/proc/PID/status` with the heap size the runtime reports. The difference is memory allocated outside the language's heap: C extensions, thread stacks and the runtime itself. On the JVM, Native Memory Tracking names the VM's share of it.

## 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](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Containers killed for memory after a deploy: leak or backlog](/learn/container-memory-kills-after-deploy/)
    
    Capacity overruns The Proofline team November 20, 2026 8 min read
    
-   ### [Memory rises steadily after a deploy: a leak, or a cache filling to its bound?](/learn/memory-grows-leak-or-bounded-cache/)
    
    Capacity overruns The Proofline team November 24, 2026 9 min read
