Skip to content

Horizontal Pod Autoscaler — scaling on metrics that matter

Configure HPA correctly — metrics-server, CPU/memory targets, custom metrics from Prometheus, behavior tuning, and the requests/limits mistake that nullifies it.

The Horizontal Pod Autoscaler (HPA) adds and removes Pods based on observed metrics. The basic case is “scale by CPU”; the more useful case is “scale by request rate” or “scale by queue depth.” This article gets you to a working HPA — metrics-server installed and healthy, an HPA that actually scales, custom Prometheus metrics for the realistic use case, and the resource-requests detail that quietly breaks CPU-based scaling when set wrong.

How to verify

What the cluster knows about scaling:

kubectl get apiservices | grep metrics
kubectl top nodes
kubectl top pods -A
kubectl get hpa -A

The v1beta1.metrics.k8s.io APIService should be True/Available. kubectl top fails if metrics-server is missing or misconfigured — fix that before HPA. get hpa shows the current/target metrics and the current replica count.

For one HPA, describe shows the recent scaling events and any errors fetching metrics:

kubectl describe hpa web -n team-payments
kubectl get events -n team-payments --field-selector involvedObject.name=web

What’s happening

HPA is a controller that polls the metrics API every 15 seconds (configurable), compares observed metrics to targets, and updates the target Deployment’s replicas field. The math is straightforward: desiredReplicas = ceil(currentReplicas * (currentMetric / targetMetric)). There’s a stabilization window to prevent thrashing.

HPA reads from three metrics APIs:

  • metrics.k8s.io — CPU and memory, served by metrics-server.
  • custom.metrics.k8s.io — anything else namespaced (requests per second per Pod), served by an adapter (Prometheus Adapter, KEDA).
  • external.metrics.k8s.io — non-Pod metrics (SQS queue depth, Pub/Sub backlog), again via an adapter.

For CPU autoscaling to work, the target Deployment must have CPU requests set. The HPA computes utilization as usage / requests. With no requests, utilization is undefined and the HPA gives up. This is the most common reason an HPA never scales.

The behavior field added in autoscaling/v2 tunes scaling speed: scaleUp and scaleDown policies with a stabilization window and policy ladders. Out of the box, scale-up is aggressive and scale-down is slow (5-minute stabilization); for short-lived traffic spikes you may want to slow scale-up too.

The procedure

  1. Install metrics-server if it’s not already in the cluster. On managed Kubernetes it usually is; on kubeadm you install it:

    kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
    kubectl -n kube-system rollout status deployment/metrics-server
    kubectl top nodes

    If top fails with x509, add --kubelet-insecure-tls to the metrics-server args (lab clusters with self-signed kubelet certs). In production, fix the certs, don’t disable the check.

  2. Set CPU requests on the target Deployment. Without this, HPA cannot compute utilization.

    spec:
      template:
        spec:
          containers:
            - name: web
              image: registry.example.com/web:1.4.2
              resources:
                requests:
                  cpu: "200m"
                  memory: "256Mi"
                limits:
                  memory: "512Mi"
  3. Create a CPU-based HPA. Target 60% utilization, between 3 and 20 replicas:

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: web
      namespace: team-payments
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: web
      minReplicas: 3
      maxReplicas: 20
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 60
  4. Tune behavior so scale-up is steady and scale-down is conservative. The defaults are often too aggressive on the way up and too slow on the way down for human-facing services:

    spec:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 30
          policies:
            - type: Percent
              value: 50
              periodSeconds: 60
            - type: Pods
              value: 4
              periodSeconds: 60
          selectPolicy: Max
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
            - type: Percent
              value: 20
              periodSeconds: 60
  5. Scale on a custom metric — requests per second per Pod, served by Prometheus Adapter. Install the adapter, configure a rule that exposes http_requests_per_second as a Pod metric, then:

    metrics:
      - type: Pods
        pods:
          metric:
            name: http_requests_per_second
          target:
            type: AverageValue
            averageValue: 100   # target 100 rps per Pod
  6. Scale on an external metric — useful for queue workers. With the AWS SQS external metrics adapter, the HPA scales a worker Deployment to keep the queue drained:

    metrics:
      - type: External
        external:
          metric:
            name: sqs-approximate-number-of-messages
            selector:
              matchLabels: { queue: orders }
          target:
            type: AverageValue
            averageValue: 30
  7. Confirm it scales by generating load (or watching real traffic):

    kubectl run -n team-payments load --rm -it --image=busybox -- \
      sh -c 'while true; do wget -q -O- http://web:80 >/dev/null; done'
    watch -n 5 'kubectl get hpa web -n team-payments && kubectl get pods -n team-payments -l app=web'

Common pitfalls

  • No CPU requests on the Deployment means CPU-based HPA does nothing — the HPA’s status shows <unknown> for the current metric.
  • HPA and Vertical Pod Autoscaler (VPA) in “Auto” mode fight each other on CPU/memory — pick one per resource, or use VPA only in “Off” recommendation mode for HPA-targeted Deployments.
  • A single noisy Pod can pull the average up and trigger unnecessary scaling — kubectl top pods shows distribution; if utilization is bimodal, the average target hides real behaviour.
  • scaleTargetRef to a Deployment that doesn’t exist will leave the HPA stuck — describe hpa shows failed to get scale target; the HPA controller silently retries.
  • Prometheus Adapter rules without enough labels (no namespace, no pod) won’t surface as Pod metrics — HPA needs the metric series keyed by Pod identity to work.

We operate HPA for clients on metrics that reflect the actual SLO — request rate, queue depth, p95 latency — not raw CPU, with behavior tuned per workload and load tests that prove the scaling curve. See /en/services/managed-operations/.