Probes, resources and autoscaling

Mid-level Always asked 7 min

On this page

The question

What is the difference between liveness, readiness and startup probes?

30-second answer

They answer different questions and trigger different actions. Liveness asks whether the container is broken beyond repair; failing it, the kubelet restarts the container. Readiness asks whether it can serve traffic now; failing it, the Pod leaves its Service's endpoints, and nothing restarts. Startup asks whether a slow app has finished starting; until it passes, the other two do not run, so liveness cannot kill a booting JVM. Each can be an HTTP, TCP (Transmission Control Protocol), gRPC or command check.

Understand it

CPU load drives the HPA

Explore

1000 requests a second need 1000m of CPU; each Pod may use 350m at 70%, so the HPA wants 3. It runs 3.

1000 req/s
70 %
View as text

An HPA (Horizontal Pod Autoscaler) box above a row of up to 10 Pods of the Deployment orders. Each Pod requests 500 millicores of CPU and shows a bar of its CPU use against a dashed line at the target. The illustrated service spends 1 millicore per request per second. minReplicas is 2 and maxReplicas 10.

250 requests a second need 250m of CPU; each Pod may use 350m at 70%, so the HPA wants 1. minReplicas keeps 2 running anyway.

1000 requests a second need 1000m of CPU; each Pod may use 350m at 70%, so the HPA wants 3. It runs 3.

1000 requests a second need 1000m of CPU; each Pod may use 250m at 50%, so the HPA wants 4. It runs 4.

5000 requests a second need 5000m of CPU; each Pod may use 350m at 70%, so the HPA wants 15. maxReplicas stops it at 10, so every Pod runs hot.

An HPA (Horizontal Pod Autoscaler) box above a row of up to 10 Pods of the Deployment orders. Each Pod requests 500 millicores of CPU and shows a bar of its CPU use against a dashed line at the target. The illustrated service spends 1 millicore per request per second. minReplicas is 2 and maxReplicas 10.

250 requests a second need 250m of CPU; each Pod may use 350m at 70%, so the HPA wants 1. minReplicas keeps 2 running anyway.

1000 requests a second need 1000m of CPU; each Pod may use 350m at 70%, so the HPA wants 3. It runs 3.

1000 requests a second need 1000m of CPU; each Pod may use 250m at 50%, so the HPA wants 4. It runs 4.

5000 requests a second need 5000m of CPU; each Pod may use 350m at 70%, so the HPA wants 15. maxReplicas stops it at 10, so every Pod runs hot.

Takeaway: The HPA (Horizontal Pod Autoscaler) compares average CPU use, as a percent of each Pod’s request, with a target, and sets replicas to bring it back under, between minReplicas and maxReplicas.

Which probe fails, and what Kubernetes does

Predict

orders runs 3 Pods with startup, liveness and readiness probes. Readiness includes the database check; liveness checks only the app. The database goes down for 2 minutes.

While the database is down, what does Kubernetes do with the orders Pods?
View as text

A database next to one of the 3 orders Pods. The Pod lists its three probes with their results, what liveness checks, its restart count and whether the Service sends it traffic. orders runs 3 Pods with startup, liveness and readiness probes. Readiness includes the database check; liveness checks only the app. The database goes down for 2 minutes. The learner predicts what Kubernetes does.

Readiness fails 3 times in a row and the Pods turn not ready: the Service stops sending them traffic. Liveness still passes, so nothing restarts; the Pods wait.

The database returns, readiness passes again and the Pods rejoin the Service. No restart, no cold start, no lost state: the outage lasted exactly as long as the database’s.

Now add the database to liveness. All 3 Pods fail it and restart again and again, into CrashLoopBackOff: a database outage becomes a full outage.

Last case: the JVM takes 90 seconds to start. A startup probe allowing 30 × 5 s holds the other probes off, so liveness cannot kill it while it boots.

A database next to one of the 3 orders Pods. The Pod lists its three probes with their results, what liveness checks, its restart count and whether the Service sends it traffic. orders runs 3 Pods with startup, liveness and readiness probes. Readiness includes the database check; liveness checks only the app. The database goes down for 2 minutes. The learner predicts what Kubernetes does.

Readiness fails 3 times in a row and the Pods turn not ready: the Service stops sending them traffic. Liveness still passes, so nothing restarts; the Pods wait.

The database returns, readiness passes again and the Pods rejoin the Service. No restart, no cold start, no lost state: the outage lasted exactly as long as the database’s.

Now add the database to liveness. All 3 Pods fail it and restart again and again, into CrashLoopBackOff: a database outage becomes a full outage.

Last case: the JVM takes 90 seconds to start. A startup probe allowing 30 × 5 s holds the other probes off, so liveness cannot kill it while it boots.

Takeaway: A failing readiness probe only removes the Pod from its Service; a failing liveness probe restarts the container; a startup probe holds both off while the app boots. Never let liveness depend on another service.

What Kubernetes does when each check failsA failing startup probe, once it runs out of attempts, restarts the container, and until it passes liveness and readiness do not run. A failing liveness probe restarts the container. A failing readiness probe removes the Pod from its Service's endpoints and restarts nothing. Passing the memory limit gets the container OOMKilled, and using its CPU limit gets it throttled.Startup probe failspast its thresholdContainerrestartedLiveness probe failsReadiness probefailsRemoved fromService endpointsMemory overits limitOOMKilled,exit 137, restartedCPU at its limitThrottled,slower, not killed
What Kubernetes does when each check failsA failing startup probe, once it runs out of attempts, restarts the container, and until it passes liveness and readiness do not run. A failing liveness probe restarts the container. A failing readiness probe removes the Pod from its Service's endpoints and restarts nothing. Passing the memory limit gets the container OOMKilled, and using its CPU limit gets it throttled.Startup probe failspast its thresholdContainerrestartedLiveness probe failsReadiness probefailsRemoved fromService endpointsMemory overits limitOOMKilled,exit 137, restartedCPU at its limitThrottled,slower, not killed
What Kubernetes does when each check fails

In code

      containers:
        - name: orders
          image: registry.example.com/orders:1.4.2
          startupProbe:                         # up to 30 x 5 s = 150 s to start
            httpGet: { path: /actuator/health/liveness, port: 8080 }
            periodSeconds: 5
            failureThreshold: 30
          livenessProbe:                        # restart if the app is broken
            httpGet: { path: /actuator/health/liveness, port: 8080 }
            periodSeconds: 10
          readinessProbe:                       # no traffic while it cannot serve
            httpGet: { path: /actuator/health/readiness, port: 8080 }
            periodSeconds: 5
          resources:
            requests: { cpu: 500m, memory: 768Mi }   # what the scheduler reserves
            limits: { memory: 768Mi }                # over it: OOMKilled
          env:
            - name: JAVA_TOOL_OPTIONS
              value: "-XX:MaxRAMPercentage=75"       # heap = 75% of the limit, the rest for native memory
Three probes on Spring Boot's health groups, and requests and limits
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: orders
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: orders }
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: { type: Utilization, averageUtilization: 70 }
An HPA keeps average CPU near 70% of the request, with 2 to 10 Pods
# Kubernetes probes are on by default when Spring Boot runs in Kubernetes; this turns them on anywhere
management.endpoint.health.probes.enabled=true
# Readiness may include the database: an outage only stops traffic
management.endpoint.health.group.readiness.include=readinessState,db
# Liveness stays the app's own state: never a dependency
management.endpoint.health.group.liveness.include=livenessState
Which checks each health group includes
kubectl get pod orders-56fff5d9f5-9jtpw -o jsonpath='{.status.containerStatuses[0].lastState.terminated}'
# {"exitCode":137,"reason":"OOMKilled",...}            <- over the memory limit
kubectl describe pod orders-56fff5d9f5-9jtpw | grep -A2 "Liveness probe failed"
kubectl get pod orders-56fff5d9f5-9jtpw -o jsonpath='{.status.qosClass}'   # Burstable
kubectl exec deploy/orders -- java -XX:+PrintFlagsFinal -version | grep -E " MaxHeapSize | ActiveProcessorCount "
Read why a container restarted, and what the JVM thinks it has
# The heap alone may grow to 1 GiB in a 768 MiB container: killed under load
 Wrong - name: JAVA_TOOL_OPTIONS
 Wrong   value: "-Xmx1g"

# Sized from the limit the JVM reads: 576 MiB of heap, the rest for metaspace and threads
 Right - name: JAVA_TOOL_OPTIONS
 Right   value: "-XX:MaxRAMPercentage=75"
A fixed heap bigger than the limit gets the container OOMKilled
One HPA decision, every 15 secondsEvery 15 seconds the HPA controller asks the metrics API, served by metrics-server, for the CPU use of the Deployment's Pods. It divides by their requests to get average utilization, 143 percent against a 70 percent target, computes desired replicas as ceiling of 2 times 143 over 70, which is 5, and updates the Deployment's replicas. The scheduler places the new Pods.SchedulerDeployment ordersmetrics-serverHPA controllerceil(2 × 143% ÷ 70%) = 5CPU of the orders Pods?2 Pods, 715m each, of 500m requestedreplicas 53 new Pods to place
One HPA decision, every 15 secondsEvery 15 seconds the HPA controller asks the metrics API, served by metrics-server, for the CPU use of the Deployment's Pods. It divides by their requests to get average utilization, 143 percent against a 70 percent target, computes desired replicas as ceiling of 2 times 143 over 70, which is 5, and updates the Deployment's replicas. The scheduler places the new Pods.SchedulerDeployment ordersmetrics-serverHPA controllerceil(2 × 143% ÷ 70%) = 5CPU of the orders Pods?2 Pods, 715m each, of 500m requestedreplicas 53 new Pods to place
One HPA decision, every 15 seconds

Solve it

Pods restart under load with exit code 137

orders runs with a 1 GiB memory limit and -Xmx1g. Under the afternoon peak, Pods restart every few minutes; kubectl get pods shows restarts climbing and the last state OOMKilled, exit code 137. Heap dumps show the heap is only half full. Explain the restarts and fix them.

  1. Read the reason. OOMKilled with 137 means the kernel killed the process for passing its memory cgroup limit, not a Java OutOfMemoryError, which would be in the logs with exit code 1.
  2. Count all the memory. The limit covers the whole process: heap, metaspace, thread stacks, the code cache, direct buffers and GC (garbage collector) structures. A 1 GiB heap in a 1 GiB limit leaves nothing for the rest.
  3. Size from the limit. Drop -Xmx and set -XX:MaxRAMPercentage=75, 768 MiB of heap, leaving a quarter for native memory. Since JDK (Java Development Kit) 10 the JVM reads the cgroup limit; plain defaults would give only a quarter.
  4. Set requests honestly. Request what the Pod really uses, and set the memory limit equal to it, so the scheduler never overcommits the node. Leave CPU without a limit, or a generous one, to avoid throttling.
  5. Check. Under the same load, restarts stay at 0, kubectl top pod shows memory well under the limit, and Native Memory Tracking accounts for the non-heap part.
kubectl get pod orders-56fff5d9f5-9jtpw -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
# OOMKilled
kubectl set env deployment/orders JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:NativeMemoryTracking=summary"
kubectl rollout status deployment orders
kubectl exec deploy/orders -- jcmd 1 VM.native_memory summary   # heap vs the rest; jcmd needs a JDK image
kubectl top pod -l app=orders                                               # needs metrics-server
Confirm the kill reason, then size the heap from the limit

How to answer

  • Liveness checks the app itself, never a database or another service.
  • Readiness may include dependencies, so an outage only stops traffic.
  • Spring Boot exposes /actuator/health/liveness and /actuator/health/readiness for exactly this.
  • Tune periodSeconds and failureThreshold so one slow check does not trigger an action.

Common mistakes

  • Pointing liveness at a health check that includes the database, turning its outage into restart loops.
  • Using a long initialDelaySeconds on liveness instead of a startup probe.

Follow-up questions

What is the difference between resource requests and limits?

A request is what the scheduler reserves for the container on a node: a Pod only lands where the requests fit, and the HPA measures utilization against them. A limit is the most it may use, enforced by cgroups at run time. Past its CPU limit a container is throttled; past its memory limit it is killed, OOMKilled. Requests and limits together set the QoS (quality of service) class, which decides who is evicted first when a node runs short.

  • Guaranteed QoS, requests equal to limits, is evicted last.
  • Memory limit equal to the request avoids surprise kills from overcommitted nodes.
  • CPU limits often cause throttling at peaks; many teams set only a CPU request.

See it in the infographic: CPU load drives the HPA

A Pod shows OOMKilled with exit code 137. What does it mean, and how do you fix it?

The container's processes used more memory than its limit, and the kernel's OOM (out of memory) killer ended them with SIGKILL, so 128 plus 9 is 137; the kubelet then restarts it. It is not a Java OutOfMemoryError, which is thrown inside a JVM whose heap is full. For a JVM, the usual cause is a heap sized near the limit, leaving no room for metaspace, threads and direct buffers. Size the heap with -XX:MaxRAMPercentage, around 75, or raise the limit.

  • kubectl describe pod shows Last State Terminated, Reason OOMKilled.
  • A node under memory pressure can also evict Pods, which looks different, as Evicted.
  • Native Memory Tracking shows where the non-heap memory goes.

See it in the infographic: Which probe fails, and what Kubernetes does

How does the Horizontal Pod Autoscaler decide how many replicas to run?

Every 15 seconds the HPA (Horizontal Pod Autoscaler) reads a metric, usually average CPU use as a percent of the Pods' requests, from the metrics API served by metrics-server. It computes desired replicas as current replicas times current value divided by target, rounded up, ignores changes within a 10 percent tolerance, clamps the result between minReplicas and maxReplicas, and updates the Deployment. Scaling down waits through a 5-minute stabilization window, so short dips do not remove Pods.

  • Without CPU requests on the Pods, CPU utilization cannot be computed.
  • Custom or external metrics, such as queue length, scale on demand directly; KEDA builds on this.
  • The cluster autoscaler adds nodes when new Pods do not fit.

See it in the infographic: CPU load drives the HPA

What should you watch out for when running a JVM in a container?

Memory and CPU sizing. JVMs since JDK 10 and 8u191 read the cgroup limits, but the default heap is a quarter of the limit, so set -XX:MaxRAMPercentage, typically 75, leaving room for metaspace, threads and buffers. The CPU count comes from the CPU limit and sizes GC (garbage collection) threads; under 2 CPUs or about 1.8 GB the JVM falls back to the Serial collector. Start java as PID (process ID) 1 so it receives SIGTERM.

  • Never set -Xmx equal to the memory limit; the JVM (Java Virtual Machine) needs room beyond its heap.
  • -XX:ActiveProcessorCount overrides the CPU count when limits mislead the JVM.
  • JVM startup and warm-up interact with probes and autoscaling; use a startup probe.

See it in the infographic: CPU load drives the HPA

How would you design the probes for a Spring Boot service that depends on PostgreSQL and Kafka?

Liveness on /actuator/health/liveness, which reflects only the application's own state, so a dependency outage never restarts it. Readiness on /actuator/health/readiness, including the database if requests cannot be served without it, so an outage takes Pods out of rotation. A startup probe with enough failureThreshold to cover the slowest cold start. Keep checks cheap, with timeouts below periodSeconds, and do not make readiness depend on something every replica shares unless you accept all of them leaving together.

  • Kafka consumers keep working without traffic, so readiness matters less for them.
  • All replicas unready at once means the Service has no endpoints, a deliberate trade-off.
  • Test probes by killing dependencies in staging.

See it in the infographic: Which probe fails, and what Kubernetes does

What happens to in-flight requests when a Pod is shut down during a rollout?

The Pod is marked terminating and removed from endpoints while the kubelet sends SIGTERM, but load balancers and kube-proxy rules update a moment later, so a few requests can still arrive. A short preStop sleep, a few seconds, plus Spring Boot's graceful shutdown lets those finish within terminationGracePeriodSeconds, 30 by default.

Check yourself

1. A Pod's readiness probe fails while its liveness probe passes. What does Kubernetes do?
Show answers
  • Removes it from the Service's endpoints and leaves it running: Correct. Readiness only decides who receives traffic.
  • Restarts the container: Incorrect. Restarts come from liveness or a startup probe running out of attempts.
  • Evicts the Pod to another node: Incorrect. Probes never move Pods.
2. A container passes its CPU limit, and another passes its memory limit. What happens to each?
Show answers
  • The first is throttled, the second is OOMKilled: Correct. CPU time can be withheld; memory cannot, so the kernel kills.
  • Both are killed and restarted: Incorrect. CPU over the limit only waits for the next period.
  • Both are slowed down: Incorrect. There is no way to slow memory use down, so it is killed.
3. An HPA targets 70% CPU. 2 Pods each request 500m and use 700m, which is 140%. How many replicas does it want?
Show answers
  • 4: Correct. ceil(2 × 140 ÷ 70) = 4.
  • 3: Incorrect. 1,400m ÷ 350m is exactly 4, so 3 leaves Pods above the target.
  • 10, the maximum: Incorrect. The HPA computes a number, then clamps it; 4 is within the range.