Difficulty: Advanced
How does the Horizontal Pod Autoscaler (HPA) work in Kubernetes, what metrics can it use, and what are the common pitfalls?
The Horizontal Pod Autoscaler automatically changes the replica count of a Deployment or StatefulSet based on observed metrics. Every 15 seconds by default it reads current utilisation (usually CPU from Metrics Server), compares it with a target such as 70%, and computes desiredReplicas = ceil(currentReplicas × currentValue / targetValue), clamped between minReplicas and maxReplicas.
metrics.k8s.io API.ceil(4 × 140/70) = 8.scale subresource, and the Deployment creates or removes Pods.A tolerance of 10% avoids flapping on small changes, and by default scale-down waits for a 5-minute stabilization window so a short dip does not remove capacity.
| Type | Source | Example |
|---|---|---|
| Resource | Metrics Server | CPU at 70%, memory average |
| ContainerResource | Metrics Server | CPU of only the app container, ignoring sidecars |
| Pods | Custom metrics API (Prometheus Adapter) | Requests per second per Pod |
| Object | Custom metrics API | Requests per second on an Ingress |
| External | External metrics API | SQS or Kafka queue lag |
For event-driven workloads, KEDA is widely used. It plugs into the HPA as an external metrics provider and can also scale to zero, which plain HPA cannot do.
<unknown> targets.replicas: 3 and Argo CD reapplies it, it overrides the HPA. Remove replicas from the Deployment once an HPA owns it.minReplicas or a scheduled scaler, and make sure the Cluster Autoscaler or Karpenter can add nodes, otherwise new Pods just sit Pending.autoscaling/v2 lets you control scale velocity: for example allow doubling every 15 seconds on scale-up but remove at most 10% of Pods per minute on scale-down. This gives fast reaction to spikes and gentle recovery.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: checkout
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: checkout
minReplicas: 3
maxReplicas: 40
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # percent of the CPU request
behavior:
scaleUp:
policies:
- type: Percent
value: 100 # can double
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10 # shrink slowly
periodSeconds: 60
The Deployment's Pods must declare CPU requests. Scale-up is aggressive and scale-down is cautious, which suits bursty user traffic.
kubectl top pods -l app=checkout
kubectl get hpa checkout --watch
kubectl describe hpa checkout # shows events and why it did or did not scale
If TARGETS shows <unknown>, check that Metrics Server is running and that the Pods have resource requests.
Horizontal Pod Autoscaler, Metrics Server, Resource Requests, Scaling Behavior, KEDA