Autoscaling: HPA arithmetic, stabilization, custom metrics, VPA, and cluster autoscaler

Three autoscalers on three axes: HPA changes replicas from a metric, VPA changes requests, Cluster Autoscaler changes nodes. HPA and VPA on the same metric fight.

Read the briefing
About 3 min to read 7 drills

What to remember

  1. HPA = replicas, VPA = requests, CA = nodes. Say which axis you mean and the confusion disappears.
  2. HPA utilisation is measured against requests. Wrong requests make the HPA scale on a fiction.
  3. HPA and VPA on the same metric oscillate. Use VPA in recommendation mode alongside an HPA, not both enforcing on CPU.
  4. The Cluster Autoscaler only reacts to Pending pods. It does not predict load, and node warm-up is minutes — that is your real floor.
  5. Scaling ceilings are quota and warm-up, not the policy. Which is why headroom and shedding matter more than the tuning.

The big picture

Kubernetes has three autoscalers that people conflate: the HorizontalPodAutoscaler changes replica counts from metrics, the VerticalPodAutoscaler changes requests and limits, and the Cluster Autoscaler adds and removes nodes when pods cannot schedule or nodes sit idle. They interact through requests: HPA scales pods, pods need requests, requests fill nodes, and the cluster autoscaler responds. Interviewers test whether you can predict what each one will do and why pods still sit Pending with autoscaling "on".

The mental model

Three feedback loops with three signals. HPA: desired = ceil(current × observed / target) on a metric, smoothed by stabilization windows. VPA: watch usage, recommend requests, optionally apply by evicting. Cluster Autoscaler: Pending pods that would fit a new node from a node group trigger scale-up; nodes whose pods can be moved elsewhere trigger scale-down. The loops only work if requests are honest.

In depth

HPA: the formula and the smoothing

Every 15 seconds the HPA controller reads the metric for the pods matching the target (CPU utilization is the ratio of usage to request, so CPU HPA without requests is meaningless) and computes desiredReplicas = ceil(currentReplicas × currentMetric / targetMetric). A 10% tolerance around 1.0 suppresses noise. Scale-up is fast by default; scale-down waits through a stabilization window (300 s default) and picks the highest recommendation seen in that window, which is why replicas ramp down slowly on purpose. behavior policies bound the rate (for example, at most 4 pods or 100% per 60 s).

Metrics come from three sources: Resource (CPU, memory via metrics-server), Pods/Object custom metrics (through an adapter such as prometheus-adapter), and External metrics (queue depth, request rate from a managed service). Memory-based HPA is usually wrong for JVMs and caches because usage does not fall when load does; scale on the thing that actually varies with load.

VPA and why it does not mix with HPA on the same metric

VPA observes container usage and produces a recommendation for requests (and limits, proportionally). In Off mode it only recommends, which is the safe way to right-size requests from real data. In Auto mode it evicts pods to apply new values, which means restarts; in-place resize is arriving but not universal. Running VPA and HPA on the same resource fights: HPA scales replicas because CPU per pod is high, VPA raises the request, utilization drops, HPA scales down, and so on. Use VPA for the resource HPA does not scale on, or VPA in recommendation mode only.

Cluster Autoscaler: what it can and cannot see

The cluster autoscaler watches for Pending pods with FailedScheduling and simulates whether a new node from one of its node groups would let them schedule; if yes, it scales that group up (a scale-up takes minutes, not seconds, because a node has to boot and join). It scales down nodes that are under-utilized and whose pods can be moved safely: pods with local storage, without a controller, or protected by a PDB it cannot satisfy block scale-down, and so does the annotation cluster-autoscaler.kubernetes.io/safe-to-evict: "false".

Pods stay Pending with the autoscaler enabled when: the node group is at its maximum, no node group can satisfy the pod's constraints (GPU, zone, taints, a request larger than any node), or the pod's requests exceed what a fresh node's allocatable offers. The event and the autoscaler's status ConfigMap say which. Over- provisioning (a low-priority "balloon" deployment that gets preempted on demand) buys headroom so scale-ups happen before real pods need them.

Myths and facts

Myth: HPA scales on actual CPU usage.

Fact: It scales on utilization relative to the container's CPU request; without requests, CPU HPA has no denominator.

Myth: With the cluster autoscaler enabled, pods never stay Pending.

Fact: They stay Pending when the node group is at max, when no group can satisfy the constraints, or when requests exceed a node's allocatable.

Myth: HPA and VPA can both manage CPU for the same Deployment.

Fact: They oscillate against each other; use VPA in recommendation mode or on a different resource.

Myth: Scaling down is instant when load drops.

Fact: The scale-down stabilization window (default 5 minutes) intentionally delays it to avoid flapping.

Myth: Memory is a good HPA metric.

Fact: Rarely: many runtimes hold memory after load falls, so the HPA never scales in.

How pros do it

  • Set CPU requests from observed p95 before enabling HPA; the formula divides by them.
  • Scale on the signal that tracks load (requests per second, queue depth) via custom or external metrics when CPU is a poor proxy.
  • Tune behavior: fast up, slow down; cap scale-up steps for services with expensive cold starts.
  • Run VPA in Off mode for recommendations; apply them through code review, not automatic eviction, for stateful or latency-critical pods.
  • Give the cluster autoscaler headroom: node group maximums above expected peak, an over-provisioning balloon, and PDBs that allow at least one disruption.

Questions people ask

Autoscaling is on and my pod is still Pending. Why?

One of three things: the node group is at its maximum, no node group satisfies the pod's constraints (GPU, zone, taint, a bound PVC's zone, a request larger than any node), or the autoscaler is in backoff after a failed scale-up. Read the pod's latest FailedScheduling event and the autoscaler's status; it simulates the same filters the scheduler uses. Say all three before picking one.

HPA shows <unknown>/50% for CPU. Why?

The HPA cannot get the metric: metrics-server is missing or unhealthy, the pods have no CPU requests (utilization has no denominator), or the pods are too new. kubectl describe hpa shows the condition and a FailedGetResourceMetric event.

Why did the HPA scale to the max and stay there after a spike?

Check the metric first: memory, or any signal that does not fall when load does, keeps utilization high forever. Then the target (is it realistic?) and the scale-down stabilization window, which holds the highest recommendation of the last five minutes on purpose.

How fast can I scale out?

Pods in seconds if capacity exists; nodes in minutes (boot, join, image pull). If you need node-level capacity in seconds, keep it warm: an over-provisioning balloon or a scheduled scale-up before a known event.

Can I autoscale to zero?

Not with a plain HPA: minReplicas cannot be below 1 unless the HPAScaleToZero feature gate is on (alpha, off by default), and then only on object or external metrics. KEDA is the practical answer for event-driven scale-to-zero; node groups can scale to zero if nothing pins them.

Further reading

Drills · 7

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

An HPA targets 60% CPU utilization. The Deployment has 4 replicas and average utilization is 150%. What does the HPA do on its next loop?

  1. ceil(4 × 150 / 60), computed from the ratio of current to target utilization. desiredReplicas = ceil(currentReplicas × currentMetric / targetMetric).
  2. It adds one replica per control-loop iteration until utilization is under 60%. The HPA jumps directly to the computed count (bounded by behavior policies), it does not step by one.
  3. It cannot scale because utilization above 100% means the metric is invalid. Utilization above 100% simply means usage exceeds requests; it is a normal input.
  4. It doubles the replicas because utilization is over 100%. There is no doubling rule; the ratio decides.
In short

The HPA jumps straight to ceil(current replicas × current utilization ÷ target); it does not add one pod at a time.

Why

The formula is the whole algorithm: scale replicas by the ratio of observed to target, round up, then apply tolerance, min/max, and behavior limits. Utilization is usage divided by request, which is why requests must be honest.

The common mistake

Saying it adds one replica per loop, or that 150% utilisation is impossible. Utilisation is usage divided by the request, so it can exceed 100%, and the HPA jumps straight to ceil(current × observed ÷ target), bounded only by min/max and the behavior policies.

Read the docs

2 Read the output

