Running Java on Kubernetes: probes, limits and graceful shutdown
Most of the trouble I've seen with Java on Kubernetes comes from three places: memory settings that disagree with the container, probes that test the wrong thing, and shutdowns that drop requests. All three are configuration, and all are easy to get right once.
Memory: size the heap from the limit
Modern JVMs read the container's limits, so the old advice about special flags is out of date. What remains is deciding how much of the limit is heap. Use a percentage, so the same image works at any size:
env:
- name: JAVA_TOOL_OPTIONS
value: >-
-XX:MaxRAMPercentage=65
-XX:+ExitOnOutOfMemoryError
resources:
requests:
memory: 1Gi
cpu: 500m
limits:
memory: 1Gi
Don't use 100%. A JVM's memory also includes metaspace, thread stacks, the code cache, GC structures and direct buffers. If the total crosses the limit, the kernel kills the container with exit code 137, and no OutOfMemoryError or stack trace appears anywhere. A heap at 60 to 75% of the limit is a good starting point. Native-heavy services, with lots of Netty direct buffers for instance, need the lower end. To see what's actually using the rest, run with -XX:NativeMemoryTracking=summary and then jcmd <pid> VM.native_memory.
Set the memory request equal to the limit. Memory can't be reclaimed from a running JVM the way CPU can be throttled, so a pod running above its request is first in line for eviction when the node runs short.
ExitOnOutOfMemoryError lets Kubernetes restart a process that has run out of heap, rather than leaving it half alive.
CPU: be careful with limits
The JVM also derives decisions from the CPU limit: availableProcessors(), GC threads, the common pool. A limit of 500m looks like one processor, which may push the JVM towards SerialGC and make thread pools very small. If that's not what you want, set -XX:ActiveProcessorCount explicitly.
CPU limits are enforced in small time slices by CFS quota, so a JVM can use up its allowance in the first part of a 100 ms period and then be throttled for the rest. That's especially painful at startup and during GC, and it appears as latency with no obvious cause. Check container_cpu_cfs_throttled_periods_total. Many teams set a CPU request and no CPU limit, which is a reasonable default if your platform allows it.
Probes: three questions
Each probe asks something different, and mixing them up causes outages.
| Probe | Question | On failure |
|---|---|---|
| Startup | Has it finished starting? | Keep waiting, then restart |
| Readiness | Should it get traffic right now? | Removed from the service |
| Liveness | Is it stuck beyond recovery? | Container restarted |
Spring Boot Actuator provides separate endpoints for these:
startupProbe:
httpGet: { path: /actuator/health/readiness, port: 8080 }
periodSeconds: 5
failureThreshold: 36 # up to three minutes to start
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 8080 }
periodSeconds: 5
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 8080 }
periodSeconds: 10
failureThreshold: 3
The startup probe keeps slow JVM warmups away from the liveness check, so you don't need a large initialDelaySeconds.
A liveness probe should never check a database or any other dependency. Imagine the database has a brief problem and liveness depends on it. Every pod fails its probe, every pod restarts, and a small database issue becomes a total outage, followed by a thundering herd of cold JVMs reconnecting at once. Restarting your application doesn't repair someone else's database.
Spring Boot's liveness group doesn't include dependencies by default, so leave it that way. Readiness is where a dependency can go, if taking the pod out of rotation would actually help. If every pod depends on the same database, it often won't.
Keep the management endpoints out of public routing too.
Graceful shutdown
During a rolling update, a pod receives SIGTERM while traffic may still be on its way to it. Removing it from the service's endpoints and stopping the process happen in parallel, and the load balancer learns about the change some time later. If the application exits immediately, requests fail.
# application.yml
server:
shutdown: graceful # the default since Spring Boot 3.4
spring:
lifecycle:
timeout-per-shutdown-phase: 25s
# Pod spec
terminationGracePeriodSeconds: 45
containers:
- name: app
lifecycle:
preStop:
sleep:
seconds: 10
The sleep action needs a reasonably recent Kubernetes version. On older clusters use an exec hook with sleep, as long as the image has that command.
The numbers need to add up: the preStop wait, plus the application's shutdown timeout, must be shorter than terminationGracePeriodSeconds. Otherwise Kubernetes ends the process with SIGKILL partway through. Here that's 10 + 25, which fits in 45.
And make sure Java actually receives the signal. A shell-form ENTRYPOINT or a wrapper script that doesn't use exec leaves the shell as PID 1, and the JVM may never see SIGTERM.
A quick checklist
- The heap is a percentage of the limit, and well under 100%.
- Memory request equals memory limit.
- CPU throttling is measured rather than assumed.
- Liveness has no external dependencies.
- A startup probe covers slow starts.
- Shutdown timings add up, and Java is PID 1.
Get these right in a shared chart or template, and each new service starts out correct.