Video in progress
How do you match requests/limits and JVM settings for a Java service in Kubernetes?
I set the memory limit based on the JVM's whole footprint: the heap is 60-75% of the limit through MaxRAMPercentage, and the rest goes to native memory. I set the CPU limit carefully, because throttling slows down the GC and JIT threads too.
📖 Answer
Since JDK 10 the JVM sees cgroup limits (cgroup v2 support from JDK 15 and 11.0.16). That means you can give a percentage instead of writing -Xmx by hand.
resources:
requests: { cpu: "1", memory: "2Gi" }
limits: { memory: "2Gi" } # no CPU limit
env:
- name: JAVA_TOOL_OPTIONS
value: "-XX:MaxRAMPercentage=70 -XX:ActiveProcessorCount=2"
On memory: I set the memory request and limit equal, because Java rarely gives memory back, and a pod that goes above its request is the first to be killed under node pressure. 70% is an average figure. In a service with many threads, Netty or a big metaspace it can be 60%. I work it out by measuring with NMT.
On CPU there is a debate. With a CFS quota limit, if the quota runs out within the 100 ms period, the whole process waits, which gives a latency spike no different from a GC pause. Many teams remove the CPU limit and keep only the request. Then the JVM may calculate availableProcessors() from the node's cores, not from the request (JDK 19+ doesn't consider CPU shares), so I write -XX:ActiveProcessorCount explicitly. The number of GC threads, ForkJoinPool and Netty event loops follows from it.
Finally: let the readiness probe account for JIT warm-up, and don't let the liveness probe kill a pod during a long Full GC. Set the timeouts by looking at the worst pause in the GC log.
Sign up to mark studied questions and save your progress.