Introduction

Kubernetes HPA v2 is the autoscaling/v2 API for the Horizontal Pod Autoscaler, and it changes replica counts from observed metrics rather than from a schedule or a human guess. It supports several metrics at once, per-direction scaling policies, and stabilization windows that stop replica counts from flapping.

The previous lesson, PromQL for Kubernetes SREs, built the signals: throttling ratios, memory headroom and restart counts. This lesson, in Module 11 on Kubernetes autoscaling, turns signals into replica decisions. The companion pillar, HPA vs VPA in Kubernetes, covers choosing between horizontal and vertical scaling; this tutorial assumes you picked horizontal scaling and now need it configured correctly.

Consider an illustrative composite drawn from common production reviews, not a named incident. A checkout API runs four replicas with an HPA target of 50 percent CPU. Traffic doubles during a campaign, CPU climbs to 80 percent, and the HPA does nothing, because the Pods define no CPU requests and the target shows as unknown. An engineer adds requests during the incident, the HPA jumps straight to its maximum, and two hours later it removes replicas in bursts that drop in-flight requests. Three failures, one missing prerequisite, and behaviour fields nobody had set.

The 5-minute takeaway

Requests come first, because utilization targets are percentages of requests. CPU is the default signal; memory works only when usage follows load. Custom and external metrics beat CPU when queues or request rates describe load better. Scale-up should react fast, scale-down should wait. maxReplicas is a cost and capacity decision, not a formality. Every HPA gets watched with kubectl describe hpa until its events stay boring.


1. Kubernetes HPA v2: the control loop and the replica formula

Kubernetes HPA v2 runs a control loop in the controller manager, roughly every 15 seconds, that reads metrics, computes a desired replica count per metric, and applies the largest result inside your limits. The formula is desiredReplicas equals ceil of currentReplicas multiplied by currentMetric divided by targetMetric.

Work the arithmetic once and the behaviour stops surprising you. Four replicas at 75 percent average CPU against a 50 percent target give ceil(4 x 75 / 50), which is 6 replicas. Two replicas at 30 percent against the same target give ceil(2 x 30 / 50), which is 2, so nothing changes. The ceiling function means the controller rounds up, never down, when the ratio sits between whole replicas.

A tolerance band keeps the loop calm. When the computed ratio sits within 10 percent of the target, the HPA leaves replicas alone instead of chasing noise. That band is why a service can sit at 54 percent against a 50 percent target without scaling. It is also why very small replica counts scale coarsely: moving from 2 to 3 replicas is a 50 percent capacity step, so small services feel every change.

With several metrics configured, the controller computes a desired count for each one and takes the maximum. CPU might ask for 5 replicas while a queue metric asks for 9; the HPA scales to 9. There is no averaging and no voting. Adding a metric can only raise the desired count, never lower it below what another metric requested, so every metric you add needs a target you trust.

The loop writes spec.replicas on the scale target through the scale subresource. That has one operational consequence teams miss: the Deployment manifest in Git should omit spec.replicas, or every apply resets the count the HPA just chose. GitOps tools need the same care, ignoring the replicas field on HPA-managed workloads so sync does not fight the controller.


2. Kubernetes HPA v2: prerequisites are requests and metrics-server

Kubernetes HPA v2 needs two prerequisites before any target works: resource requests on every container it measures, and a metrics pipeline that serves the resource metrics API. Without requests, utilization has no denominator. Without metrics-server or an equivalent provider, the controller has nothing to read.

Utilization is usage divided by request, summed across containers and averaged across Pods. A container using 250m CPU with a 500m request sits at 50 percent. Remove the request and the same container reports unknown, and the HPA event log fills with FailedGetResourceMetric warnings while replicas stay frozen. Requests are not paperwork here; they are the unit the whole calculation stands on.

metrics-server scrapes kubelets and serves the metrics.k8s.io API that kubectl top also uses. Verify it before writing any HPA: kubectl top pods should return numbers, and kubectl get apiservice v1beta1.metrics.k8s.io should show Available as True. On managed clusters metrics-server usually arrives preinstalled, but preinstalled is a claim to check, not a fact to assume during an incident.

bash
kubectl top pods -n production
kubectl get apiservice v1beta1.metrics.k8s.io
kubectl describe hpa checkout-api -n production

Requests also decide scheduling, so HPA work and capacity work are the same conversation. Requests set far above real usage make utilization look low and delay scale-up; requests set too low make utilization look high and trigger scale-up that mostly adds idle Pods. Size requests from observed usage, the same evidence the PromQL lesson produced, and revisit them after the first week of HPA data. The kubectl inspection commands used throughout this tutorial are covered in the kubectl master guide in this series.


