Video in progress

Strong Junior 🧩 Microservices

How do you set memory for a Java service running in a container: `-Xmx` or `MaxRAMPercentage`?

A modern JVM sees the container limit, so I give the heap relative to the limit with -XX:MaxRAMPercentage, usually 60-75%. The rest is needed for metaspace, thread stacks and direct buffers; if you make the heap equal to the limit, the pod gets OOMKilled.

📖 Answer

Since Java 10 (and 8u191 too) the JVM reads the cgroup limit. But by default the heap is only 1/4 of the container memory: ~512 MiB in a pod with a 2 GiB limit. Many people are surprised: there's memory available, yet the service throws OutOfMemoryError: Java heap space.

The second mistake is the opposite: a 2 GiB limit and -Xmx2g. The JVM also has memory outside the heap: metaspace, JIT code, a stack for every thread, Netty/NIO direct buffers, GC structures. The total goes over the limit and Kubernetes kills the process with OOMKilled, and you see no exception at all in Java.

Here's what I usually do:

env:
  - name: JAVA_TOOL_OPTIONS
    value: "-XX:MaxRAMPercentage=70 -XX:+ExitOnOutOfMemoryError"
resources:
  requests:
    memory: "1Gi"
  limits:
    memory: "1Gi"

It's convenient that the percentage is tied to the limit: if you change the limit, the heap adjusts by itself. ExitOnOutOfMemoryError is so you don't get stuck half-dead: the process exits and Kubernetes restarts it.

If there are many threads (say, 400 Tomcat threads) or you use a lot of direct buffers, lower the percentage to 60. You can see the real breakdown with -XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory.