Horizontal Pod Autoscaler (HPA)

Difficulty: Advanced

Question

How does the Horizontal Pod Autoscaler (HPA) work in Kubernetes, what metrics can it use, and what are the common pitfalls?

Answer

The Horizontal Pod Autoscaler automatically changes the replica count of a Deployment or StatefulSet based on observed metrics. Every 15 seconds by default it reads current utilisation (usually CPU from Metrics Server), compares it with a target such as 70%, and computes desiredReplicas = ceil(currentReplicas × currentValue / targetValue), clamped between minReplicas and maxReplicas.

How the control loop works

  1. Metrics Server scrapes CPU and memory from each kubelet and exposes them through the metrics.k8s.io API.
  2. The HPA controller (inside kube-controller-manager) reads these metrics for all Pods selected by the target.
  3. Utilisation is calculated relative to resource requests. A Pod using 350m CPU with a 500m request is at 70%.
  4. It computes the desired replicas with the formula above. Example: 4 Pods averaging 140% against a 70% target gives ceil(4 × 140/70) = 8.
  5. It updates the scale subresource, and the Deployment creates or removes Pods.

A tolerance of 10% avoids flapping on small changes, and by default scale-down waits for a 5-minute stabilization window so a short dip does not remove capacity.

Metric types

TypeSourceExample
ResourceMetrics ServerCPU at 70%, memory average
ContainerResourceMetrics ServerCPU of only the app container, ignoring sidecars
PodsCustom metrics API (Prometheus Adapter)Requests per second per Pod
ObjectCustom metrics APIRequests per second on an Ingress
ExternalExternal metrics APISQS or Kafka queue lag

For event-driven workloads, KEDA is widely used. It plugs into the HPA as an external metrics provider and can also scale to zero, which plain HPA cannot do.

Pitfalls interviewers like to hear about

  • No resource requests: utilisation cannot be calculated, and the HPA reports <unknown> targets.
  • Memory-based scaling often fails for JVM or Node.js apps, because memory is rarely released after load drops, so they never scale down.
  • Fighting with kubectl or GitOps: if your manifest sets replicas: 3 and Argo CD reapplies it, it overrides the HPA. Remove replicas from the Deployment once an HPA owns it.
  • HPA and VPA on the same CPU metric conflict. Use VPA in recommendation mode or scale on different signals.
  • Slow reaction: metrics lag plus Pod start time means HPA cannot absorb a sudden spike, such as a Flipkart Big Billion Days sale opening at midnight. Pre-scale with a higher minReplicas or a scheduled scaler, and make sure the Cluster Autoscaler or Karpenter can add nodes, otherwise new Pods just sit Pending.

Tuning with the behavior field

autoscaling/v2 lets you control scale velocity: for example allow doubling every 15 seconds on scale-up but remove at most 10% of Pods per minute on scale-down. This gives fast reaction to spikes and gentle recovery.

HPA control loop. Every 15 seconds the HPA turns metrics into a new replica count.
  1. kubelet stats: CPU and memory per container.
  2. Metrics Server: Serves the metrics.k8s.io API.
  3. HPA controller: Computes ceil(current x actual / target).
  4. Scale subresource: Sets replicas on the Deployment.
  5. New Pods: Scheduled onto nodes, or Pending if no room.

Code examples

HPA on CPU with tuned scaling behavior

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: checkout
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout
  minReplicas: 3
  maxReplicas: 40
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70   # percent of the CPU request
  behavior:
    scaleUp:
      policies:
        - type: Percent
          value: 100               # can double
          periodSeconds: 15
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10                # shrink slowly
          periodSeconds: 60

The Deployment's Pods must declare CPU requests. Scale-up is aggressive and scale-down is cautious, which suits bursty user traffic.

Checking HPA status

kubectl top pods -l app=checkout
kubectl get hpa checkout --watch
kubectl describe hpa checkout   # shows events and why it did or did not scale

If TARGETS shows <unknown>, check that Metrics Server is running and that the Pods have resource requests.

Key points

  • Formula: desired = ceil(current replicas x current metric / target metric).
  • CPU utilisation is measured against requests, so requests are mandatory.
  • Default sync period is 15s; default scale-down stabilization window is 5 minutes.
  • Custom and external metrics need an adapter such as Prometheus Adapter or KEDA.
  • HPA scales Pods, not nodes; pair it with Cluster Autoscaler or Karpenter.

Common follow-up questions

  • Why does the HPA show <unknown> for its target?
  • How would you autoscale a worker based on Kafka consumer lag?
  • What is the difference between HPA, VPA and Cluster Autoscaler?
  • How would you prepare for a traffic spike at a known time?

Interview tips

  • Write out the replica formula with a quick worked example; it is concrete and memorable.
  • Mention that utilisation is relative to requests; many candidates think it is relative to node capacity.
  • Bring up the HPA vs GitOps replicas conflict; it is a real production issue that shows experience.

Concepts covered

Horizontal Pod Autoscaler, Metrics Server, Resource Requests, Scaling Behavior, KEDA

More Kubernetes & Orchestration questions