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
mallocand 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 glibc's
malloccan 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) - Page cache counts as memory.
v2.14writes 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
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
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 RssAnon and RssFile split a process's resident memory the same way. proc_pid_status(5)
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"
doneWrite 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
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) ยท /proc/PID/smaps_rollup
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 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
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 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
To test glibc's retention without a restart, malloc_trim(0) asks glibc to release free memory from its heap. malloc_trim(3) 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 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
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? Choose the observation where explanations disagree
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)
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.