Video in progress
A Java service on Kubernetes works with files a lot and gets OOMKilled from time to time, while the heap is well below the limit. How could file IO be related?
The container's memory accounting (cgroup) includes page cache and tmpfs. Writing large files increases dirty pages, and emptyDir with medium: Memory is straight RAM. Add mmap and direct buffers, and the process exceeds the limit even if the heap is small.
📖 Answer
In Kubernetes the memory limit works through cgroups, and it counts not only the process's "own" memory but also the page cache that belongs to the container. The kernel reclaims clean page cache under pressure, so it usually does not cause an OOMKill. But there are a few cases:
- Dirty pages. The service writes fast and the disk is slow. Unwritten pages can't be reclaimed; they have to reach the disk first. Under pressure this ends in throttling and sometimes OOM.
- tmpfs. A file written to
emptyDir: { medium: Memory }or to/dev/shmis RAM, and it counts toward the container limit. If someone did this so that "temp would be faster", a 3 GB temporary file kills the pod. - mmap. Modified (dirty) mapped pages and large read-only mappings show up in RSS.
- Direct buffers and the JDK's internal caches: same as in the previous question.
To check:
kubectl exec pod -- cat /sys/fs/cgroup/memory.stat # cgroup v2: anon, file, file_dirty, shmem
kubectl describe pod pod | grep -A3 "Last State" # OOMKilled, exit code 137
A large anon means the Java process's memory (heap + native). A large shmem means tmpfs. A large file/file_dirty means file IO.
What I do:
- For large temporary files, a disk-backed
emptyDirand anephemeral-storagelimit; in-memory tmpfs only for small, bounded data. - Don't keep very large files in the pod: stream them to storage.
- Compute the memory limit from
-Xmx+ native + the working set of file IO.-XX:MaxRAMPercentage=75leaves 25% for everything else, which may be too little for a service that works with files a lot. - Exceeding the ephemeral storage limit also evicts the pod: it is a separate limit that is often forgotten.
Sign up to mark studied questions and save your progress.