3. Kubernetes HPA v2: CPU targets that survive real traffic

Kubernetes HPA v2 CPU scaling uses a Resource metric with a Utilization target, expressed as averageUtilization against the CPU request. Start near 60 to 70 percent for latency-sensitive services, then tune from load-test and production data rather than copying a number from a blog post, including this one.

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: checkout-api
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout-api
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 65

The target is a trade between headroom and cost. A 50 percent target keeps half the requested CPU spare on every Pod, which absorbs bursts while new Pods start, and costs roughly double the replicas of a 100 percent target. A 90 percent target packs Pods tightly and leaves almost nothing for the traffic spike that arrives while replacements are still pulling images. Latency budgets decide: graph p99 latency against utilization during a load test, find where latency bends, and set the target below that point with margin for Pod startup time.

Startup time is the hidden variable. The HPA reacts in seconds, but a Pod takes as long as image pull, init containers, runtime warm-up and readiness probes take. If that chain runs 90 seconds, the existing Pods must absorb 90 seconds of growth alone. Services with slow starts need lower targets or higher minimum replicas, and no target value fixes a five-minute image pull. Measure time-to-ready and treat it as part of the scaling budget.

CPU targets assume CPU tracks load. For services whose bottleneck sits in a database, a downstream API or a lock, CPU stays calm while latency climbs, and the HPA correctly does nothing about the wrong signal. Section 6 covers metrics that describe those workloads better. CPU remains the right first metric for stateless compute-bound services, which is most web APIs, and the wrong only metric for everything else.


4. Kubernetes HPA v2: memory targets need a workload that releases memory

Kubernetes HPA v2 memory scaling uses the same Resource metric shape with name memory, and it works only when memory usage rises and falls with load. Heap-heavy runtimes keep memory after traffic drops, so memory targets scale those services up and then refuse to scale them down.

yaml
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 75

The failure mode is mechanical. A JVM or Go service grows its heap under load, garbage collection returns pages to the runtime rather than to the operating system promptly, and working set stays high after traffic leaves. The HPA reads sustained high utilization and holds replicas. Nothing is broken; the metric simply does not mean what the target assumes. Memory scaling fits workloads whose memory genuinely tracks concurrency, such as some cache-fronted or batch-processing services, and misfits long-lived heap services.

Where memory belongs for most teams is a guardrail, not a driver. A memory target set high, around 80 to 85 percent, acts as a safety valve that adds replicas before OOM kills start, while CPU or a custom metric does the everyday scaling. Because the controller takes the maximum across metrics, a high memory target only wins when memory pressure is real. The OOMKilled troubleshooting guide covers the kill this guardrail exists to prevent.

Watch the interaction with limits. Utilization divides by the request, but the kernel enforces the limit. A container with a 512Mi request and a 512Mi limit at 80 percent utilization sits close to an OOM kill on the next allocation spike, and the HPA needs minutes to add capacity that helps. Memory requests equal to limits give predictable behaviour for memory-critical services, at the cost of tighter node packing. That trade belongs in platform standards; the HPA target then reads honestly against it.


5. Kubernetes HPA v2: multiple metrics, and the maximum wins

Kubernetes HPA v2 evaluates every configured metric independently and scales to the largest desired count, so metric selection is really a decision about which signal may demand capacity. Add metrics that each describe a real saturation path, and give every one a target you would defend in an incident review.

Metric type Source Example signal Target type
Resource metrics-server CPU or memory utilization Utilization or AverageValue
Pods custom metrics API requests per second per Pod AverageValue
Object custom metrics API requests per second on an Ingress Value or AverageValue
External external metrics API queue depth in SQS or Pub/Sub AverageValue

The maximum rule cuts both ways. A stale or noisy metric with an aggressive target pins the service at maxReplicas while CPU sits idle, and the event log shows the winning metric only if you read it. When replicas look wrong, kubectl describe hpa prints each metric's current value against its target, which names the metric that asked for the current count. Make that the first command, not the last.

Target types matter per metric. Utilization suits Resource metrics because requests define the denominator. AverageValue suits Pods metrics, where the controller divides the metric total by replica count and compares against your per-Pod target. Value suits Object metrics tied to one object. External metrics usually use AverageValue so queue depth spreads across replicas: 1,000 messages with an AverageValue target of 50 asks for 20 replicas.

Keep the metric set small. Two or three signals that fail independently beat six correlated ones, because correlated metrics add tuning surface without adding information. A typical production set is CPU utilization plus one application signal such as request rate or queue depth, with memory as the high guardrail from section 4. Every additional metric should answer a saturation question the others cannot.


6. Kubernetes HPA v2: custom metrics through Prometheus Adapter

Kubernetes HPA v2 custom metrics come from the custom.metrics.k8s.io API, most commonly served by Prometheus Adapter translating PromQL into metric values. Pods metrics describe per-Pod signals such as request rate; Object metrics describe one named object such as an Ingress. Both need the adapter configured before the HPA can read them.

The pipeline has three links, and each one fails differently. The application exposes a metric, Prometheus scrapes it, and the adapter maps a PromQL query to a custom metric name with the right label handling. The HPA then reads that name. When scaling misbehaves, test the links in order: query Prometheus directly, then query the custom metrics API with kubectl get --raw, then read the HPA events. Guessing which link broke wastes the incident.

yaml
    - type: Pods
      pods:
        metric:
          name: http_requests_per_second
        target:
          type: AverageValue
          averageValue: "50"

AverageValue divides the summed metric by the current replica count, so a target of 50 requests per second per Pod asks for 8 replicas at 400 requests per second total. Choose per-Pod targets from load tests that found where one Pod's latency bends, exactly as with CPU targets. A request-rate target copied from another service encodes that service's Pod size, not yours.

Metric naming and label discipline decide whether this stays maintainable. The adapter rule should expose one clear metric name per signal, aggregate away labels the HPA does not need, and keep the query cheap enough to run every sync period. The observability stack lesson covers running Prometheus for this pipeline; the adapter is a consumer of that stack, not a replacement for it.

One caution on latency metrics. Scaling on p99 latency sounds precise and behaves badly, because latency is an outcome with many causes, and adding replicas to a database-bound service can worsen the latency that triggered the scale-up. Prefer leading signals that measure offered load, such as request rate, in-flight requests or queue depth, and keep latency as the alert that tells you scaling is not working.


7. Kubernetes HPA v2: external metrics and the KEDA boundary

Kubernetes HPA v2 external metrics come from outside the cluster through the external.metrics.k8s.io API, typically queue depth or backlog size from a cloud service. They suit worker fleets where work waits in a queue and CPU says little about how much capacity the backlog needs.

yaml
    - type: External
      external:
        metric:
          name: sqs_queue_depth
          selector:
            matchLabels:
              queue: checkout-jobs
        target:
          type: AverageValue
          averageValue: "30"

An AverageValue target of 30 messages per replica turns a 900-message backlog into 30 replicas, then relaxes as workers drain the queue. The selector picks which queue the metric describes when one provider serves several. External metrics need a provider that polls the cloud API and serves the external metrics API; KEDA is the common choice, and it also adds event-driven scaling triggers and scale-to-zero, which native HPA cannot do because minReplicas stops at 1 in practice for most setups.

The boundary decision is simple. Use native HPA external metrics when an adapter already serves your queue signal and scale-to-zero does not matter. Use KEDA when you need its trigger catalogue, cron or event sources, or scaling to zero for batch workers. Running both against the same workload invites two controllers writing replicas, so pick one owner per workload and write the choice in the runbook.

Queue metrics have a lag problem worth respecting. Depth rises after producers surge, workers take time to start, and depth falls only as fast as jobs complete. Aggressive targets overshoot into replica counts the downstream database cannot serve. Cap maxReplicas from downstream capacity, not from optimism, and let the queue absorb short bursts; that buffering is what the queue exists for.


8. Kubernetes HPA v2: scale-up policies cap the rate of growth

Kubernetes HPA v2 behaviour policies limit how fast replicas may change in each direction, using Percent or Pods limits per period. Scale-up policies protect downstream systems and node capacity from a metric spike that asks for ten times the replicas in one sync period.

yaml
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 60
        - type: Pods
          value: 4
          periodSeconds: 60
      selectPolicy: Max

With selectPolicy Max, the controller applies whichever policy allows the larger change; Min applies the smaller, and Disabled turns the direction off. The example allows doubling every minute or adding four Pods per minute, whichever is larger. For a service at 3 replicas, the Pods policy wins and growth stays measured. For a service at 40 replicas, the Percent policy allows 40 more, which may be exactly what a genuine traffic surge needs.

Defaults already exist: scale-up allows the larger of 100 percent or 4 Pods per 15 seconds, with no stabilization window. Writing the policies explicitly still pays, because the next engineer reads intent instead of recalling defaults, and because services with fragile downstreams usually need slower growth than the default allows. A database that tolerates 50 new connections per minute sets the real scale-up budget.

Scale-up speed also interacts with node capacity. Replicas the cluster cannot schedule sit Pending, and Pending Pods do not serve traffic. Pod scaling and node scaling run as separate loops with separate delays, so pair replica decisions with node capacity planning; Karpenter vs Cluster Autoscaler compares the node-layer options. Size maxReplicas and node headroom together, or the HPA writes cheques the scheduler cannot cash.


9. Kubernetes HPA v2: scale-down stabilization stops flapping

Kubernetes HPA v2 scale-down uses a stabilization window that holds the highest recommended replica count from the recent past before removing Pods. The default window is 300 seconds, and pairing it with a slow Pods policy turns scale-down from a cliff into a ramp that in-flight work survives.

yaml
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Pods
          value: 1
          periodSeconds: 60

Flapping is the failure this prevents. Traffic dips for ninety seconds, the controller removes three Pods, traffic returns, and the service spends the next minutes cold-starting replacements while latency climbs. The stabilization window ignores dips shorter than five minutes, and the Pods policy removes one replica per minute after that. Cost falls slightly slower; reliability rises a lot. For most services that trade is correct, and the savings from aggressive scale-down rarely survive contact with the first retry storm.

Scale-down also needs cooperation from the workload. Pods removed by the HPA go through normal termination: readiness drops, endpoints drain, and the process gets its termination grace period. Services that ignore SIGTERM or hold long-lived connections without draining turn every scale-down into dropped requests. Set terminationGracePeriodSeconds from real drain time, and make preStop hooks wait for load balancer deregistration where your platform needs it.

Tune the window from traffic shape. Services with sharp daily cliffs can use shorter windows once the cliff passes; services behind retry-heavy clients should keep long windows because client retries manufacture the load that scale-down just removed capacity for. Watch replica graphs for a week before shortening anything. A sawtooth replica graph is the signature of a window set too short.


10. Kubernetes HPA v2: min and max replicas are capacity decisions

Kubernetes HPA v2 minReplicas and maxReplicas bound every calculation, and both numbers encode decisions about availability, cost and downstream capacity. minReplicas should cover an availability zone loss or a node failure at baseline load. maxReplicas should stop at the point where dependencies, quotas or budget say no.

Minimum replicas interact with PodDisruptionBudgets and topology spread. Three replicas spread across zones survive one zone failing; two replicas in one zone do not survive much. Set the minimum from the failure you intend to absorb at 3 a.m. without paging anyone, then let the HPA handle variation above that floor. A minimum of 1 for a user-facing service is a cost decision wearing an availability costume.

Maximum replicas need three checks. First, downstream capacity: database connections, downstream rate limits and connection pools per Pod multiplied by maxReplicas must stay inside what dependencies tolerate. Second, namespace quotas: ResourceQuota caps total requests, and an HPA that hits the quota leaves Pods Pending with FailedCreate events; the ResourceQuota and LimitRange lesson covers sizing quotas with autoscaling in mind. Third, node capacity: the cluster must be able to schedule maxReplicas during the same surge that triggers them.

Cost review belongs in the same conversation. maxReplicas multiplied by per-Pod requests is the worst-case hourly footprint of the service, and finance deserves that number before the campaign, not after it. Alert when replicas sit at maximum for sustained periods; that alert means either demand outgrew the plan or a metric is lying, and both deserve a human.


11. Kubernetes HPA v2: troubleshooting unknown metrics and stuck replicas

Kubernetes HPA v2 troubleshooting starts with kubectl describe hpa, because its events name the failing metric, the target and the controller's reasoning. Unknown targets mean missing requests or a broken metrics pipeline. Stuck replicas mean a metric, a policy or a quota is holding the count where it is.

Symptom First check Likely cause Fix direction
TARGETS shows unknown kubectl top pods, Pod requests Missing requests or metrics-server down Add requests; repair metrics pipeline
Replicas never rise describe hpa metric values Metric under target, or wrong signal Check utilization math; pick a load-tracking metric
Replicas pinned at max describe hpa winning metric Noisy metric or target too low Raise target; fix the metric source
Replica count sawtooths Replica graph vs traffic Scale-down window too short Lengthen stabilization; slow Pods policy
Pods Pending at scale-up Events on Pending Pods Quota, node capacity or requests too large Raise quota or capacity; rightsize requests
HPA fights GitOps sync Deployment diff on replicas Manifest sets spec.replicas Remove replicas from Git; ignore the field

Two checks settle most arguments. First, compute utilization by hand: kubectl top pod gives usage, the Pod spec gives requests, and the division should roughly match the HPA target display. When hand math and controller math disagree, a container without requests or a sidecar with large requests is usually distorting the average. Second, read the ScalingReplicaSet and FailedGetResourceMetric events with timestamps; they separate a metric problem from a policy problem in one screen.

Remember what the HPA cannot see. It does not know Pods are Pending, nodes are full, or the database is saturated; it knows metrics and limits. Pair HPA events with Pod phase and node signals before concluding the autoscaler misbehaved. The surrounding platform habits in the Kubernetes best practices guide in this series keep autoscaling boring.


12. Kubernetes HPA v2: production checklist and tuning loop

Kubernetes HPA v2 production tuning is a loop, not a one-time manifest: set requests from usage, pick targets from latency data, bound replicas from dependency capacity, then watch events and replica graphs until scaling decisions look dull. The checklist below turns this tutorial into that review.

Review point Healthy sign Warning sign
Requests Match observed usage per container Unknown targets or chronic over-requesting
CPU target Set from latency bend in load tests Copied default with no data
Memory metric Guardrail target or absent Primary signal on heap-heavy service
Custom metric Tracks offered load, cheap query Latency metric driving scale-up
Scale-down Smooth ramp after traffic falls Sawtooth replica graph
maxReplicas Inside quota and downstream limits Pending Pods during surges

Production checklist

  • Every container in the scale target defines CPU and memory requests sized from observed usage.
  • kubectl top works and the metrics API reports Available before the HPA is trusted.
  • CPU target comes from load-test latency data, with margin for Pod startup time.
  • Memory is a high guardrail or absent, never the primary signal for heap-heavy services.
  • Custom metrics track offered load such as request rate or queue depth, with adapter queries tested end to end.
  • Scale-up policies respect downstream connection and rate budgets; scale-down uses a stabilization window and a slow Pods policy.
  • minReplicas absorbs a zone or node loss; maxReplicas fits quota, node capacity and the cost ceiling.
  • The Deployment manifest omits spec.replicas so GitOps sync and the HPA stop fighting.
  • Alerts fire on sustained maxReplicas and on FailedGetResourceMetric events, with describe hpa output in the runbook.

Autoscaling rewards the same discipline as the monitoring lesson before it: honest units, bounded behaviour, and evidence before tuning. A Kubernetes HPA v2 setup that scales a little late and a little slowly, inside limits everyone agreed on, beats an eager one that discovers downstream limits during a campaign. From here, Module 11 on Kubernetes autoscaling continues to the node layer, because replica decisions only help when nodes arrive to run them.

Frequently Asked Questions

What does Kubernetes HPA v2 need before it can scale on CPU?

Kubernetes HPA v2 needs CPU requests on every container and a working metrics pipeline, usually metrics-server. Utilization is usage divided by request, so a missing request produces an unknown target and no scaling. Verify with kubectl top pods and kubectl describe hpa before trusting any target value.

How does Kubernetes HPA v2 calculate desired replicas?

Kubernetes HPA v2 computes ceil(currentReplicas x currentMetric / targetMetric) for each configured metric, applies a 10 percent tolerance band, then takes the largest result across metrics. Behaviour policies and min/max limits bound the final number before the controller writes spec.replicas on the target.

Should Kubernetes HPA v2 scale on memory?

Kubernetes HPA v2 should scale on memory only when memory usage rises and falls with load. Heap-heavy runtimes retain memory after traffic drops, so memory targets hold replicas high. For most services, keep memory as a high guardrail around 80 to 85 percent and let CPU or a load metric drive scaling.

How do I stop Kubernetes HPA v2 from flapping?

Kubernetes HPA v2 flapping stops with scale-down stabilization. Keep stabilizationWindowSeconds at 300 or higher and remove Pods slowly with a Pods policy such as one per minute. Scale-up can stay responsive with stabilizationWindowSeconds 0, because fast growth and slow shrink match how traffic actually behaves.

How do custom metrics work in Kubernetes HPA v2?

Kubernetes HPA v2 reads custom metrics from the custom.metrics.k8s.io API, usually served by Prometheus Adapter. A Pods metric with an AverageValue target divides the metric total by replica count, so 400 requests per second against a target of 50 asks for 8 replicas.

Why does Kubernetes HPA v2 show unknown in TARGETS?

Kubernetes HPA v2 shows unknown when the controller cannot fetch a metric or cannot compute utilization. The usual causes are containers without resource requests, metrics-server unavailable, or an adapter rule that does not match the metric name. kubectl describe hpa events name the failing metric directly.

What is the difference between Kubernetes HPA v2 and KEDA?

Kubernetes HPA v2 is the built-in autoscaler for resource, custom and external metrics with a minimum of one replica in practice. KEDA adds event-driven triggers, many external sources and scale-to-zero, and it manages an HPA underneath. Pick one owner per workload to avoid two controllers writing replicas.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →