Horizontal Pod Autoscaler: Scaling Decisions in Practice

The Horizontal Pod Autoscaler in Kubernetes: the scaling formula, scale-up and scale-down behavior, custom metrics, KEDA and pitfalls.

Executive Summary: The Horizontal Pod Autoscaler (HPA) changes a Deployment’s replica count so a metric stays near a target. Its core formula is simple: desired replicas equal current replicas multiplied by the ratio of current to target metric value. Most HPA problems come from what feeds that formula: CPU utilization measured against inaccurate requests, metrics that do not reflect load, pods that take minutes to become ready, and default scale-down behavior that is slower than people expect. Tune those inputs, add custom or queue-based metrics where CPU is the wrong signal, and pair the HPA with a node autoscaler so new pods have somewhere to run.
Isometric steps of pod groups growing from one to five replicas under a rising metrics line

A team adds an HPA targeting 70% CPU to their API. During a marketing email blast, traffic triples in two minutes. The HPA scales from 3 to 9 pods, but the new pods take 90 seconds to pass readiness, and three of them stay Pending because the nodes are full. Latency spikes anyway. After the peak, the team watches the replica count stay high for five minutes and assumes the HPA is broken. It is working exactly as configured; the configuration just did not match the workload.

The Horizontal Pod Autoscaler is a Kubernetes controller that periodically (every 15 seconds by default) reads metrics for a workload and adjusts the replicas field of its Deployment or StatefulSet. It scales horizontally, adding and removing pods, as opposed to the Vertical Pod Autoscaler, which changes each pod’s requests.

A modern HPA

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: billing-api
  namespace: billing
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: billing-api
  minReplicas: 3
  maxReplicas: 30
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 30
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 20
          periodSeconds: 60

Use the autoscaling/v2 API, which has been stable since Kubernetes 1.23 and supports multiple metrics and the behavior section. Resource metrics come from the metrics-server add-on, which most managed clusters install by default.

The formula

desiredReplicas = ceil( currentReplicas × currentMetricValue / targetMetricValue )

With 4 replicas averaging 140% CPU utilization against a 70% target, the HPA wants ceil(4 × 140 / 70) = 8. With several metrics, it computes a desired count for each and uses the highest. To avoid flapping, it ignores changes when the ratio is within a 10% tolerance of 1.0.

The crucial detail: CPU utilization is a percentage of the request, not of the node or the limit. A pod requesting 200m and using 300m is at 150%. If requests are inflated, utilization looks low and the HPA never scales; if they are tiny, it scales wildly. Accurate requests, covered in requests and limits, are a prerequisite for CPU-based autoscaling. Pods without a CPU request cannot be used for utilization at all, and the HPA reports an error.

Kubernetes 1.30, released last month, made ContainerResource metrics generally available. They compute utilization from a single named container rather than the whole pod, which keeps sidecars such as service mesh proxies from distorting the numbers.

Scaling behavior: fast up, slow down

By default, scale-up is immediate and aggressive, while scale-down uses a five-minute stabilization window: the HPA picks the highest recommendation from the last five minutes before scaling down. That is why replicas stay high after a spike. It is deliberate, to avoid removing pods just before the next burst, and it can be tuned with the behavior section above:

  • scaleUp.policies limit how fast replicas are added, for example at most doubling every 30 seconds.
  • scaleDown.stabilizationWindowSeconds sets how long to wait for load to stay low.
  • scaleDown.policies limit how many pods are removed per period, so a sudden drop does not remove half the fleet at once.

Choosing the right metric

Workload Good scaling signal How
CPU-bound API CPU utilization Resource metric
I/O-bound API waiting on databases Requests per second per pod, or concurrency Custom metric via Prometheus Adapter
Queue workers Queue depth or lag per worker External metric, or KEDA
Event-driven jobs that are often idle Events pending, scaling to zero KEDA
Memory-heavy service Rarely memory itself Usually a load metric instead

Memory is a poor autoscaling signal for most applications, because memory usage rarely drops when load drops; caches and runtimes hold on to it. A memory-based HPA tends to scale up and never come back down.

KEDA (Kubernetes Event-driven Autoscaling), a CNCF project, deserves a mention for queue and event workloads. It ships scalers for Kafka, RabbitMQ, SQS, Redis, Prometheus queries, cron schedules and many more, creates and manages the HPA for you, and can scale a deployment to zero replicas when there is no work, which the HPA alone cannot do.

Pods need somewhere to go

The HPA creates pods; it does not create nodes. When the cluster is full, new pods stay Pending. A node autoscaler closes that gap: the Cluster Autoscaler adds nodes to node groups when pods cannot be scheduled and removes underused ones, while Karpenter, popular on AWS, provisions right-sized nodes directly from pending pods’ requirements. Adding a node takes a minute or more, so for sudden spikes keep some headroom, either through a slightly lower utilization target or low-priority placeholder pods that get preempted when real pods need the space.

Pitfalls worth avoiding

  • Fighting with your manifests. If your GitOps tool or kubectl apply sets replicas: 3 on the Deployment, every apply resets what the HPA chose. Remove replicas from manifests of autoscaled workloads.
  • Slow startup. If pods take minutes to become ready, scaling reacts too late. Reduce startup time, use startup probes, and lower the target to scale earlier.
  • minReplicas of 1. A single replica means downtime during node maintenance and rollouts. Use at least 2 or 3 for anything user-facing, and add a PodDisruptionBudget.
  • Downstream limits. Scaling the API to 30 pods can overwhelm a database with connections. Use connection pooling and set maxReplicas with downstream capacity in mind.
  • No load testing. Run a load test and watch kubectl get hpa -w and kubectl describe hpa, which shows current metrics and every scaling decision with its reason.

Frequently Asked Questions

How does the Kubernetes Horizontal Pod Autoscaler work?

Every 15 seconds by default, it reads a metric such as average CPU utilization, computes desired replicas as current replicas times the ratio of the current value to the target, and updates the workload’s replica count within the configured minimum and maximum.

Why is my HPA not scaling down?

By default, scale-down waits for a five-minute stabilization window and uses the highest recommendation within it. Other causes include memory-based metrics that never drop and minReplicas set too high. kubectl describe hpa shows the current metrics and decisions.

Why does my HPA show unknown for CPU?

Usually the metrics-server is missing or unhealthy, or the target pods have no CPU requests, which utilization is calculated against. Install metrics-server and set CPU requests on every container.

Can the HPA scale to zero?

Not on its own; minReplicas must be at least 1 in standard configurations. KEDA can scale workloads to zero and back based on event sources such as queue length.

Scale on the signal that matters

The HPA is a straightforward controller fed by inputs that need care: accurate requests, a metric that tracks real load, readiness that reflects real readiness, and nodes to put pods on. Get those right, tune behavior to your traffic shape, and load test before the traffic test happens in production. For the full reference, see the Horizontal Pod Autoscaler documentation and the KEDA project. Related reading on this site: observability.

Originally posted on 7 May 2024 and post last modified on 7 May 2024

Autoscaling DevOps Kubernetes Scalability

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *