Kubernetes Auto Scaling HPA

Scale Kubernetes Pods dynamically with Horizontal Pod Autoscaler v2, metric formulas, stabilization windows, behavior rules, and interview prep.

The Horizontal Pod Autoscaler (HorizontalPodAutoscaler) automatically adjusts the number of Pod replicas in a deployment, replication controller, or stateful set based on observed compute metrics (such as CPU and memory utilization) or custom/external application metrics (such as HTTP requests per second or message queue depth). HPA ensures consistent application performance during sudden traffic surges while reducing cloud infrastructure costs during quiet periods.

HPA Architecture and Scaling Formula

The Kubernetes Horizontal Pod Autoscaler operates in a continuous control loop (default cycle of 15 seconds) driven by the kube-controller-manager. The controller queries the metrics APIs (metrics.k8s.io, custom.metrics.k8s.io, or external.metrics.k8s.io) and computes the target replica count using a mathematical formula:

$$\text{desiredReplicas} = \left\lceil \text{currentReplicas} \times \left( \frac{\text{currentMetricValue}}{\text{targetMetricValue}} \right) \right\rceil$$

If the ratio is sufficiently close to 1.0 (within the default tolerance of 0.1 or 10%), the controller takes no action to prevent unnecessary thrashing.

Autoscaler Type Target Resource Scaling Mechanism Primary Tool / Project
HPA (Horizontal) Pod count Adds or removes Pod replicas horizontally Kubernetes built-in HPA controller
VPA (Vertical) Pod CPU/Memory Resizes container requests and limits in-place or via restart Vertical Pod Autoscaler
Cluster Autoscaler Node count Adds or terminates cloud VM worker nodes Cluster Autoscaler / Karpenter

HPA Behavior and Stabilization Windows

Modern autoscaling/v2 allows granular control over scaling velocity and stabilization windows to prevent flapping (rapidly scaling up and down in response to transient metric spikes):

  • Stabilization Window: Enforces a cooling period (e.g., 300 seconds for scale-down) during which the algorithm evaluates the maximum desired replica state before removing Pods.
  • Scaling Policies: Enforce maximum percentage or integer changes per time unit (e.g., scale up by at most 100% or 4 pods every 15 seconds).

Production HPA Manifest (autoscaling/v2)

The following manifest demonstrates a production autoscaling/v2 HPA combining CPU utilization, Memory utilization, and custom scale-down dampening:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: checkout-service-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout-service
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 15
        - type: Pods
          value: 4
          periodSeconds: 15
      selectPolicy: Max
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60
      selectPolicy: Min

Managing and Inspecting HPA with kubectl

# Check current HPA targets, current metrics, and replica counts
kubectl get hpa -n production
# NAME                   REFERENCE                     TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
# checkout-service-hpa   Deployment/checkout-service   62%/70%, 54%/80% 2         10        3          5d

# Inspect detailed autoscaling events, metric queries, and condition status
kubectl describe hpa checkout-service-hpa -n production

Common Mistakes

  • Omitting container resource requests: HPA cannot calculate CPU or memory percentage utilization if resources.requests is not declared on containers in the target Deployment.
  • Using HPA and VPA on the same metrics: Running HPA and VPA concurrently targeting the same CPU/memory metrics results in conflicting control loops and erratic scaling.
  • Scaling solely on JVM memory: Java applications retain allocated heap rather than releasing it immediately to the OS, causing memory-based HPA to stay at maxReplicas indefinitely.
  • Zero stabilization on scale-down: Disabling scale-down stabilization causes rapid pod churn during bursty network traffic.

Best Practices

  • Always define realistic resources.requests on all containers before configuring an HPA.
  • Configure a generous scaleDown.stabilizationWindowSeconds (300 seconds) to accommodate temporary dips in traffic.
  • Scale primarily on CPU or throughput/request-rate custom metrics rather than raw memory.
  • Pair HPA with Cluster Autoscaler or Karpenter so the underlying node pool expands when HPA schedules new Pods.

Interview Questions

1. How does the Horizontal Pod Autoscaler calculate the desired number of replicas?

The HPA calculates desired replicas using the formula: $$\text{desiredReplicas} = \lceil \text{currentReplicas} \times (\text{currentMetricValue} / \text{targetMetricValue}) \rceil$$ For example, if you have 4 replicas running at 80% CPU utilization and your target is 50%, the desired replicas calculation is $\lceil 4 \times (80 / 50) \rceil = \lceil 6.4 \rceil = 7$ replicas.

2. Why is configuring container resource requests mandatory for HPA?

When target metrics are expressed as a percentage (averageUtilization), Kubernetes calculates utilization as: $$\text{utilizationPercentage} = \frac{\text{currentUsage}}{\text{resourceRequest}} \times 100$$ Without resources.requests, the denominator is undefined, causing HPA to report <unknown> and refuse to scale.

3. What is the difference between HPA, VPA, and Cluster Autoscaler?

HPA adjusts the number of Pod replicas (horizontal scaling). VPA modifies the CPU and memory resource requests and limits of existing Pods (vertical scaling). Cluster Autoscaler adjusts the number of physical or virtual worker nodes in the Kubernetes cluster when Pods are unschedulable due to resource shortages.

4. What is flapping and how does HPA prevent it?

Flapping is the rapid alternating between scaling up and scaling down caused by brief metric fluctuations. HPA prevents flapping using stabilization windows (configured in spec.behavior.scaleDown.stabilizationWindowSeconds), which evaluate the maximum recommended replica count over a historical timeframe (default 5 minutes) before terminating Pods.

5. Why is scaling on memory metrics often problematic for garbage-collected languages like Java?

Garbage-collected runtimes (such as Java JVM or Go) allocate memory into heap pools and do not immediately return freed memory back to the operating system after garbage collection cycles. As a result, memory metrics remain elevated, causing HPA to scale out to maxReplicas and never scale down.

6. How does HPA handle multiple metrics defined in the same manifest?

When multiple metrics (such as CPU, Memory, and custom HTTP request counts) are configured, HPA calculates the desired replica count for each metric independently and scales to the highest calculated replica count among all metrics to ensure system reliability.

Summary

  • HPA dynamically scales Pod replicas using the metrics API and a ratio-based formula.
  • resources.requests is strictly mandatory for percentage-based CPU and memory scaling.
  • autoscaling/v2 provides behavior controls to customize scale-up speed and scale-down dampening.
  • Combine HPA with Cluster Autoscaler for end-to-end workload and node elasticity.

Continue Learning

Previous: Health Checks | Next: Rolling Update and Rollback

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.