Operate and shipLesson 2 of 10
- Metrics, logs, events and traces, not reconciled
- Horizontal pod autoscaling, not reconciled
- Right-sizing and in-place resize, not reconciled
- A troubleshooting method, not reconciled
- kubectl debug and ephemeral containers, not reconciled
- Debugging from the node: crictl, journalctl and nsenter, not reconciled
- Upgrades and version skew, not reconciled
- etcd, backup and disaster recovery, not reconciled
- GitOps with Argo CD, not reconciled
- Progressive delivery, not reconciled
Horizontal pod autoscaling
The HorizontalPodAutoscaler changes a workload's replica count to hold a metric at a target. Learn its formula, the metrics it can use, how behavior and tolerance shape it, and why its targets read unknown.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
Reconcile, in 8 scenes
The loop
A HorizontalPodAutoscalerAn autoscaling/v2 object that names a scalable target, such as a Deployment, and the metrics to hold at a target value; the HPA controller in kube-controller-manager adjusts the target’s replica count to match. does not run anything itself. A control loop in kube-controller-manager visits every HPA every 15 seconds (--horizontal-pod-autoscaler-sync-period), reads the metrics it names, computes a replica count, and writes it to the target’s scale subresource. The Deployment controller then does the rest.
Anything that implements scale can be a target: Deployments, ReplicaSets, StatefulSets, and custom resources whose CRD enables the subresource. The scale subresource also reports the target’s label selector, which is how the HPA finds the pods to measure. DaemonSets have no replica count and cannot be autoscaled this way. The API is autoscaling/v2, GA since Kubernetes 1.23; v2beta2 was removed in 1.26, and the older autoscaling/v1, with its single targetCPUUtilizationPercentage field, still exists for CPU-only HPAs.
The computation is one ratio:
desiredReplicas = ceil(currentReplicas × currentMetricValue / desiredMetricValue)
Two pods each using 200% of their CPU request, against a 50% target, give ceil(2 × 200 / 50) = 8. The controller skips the change entirely when the ratio sits within the tolerance, 0.1 by default: anything between 0.9 and 1.1 counts as on target, so small wobbles in usage do not move replicas.
Several refinements keep the ratio honest:
- Not-ready pods and fresh pods. For CPU, the controller sets aside pods that are not ready, and pods still inside
--horizontal-pod-autoscaler-cpu-initialization-period(5 minutes by default) whose most recent sample was taken before they became ready. Startup CPU would otherwise trigger a scale-up the moment another pod arrives. - Missing metrics. A pod with no sample counts as using 100% of the target when the HPA is considering a scale-down, and 0% when considering a scale-up. Either way, the gap dampens the move rather than amplifying it.
- Several metrics. The controller computes a count for each metric and takes the largest: if CPU asks for 6 replicas and memory for 4, the HPA sets 6. If one metric cannot be read and the others suggest scaling down, it does not scale at all, because the unreadable metric might be the one that needs more pods.
- Rate limits. With no
behaviorfield, one scale-up step may at most double the replicas, or reach 4 if that is more, and scale-down waits for a 300-second stabilization window.
kubectl top pods -l app=web
NAME CPU(cores) MEMORY(bytes) web-896845567-nshlv 200m 24Mi web-896845567-pggpj 200m 24Mi
kubectl autoscale deployment web --cpu=50% --min=2 --max=10
horizontalpodautoscaler.autoscaling/web autoscaled
kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 200%/50% 2 10 2 0s
kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 100%/50% 2 10 4 15s
kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 50%/50% 2 10 8 45s
The first sync wanted 8 but could only double to 4, so the HPA’s ScalingLimited condition was briefly True. With the same total load spread over 4 pods, each used 100% of its request, and the next sync computed ceil(4 × 100 / 50) = 8. At 8 pods the ratio is 1.0 and the loop rests.
ExplainerHorizontal pod autoscaling
Total CPU the traffic needs, shared by the ready pods
Target CPU, as a percent of each pod's request
The cluster-wide default is 0.1. In Kubernetes 1.37 and later an HPA can set its own, per direction, under spec.behavior.
desiredReplicas = ceil(currentReplicas × currentUtilization / target)
= ceil(2 × 75% / 50%) = 3
300m of demand across 2 pods is 150m each, 75% of the 200m request. The next sync writes 3.
Pods Each box is one pod's 200m request, the fill its CPU use, the accent line the target; a dashed slot is room up to maxReplicas.
Ratio utilisation / target1.50 scale up
2 replicas, not synced
The HPA has not synced yet. It runs every 15 s; press Next sync to run it.
The HPA has not synced yet. It runs every 15 s; press Next sync to run it.
kubectl describe hpa reports three conditions that summarise the loop’s state. AbleToScale says whether the controller can read and write the target’s scale, and whether a stabilization window or policy is holding it back. ScalingActive says whether at least one metric could be computed; False is the condition behind <unknown> targets. ScalingLimited turns True when the computed count hit minReplicas, maxReplicas or a rate limit, which is the first thing to check when an HPA seems stuck at its maximum while load keeps rising.
Metric types
An autoscaling/v2 HPA lists one or more metrics. Each has a source type and a target type:
| Type | Measures | Target types |
|---|---|---|
Resource | CPU or memory of the whole pod, from metrics.k8s.io | Utilization (percent of request), AverageValue |
ContainerResource | CPU or memory of one named container, GA in 1.30 | Utilization, AverageValue |
Pods | A per-pod custom metric, such as requests per second | AverageValue |
Object | A metric describing one other object, such as an Ingress’s request rate | Value, AverageValue |
External | A metric from outside the cluster, such as queue depth | Value, AverageValue |
Utilization is measured against requests, summed over every container in the pod. If any container, a sidecar included, has no request for that resource, utilization is undefined and the HPA takes no action on that metric. ContainerResource avoids the problem, and also stops a busy sidecar from scaling the app.
Memory makes a weak primary metric. Many runtimes, the JVM among them, keep heap they have allocated rather than returning it to the kernel, so usage stays high after load drops and a memory-driven HPA rarely scales down. Use memory as a second metric that guards against exhaustion, next to CPU or a request-rate metric that falls when traffic does.
Pods, Object and External metrics come from the custom metrics (custom.metrics.k8s.io) and external metrics (external.metrics.k8s.io) APIs, which an adapter such as the Prometheus Adapter or KEDA serves.
Here is an HPA on CPU utilization and average memory, with behavior that is examined in the next two sections:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
- type: Resource
resource:
name: memory
target:
type: AverageValue
averageValue: 200Mi
behavior:
scaleUp:
tolerance: 0.05
scaleDown:
stabilizationWindowSeconds: 300
tolerance: 0.15
policies:
- type: Pods
value: 1
periodSeconds: 60
The other source types change only the metrics entries:
metrics:
- type: ContainerResource
containerResource:
name: cpu
container: web
target:
type: Utilization
averageUtilization: 60
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "50"
- type: External
external:
metric:
name: queue_messages_ready
selector:
matchLabels:
queue: orders
target:
type: AverageValue
averageValue: "30"
An External AverageValue divides the metric by the replica count, so 30 means “one replica per 30 waiting messages”. Value compares the raw metric with the target.
Scaling behavior
spec.behavior has a scaleUp and a scaleDown section. Each holds:
policies: limits of the form “at mostvaluepods” or “at mostvaluepercent” perperiodSeconds(up to 1800).selectPolicy:Maxpicks the policy allowing the biggest change,Minthe smallest, andDisabledturns that direction off.stabilizationWindowSeconds: the controller remembers its recommendations over this window and, for scale-down, uses the highest one in it; for scale-up, the lowest.
The defaults, applied once you set any part of behavior:
| Direction | Stabilization window | Policies |
|---|---|---|
scaleUp | 0 seconds | 100 percent or 4 pods per 15 seconds, selectPolicy: Max |
scaleDown | 300 seconds | 100 percent per 15 seconds |
The scale-down window is what stops flapping after a burst: load drops, the recommendation falls, but the controller keeps the highest recommendation of the last five minutes. If the recommendations over that window were 10, 8, 6 and 5, replicas stay at 10 until the 10 ages out of the window, then drop to 8, and so on. The example’s one-pod-per-minute policy then lets replicas drain slowly once the window passes. A scaleUp window does the opposite job, ignoring brief spikes, at the cost of slower reaction.
Tolerance
The default 10% tolerance suits most workloads, but it is symmetric and cluster-wide (--horizontal-pod-autoscaler-tolerance on kube-controller-manager). A large deployment at 200 replicas tolerates 20 pods’ worth of drift; a latency-sensitive service may want to add pods at 3% over target and remove them only at 15% under.
Per-HPA tolerance sets spec.behavior.scaleUp.tolerance and spec.behavior.scaleDown.tolerance separately. The HPAConfigurableTolerance feature was alpha in Kubernetes 1.33 and 1.34, beta but off by default in 1.35 and 1.36, and GA in 1.37. In the example above, the HPA scales up once usage is 5% over target and down only once it is 15% under: it adds pods sooner than the default 10% would and removes them later, so a small dip in load does not take away capacity that the next rise needs.
Scale to zero
An HPA normally keeps at least one replica, because Resource and Pods metrics need a pod to measure. In Kubernetes 1.37 the HPAScaleToZero feature is beta and on by default (it was alpha from 1.16 through 1.36), and minReplicas: 0 becomes valid on one condition: at least one metric is of type Object or External, a value that exists while no pod runs. The API server rejects minReplicas: 0 on an HPA with only Resource metrics.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: worker
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: worker
minReplicas: 0
maxReplicas: 20
metrics:
- type: External
external:
metric:
name: queue_messages_ready
selector:
matchLabels:
queue: orders
target:
type: AverageValue
averageValue: "30"
While the HPA holds the workload at zero, its ScaledToZero condition is True; when it scales back up, the condition turns False with reason NotScaledToZero. This is different from setting a target’s replicas to 0 by hand on an HPA with minReplicas of 1 or more: that pauses autoscaling, and ScalingActive goes False until you scale the target back up.
Unknown targets
<unknown> in the TARGETS column means the controller could not compute that metric, and kubectl describe hpa or the ScalingActive condition says why. There are three common causes.
No metrics pipeline. Without metrics-server, the metrics.k8s.io API does not exist. kubectl top fails too, which makes this the quickest cause to rule in or out. Managed clusters often leave metrics-server out; the observability lesson covers installing it.
kubectl top pods
error: Metrics API not available
kubectl autoscale deployment web --cpu=50% --min=2 --max=10
horizontalpodautoscaler.autoscaling/web autoscaled
kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: <unknown>/50% 2 10 2 30s
kubectl get hpa web -o jsonpath='{.status.conditions[?(@.type=="ScalingActive")].message}'
the HPA was unable to compute the replica count: failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)
metrics-server can also be installed and still unusable. The API server reaches it through an APIService, and kubectl get apiservice v1beta1.metrics.k8s.io shows AVAILABLE as False with a reason such as MissingEndpoints when its pod is not ready, or FailedDiscoveryCheck when the API server cannot connect to it, often a network policy or a firewall between the control plane and the pod. The same check works for an adapter’s v1beta1.custom.metrics.k8s.io or v1beta1.external.metrics.k8s.io APIService.
No request. Metrics flow, but a container has no request for the resource, so utilization has no denominator. The message names the container and pod:
kubectl get hpa api
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE api Deployment/api cpu: <unknown>/60% 2 10 2 45s
kubectl get hpa api -o jsonpath='{.status.conditions[?(@.type=="ScalingActive")].message}'
the HPA was unable to compute the replica count: failed to get cpu utilization: missing request for cpu in container api of Pod api-866fb7b976-l2n9f
An adapter that serves nothing. For Pods, Object and External metrics, the adapter must register its API group and actually return the series. A wrong metric name, a label selector that matches no series, or an adapter whose query returns no data all end as <unknown>. Query the API directly, for example kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_requests_per_second", to see what the HPA sees.
For a few seconds after an HPA or its pods are created, <unknown> is normal: there is no sample yet.
Event-driven scaling
KEDA (Kubernetes Event-driven Autoscaling) wraps this machinery for event sources: queues, streams, databases, cron schedules and Prometheus queries. A ScaledObject names a workload and one or more triggers. KEDA serves the trigger values through the external metrics API, creates and owns an HPA for the workload, and itself handles activation between zero and one replica, so scale-to-zero works on clusters where HPAScaleToZero is off.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: worker
spec:
scaleTargetRef:
name: worker
minReplicaCount: 0
maxReplicaCount: 20
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus.monitoring:9090
query: sum(rabbitmq_queue_messages_ready{queue="orders"})
threshold: "30"
Do not also write your own HPA for a workload that a ScaledObject targets; two HPAs on one target fight each other.
One owner for replicas
An HPA writes spec.replicas on its target. If your manifest also sets replicas, every kubectl apply or GitOps sync resets the count, and the HPA climbs back over the next minutes. Leave replicas out of manifests for autoscaled workloads, so only the HPA owns the field.
Removing the field is a migration, not a one-line change. With client-side apply, the last-applied annotation still lists replicas, so the next apply would delete the field and the Deployment would fall to its default of 1. Run kubectl apply edit-last-applied deployment/<name> and delete spec.replicas from the annotation first, then remove it from the manifest. With server-side apply, transfer ownership of the field to the HPA’s field manager as the server-side apply documentation describes.
The HPA also stops at the cluster’s edge. It creates pods; if no node has room, they stay Pending until a node autoscaler such as Cluster Autoscaler or Karpenter adds capacity. And it should not share a metric with the Vertical Pod Autoscaler: if both act on CPU, the VPA changes the request that the HPA’s utilization divides by, and the two chase each other. The next lesson covers how to pair them.
kubectl --context kind-kx create deployment php-apache --image=registry.k8s.io/hpa-example --port=80kubectl --context kind-kx set resources deployment php-apache --requests=cpu=200mkubectl --context kind-kx expose deployment php-apache --port=80kubectl --context kind-kx autoscale deployment php-apache --cpu=50% --min=1 --max=10kubectl --context kind-kx run load-generator --image=busybox:1.37 --restart=Never -- /bin/sh -c 'while sleep 0.01; do wget -q -O- http://php-apache; done'kubectl --context kind-kx get hpa php-apache --watchkubectl --context kind-kx delete pod load-generatorkubectl --context kind-kx describe hpa php-apache
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Needs metrics-server; the observability lesson installs it on kind. php-apache is the image from the kubernetes.io HPA walkthrough. After deleting the load generator, watch the 300-second scale-down window hold the replicas before they fall.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Write an autoscaling/v2 HPA on CPU, memory, custom or external metrics. (not yet met)
- Compute the desired replica count from the HPA formula and the tolerance. (not yet met)
- Tune scaling with behavior policies, stabilization windows and per-direction tolerance, GA in Kubernetes 1.37. (not yet met)
- Explain why an HPA shows unknown targets, and fix it. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 9 corrections
The notes said'In EKS, Metrics Server must be installed separately. It's not included by default.'
CorrectedStill not deployed by default, but it is available as the EKS community add-on metrics-server (console, API or eksctl), which EKS docs prefer over the manifest install; the add-on uses port 10251 to coexist with Fargate. Whether EKS Auto Mode deploys it was not confirmed.
Sourcedocs.aws.amazon.com/eks/latest/userguide/metrics-server.html
The notes said'Standard HPA has minimum 1 replica'
CorrectedHPAScaleToZero is beta and enabled by default in 1.37 (alpha 1.16 to 1.36). minReplicas: 0 is accepted only when at least one Object or External metric is configured; resource metrics cannot scale from zero. On EKS 1.31 to 1.36 the minimum is still 1.
The notes saidkubectl autoscale deployment myapp --cpu-percent=50 --min=2 --max=10
Correctedkubectl 1.34 added --cpu and --memory (percentage for utilization, quantity for average value) and deprecated --cpu-percent, which no longer appears in the reference. Use: kubectl autoscale deployment myapp --cpu=50% --min=2 --max=10.
Sourcekubernetes.io/docs/reference/kubectl/generated/kubectl_autoscale
The notes saidScaling algorithm tolerance not configurable
CorrectedPer-HPA tolerance in spec.behavior.scaleUp/scaleDown.tolerance (HPAConfigurableTolerance) was alpha in 1.33 to 1.34, beta but off by default in 1.35 to 1.36, and GA in 1.37. Without it the cluster-wide default is 0.1 (--horizontal-pod-autoscaler-tolerance).
The notes said'VPA… HPA and VPA can conflict'
CorrectedStill true when both act on the same CPU/memory metric. The VPA story has changed: in-place pod resize is GA in Kubernetes 1.35, VPA 1.6.0 (2026-02-12) promoted updateMode InPlaceOrRecreate to GA (falls back to eviction when in-place is impossible), and VPA 1.5 deprecated updateMode Auto. Latest VPA is 1.8.1.
The notes said'PodDisruptionBudgets affect scale-down… eviction is blocked until PDB allows'
CorrectedHPA scale-down only lowers spec.replicas and the ReplicaSet controller deletes pods directly; PDBs apply only to the Eviction API (drains, Cluster Autoscaler/Karpenter node removal), so they never block HPA scale-down. Workload controllers are not limited by PDBs.
Sourcekubernetes.io/docs/concepts/workloads/pods/disruptions
The notes said'Pods without CPU requests can't contribute to scaling decisions'
CorrectedStronger than stated: if any container in the pods (sidecars included) lacks a request for the resource, utilization is undefined and the HPA takes no action for that metric (FailedGetResourceMetric, 'missing request for cpu'). Use ContainerResource metrics to target one container.
Sourcekubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale
The notes saidStates the algorithm as 'desired = current x (current/target)'
CorrecteddesiredReplicas = ceil(currentReplicas x currentMetricValue / desiredMetricValue), skipped when the ratio is within the tolerance (default 0.1, configurable per HPA in 1.37), with special handling for missing metrics and not-ready pods and a default 300 s scale-down stabilization window.
Sourcekubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale#algorithm-details
The notes saidHPA behavior defaults implied
CorrectedDefaults: scale-down stabilization window 300s; scale-up has no stabilization and allows the larger of 100% or 4 pods per 15s; global tolerance 10%. Per-HPA tolerance in spec.behavior (HPAConfigurableTolerance) was alpha in 1.33, beta in 1.35 and GA in 1.37.
Sourcekubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale
- kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough
- kubernetes.io/docs/reference/kubectl/generated/kubectl_autoscale
- kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline
- kubernetes.io/docs/concepts/configuration/manage-resources-containers
- kubernetes.io/docs/concepts/workloads/autoscaling/vertical-pod-autoscale
- kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources
- github.com/kubernetes-sigs/metrics-server
- keda.sh/docs/latest/concepts/scaling-deployments
- github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler
Horizontal pod autoscaling
↓ ↑ step, 1 to 8 scene, Esc leave