Video in progress
A container keeps getting OOMKilled, but on the heap graphs memory never went above half of the limit. Where do you look?
limits.memory: 1Gi
JAVA_OPTS: -Xmx700m
kubectl describe pod: Last State: Terminated, Reason: OOMKilled, Exit Code: 137
Grafana: jvm_memory_used_bytes{area="heap"} ~ 450Mi
The container limit measures the memory of the whole process, not the heap. Thread stacks, metaspace, direct buffers, the JIT code cache and malloc arenas grow outside the heap, so you need Native Memory Tracking to find which one it is.
📖 Answer
Start with the arithmetic: -Xmx700m is 70% of the limit. Everything else had to fit into the remaining 300 MB: 200 threads × ~1 MB of stack (the committed part is actually less, but still), metaspace, the code cache, the GC's own structures, Netty or NIO direct buffers. In many cases that is not enough.
Diagnosis:
# enabled at startup: -XX:NativeMemoryTracking=summary
kubectl exec shop-api-xyz -- jcmd 1 VM.native_memory summary
kubectl exec shop-api-xyz -- jcmd 1 VM.native_memory baseline
# an hour later
kubectl exec shop-api-xyz -- jcmd 1 VM.native_memory summary.diff
summary.diff shows which section is growing: Thread, Class, Internal, Other. Compare it with the total RSS inside the container from cat /sys/fs/cgroup/memory.current (cgroup v2).
What you might find:
- an unbounded thread pool, with a new thread for every request;
- direct buffers, which need to be capped with
-XX:MaxDirectMemorySize; - classes being generated nonstop (proxies, scripting engines), so metaspace grows;
- glibc malloc arenas: in an app with many threads, RSS can bloat noticeably, and
MALLOC_ARENA_MAX=2often helps.
NMT does not see everything either: memory allocated by a native library through JNI does not show up in it. In that case, the gap between RSS and the NMT total points at that "invisible" part.
Sign up to mark studied questions and save your progress.