Our label rendering service is a Java application that builds carrier labels as PDFs. On virtual machines it ran for months without a restart. In September we moved it to Kubernetes with a memory limit of three gigabytes and a heap of one and a half, and from then on each pod was OOMKilled every four or five days.
The heap was not the problem. Our JVM graphs showed it peaking at about a gigabyte after collection. Native Memory Tracking, which reports what the JVM itself has allocated outside the heap, came to about two gigabytes in total and stayed flat. The container's resident memory kept climbing past that by around a hundred megabytes a day until the kernel killed it.
pmap -x on a running pod showed the gap: dozens of anonymous mappings of almost exactly sixty four megabytes each. That shape belongs to glibc's malloc, not to Java. To keep threads from queueing on one lock, glibc gives allocating threads separate arenas, each with its own heaps of up to sixty four megabytes, and on a 64 bit system it allows up to eight arenas per CPU core. It counts the cores the machine has, not the CPU limit of the container. Our old virtual machines had eight cores. Our Kubernetes nodes have forty eight, so the same process was allowed three hundred and eighty four arenas.
The service allocates native memory from many threads: the PDF library inflating fonts and images through java.util.zip, and the network library's own buffers. Memory freed inside an arena is often kept for reuse rather than returned to the system, so with hundreds of arenas, each holding scraps nobody would use again, resident memory only grew. Native Memory Tracking could not see it, because it counts what the JVM asked malloc for, not what malloc keeps afterwards.
The fix was one environment variable in the Deployment, MALLOC_ARENA_MAX=2. Resident memory now levels off at about 2.1 gigabytes within a day and stays there. Fewer arenas means more threads contending for each one, so we compared render latency for a week before and after, and could not find a difference at our load.
Our base image now sets the variable for every Java service, and the memory dashboard shows resident memory next to the JVM's own total, so a gap between them is visible the week it opens, not on the fifth restart.
A container limits what a process may use. It does not change what the process believes about the machine.
– Sergey Shinder


