Video in progress

What problems appear when a HorizontalPodAutoscaler scales a Java service on CPU?

A new JVM pod eats a lot of CPU while it starts and its JIT warms up, so the HPA may take this for load and add even more pods. Also, memory in Java almost never goes down, so scale-down based on memory does not work well.

📖 Answer

The usual story: traffic went up, CPU passed 70%, and the HPA added 4 new pods. The new pods take 40 seconds to come up, run slowly in interpreted mode in their first minutes, and compile with the JIT, so CPU stays high again. The HPA adds more. Then when the load drops, the pods fall sharply and the whole thing repeats.

What you can do:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
spec:
  minReplicas: 4
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: { type: Utilization, averageUtilization: 60 }
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - { type: Pods, value: 1, periodSeconds: 60 }
  • the HPA computes the percentage relative to requests.cpu. If requests is wrong, the whole calculation is wrong;
  • the startup CPU of pods that are not ready yet counts for less in the calculation, which is why a correct readiness probe matters;
  • I set minReplicas so that it covers an ordinary daytime load, and scaling is only for peaks;
  • sometimes a better signal is not CPU but the request count or the queue length (custom metrics, KEDA).

I avoid autoscaling on memory: once the heap has grown, the JVM rarely gives it back to the OS, and the HPA will never scale down.