The cluster autoscaler is running and healthy. Why is the GPU pod still Pending, and what do you change?

$ kubectl describe pod worker-9f2 | tail -3
  Warning  FailedScheduling  2m  default-scheduler  0/8 nodes are available: 8 Insufficient nvidia.com/gpu.
$ kubectl -n kube-system get configmap cluster-autoscaler-status -o jsonpath='{.data.status}' | grep -A3 "NodeGroups"
# (status ConfigMap abridged to the node-group lines)
NodeGroups:
  Name:        general-pool   Health: Healthy (ready=8 ...)  ScaleUp: NoActivity  cloudProviderTarget=8 (minSize=3, maxSize=20)
  Name:        gpu-pool       Health: Healthy (ready=0 ...)  ScaleUp: NoActivity  cloudProviderTarget=0 (minSize=0, maxSize=0)
  1. The autoscaler only scales when CPU is exhausted. It simulates all scheduling constraints, including extended resources.
  2. The general pool has capacity; the scheduler is broken. General nodes have no GPUs; the filter is correct.
  3. GPU pods cannot be autoscaled. They can, given a GPU node group with headroom.
  4. The only node group that could satisfy nvidia.com/gpu has maxSize 0, so the autoscaler cannot add a GPU node; raise the gpu-pool maximum. Scale-up requires a node group whose template node would fit the pod; a max of 0 means no such node can be created.
In short

The gpu-pool node group has maxSize 0, so the autoscaler can never add a GPU node; raise that maximum.

Why

The autoscaler's status ConfigMap is the second thing to read after the pod's event. Scale-up happens only if some node group's template would let the pod schedule and that group is below its max; here the matching group is capped at zero.

The common mistake

Blaming the scheduler, or assuming the autoscaler only reacts to CPU. It simulates the same filters the scheduler uses, extended resources included; it just has no node group allowed to grow.

Read the docs

3 Pick the strongest answer

A team runs an HPA (CPU target 70%) and a VPA in Auto mode on the same Deployment, and replicas swing between 3 and 12 every few minutes. What is happening?

  1. The stabilization window is too long. A longer window dampens oscillation; it does not cause it.
  2. The two controllers fight: VPA raises CPU requests, utilization falls, HPA scales in; pods restart with new requests, utilization spikes, HPA scales out. Both act on the same signal with opposite levers; the documented guidance is not to combine them on CPU/memory.
  3. The Deployment lacks a PodDisruptionBudget. PDBs affect evictions, not HPA replica math.
  4. metrics-server is flapping and the HPA sees stale data. A metrics outage shows as , not as a regular oscillation.
In short

The HPA and the VPA are fighting each other on the same CPU signal; run the VPA in Off mode or on a different resource.

Why

VPA changes the denominator of the HPA's utilization while HPA changes the number of pods VPA observes; the loops chase each other. Use VPA in Off (recommendation) mode with HPA, or have them manage different resources.

Read the docs

4 Find what's broken

This API's replica count swings wildly and never scales in after traffic spikes. Which lines, and what do you change?

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 2
  maxReplicas: 40
  metrics:
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 15
---
# api Deployment container (excerpt)
resources:
  limits:
    cpu: "2"
    memory: 2Gi
In short

The three bad lines are the memory metric, the zero scale-down window with a 100% policy, and the missing requests.

What's broken
  • Line 15: Memory utilization does not fall when load falls for this runtime, so the HPA cannot scale in; and memory is not the resource that tracks request load here.
  • Line 21: A zero scale-down stabilization window with a 100%-per-15s policy lets the HPA halve replicas on a single quiet sample, causing thrash.
  • Line 29: The container sets limits but no requests, so Kubernetes silently copies the limits into the requests; every Utilization-type metric is then measured against 2 CPU / 2Gi that the workload never approaches, and the HPA scales far too late.
Why

Three classic HPA mistakes in one manifest: the wrong metric, no smoothing on scale-down, and requests silently defaulted to the limits, so the utilization ratio is miscalibrated. min/max (lines 10–11) are fine; a Percent policy (line 25) is fine when paired with a window.

Read the docs

5 Answer out loud

What is the difference between the HPA, the VPA and the cluster autoscaler? For each, as you would tell a new graduate: what it changes, what signal drives it, and the one mistake people make with it. Four to six sentences.

In short

A strong answer says HPA changes replica count, VPA changes requests, and Cluster Autoscaler changes nodes, each from its own signal.

What a strong answer does
  • mechanism: HPA formula and the request denominator; VPA recommends/evicts; CA simulates scheduling against node groups and respects PDBs and local storage on scale-down.
  • pitfalls: One per autoscaler: HPA without requests or on memory; VPA Auto with HPA; CA node group max or constraint mismatch.
  • communication: Three parallel sentences (changes / signal / pitfall), plain language.
Why

The signal-per-loop framing is what interviewers listen for; the pitfalls show operational experience.

The common mistake

Conflating them, or saying the cluster autoscaler predicts load. It only reacts to Pending pods, and a node takes minutes to arrive — which is why headroom matters more than tuning.

6 Scenario: what do you do next?

A token launch is expected at 18:00. Last time, the RPC gateway's HPA scaled from 6 to 60 pods in two minutes, 40 of them sat Pending for eight minutes while nodes booted, and p99 latency breached the SLO. The cluster autoscaler and HPA are both "correctly configured" according to the team.

Step 1. What is the actual failure, and what do you check first?

  1. Pod autoscaling outran node autoscaling: check node boot-to-Ready time, the node group's max and current size, and image pull time on new nodes. The mechanism is a latency mismatch between two loops; the numbers tell you how much headroom you need.
  2. Switch to VPA to make the existing pods bigger. VPA evicts pods to resize; during a spike that is an outage generator.
  3. Lower the HPA scale-up rate so pods trickle in. That preserves the SLO breach by scaling slower than demand.
  4. Raise the HPA maxReplicas to 120. More Pending pods, same node shortage.

Step 2. Node boot to Ready is 3–4 minutes; the group max is fine; image pulls add 60 s on a cold node. Mitigation for tonight?

  1. Set pod requests to zero so more pods fit per node. Dishonest requests overload nodes and make every loop lie.
  2. Pre-warm: scale the node group up ahead of 18:00 (or deploy an over-provisioning balloon deployment sized to the expected surge), pre-pull the image via a DaemonSet, and set HPA minReplicas higher for the launch window. Buys the minutes the node loop cannot deliver on demand; all reversible after the event.
  3. Disable the cluster autoscaler so it stops interfering. The autoscaler is not the problem; capacity arriving late is.
  4. Ask the marketing team to delay the launch. Sometimes right, but not before the engineering options are exhausted.

Step 3. Launch survives. Systemic fix?

  1. Permanent over-provisioning proportional to surge size, a scheduled scale-up for known events, image pre-pull on node join, and an alert on Pending-pod age during HPA scale-ups. Turns the manual pre-warm into a mechanism and detects the failure mode early.
  2. Buy bigger nodes. Bigger nodes boot just as slowly; the issue is timing.
  3. Replace the HPA with a cron that sets replicas. Loses reactive scaling for everything that is not a scheduled event.
In short

Pods scaled in seconds but nodes took minutes, so pre-warm nodes and images before the launch and then make that automatic.

Why

Two loops with different latencies: HPA reacts in seconds, nodes arrive in minutes. The standard tools are over-provisioning (a low-priority balloon that gets preempted), scheduled pre-scaling for known events, and image pre-pulling. Interviewers want the mismatch named, then reversible mitigations, then a mechanism.

Read the docs

7 Quick recall

Traffic dropped five minutes ago, nothing is wrong, and the HPA still shows the peak replica count. What is the default scale-down stabilization window that explains it?

In short

The default scale-down stabilization window is 300 seconds (5 minutes).

Accepted

300 · 300s · 300 seconds

Why

300 seconds: the HPA uses the highest recommendation from the last five minutes before scaling in, to avoid flapping.

Next lesson ConfigMaps, Secrets, Helm and Kustomize: update semantics, the subPath trap, rollouts and rollbacks
Drill · Autoscaling
0:00

Loading…