Amazon EKS — HPA — Horizontal Pod Autoscaler
Horizontal Pod Autoscaler (HPA)
HPA automatically scales the number of pod replicas based on CPU, memory, or custom metrics.
How HPA Works
HPA Control Loop (every 15 seconds)
┌─────────────────────────────────────────────────────┐
│ │
│ 1. HPA checks current metric value │
│ 2. Compares with target value │
│ 3. Calculates desired replicas: │
│ desired = ceil(current × (currentValue/target)) │
│ 4. Scales Deployment up or down │
│ │
│ Example: │
│ Current: 3 replicas at 80% CPU │
│ Target: 50% CPU │
│ Desired: ceil(3 × 80/50) = ceil(4.8) = 5 replicas │
│ │
└─────────────────────────────────────────────────────┘
Prerequisites: Metrics Server
# Check if metrics server is running
$ kubectl top nodes
# If "error: Metrics API not available", install it:
$ kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
Create HPA
CLI
$ kubectl autoscale deployment web --cpu-percent=50 --min=2 --max=20
YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # Wait 5 min before scaling down
scaleUp:
stabilizationWindowSeconds: 0 # Scale up immediately
Monitor HPA
$ kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
web-hpa Deployment/web 35%/50%, 40%/70% 2 20 3
$ kubectl describe hpa web-hpa
Common Mistakes
| Mistake | Impact |
|---|---|
| No resource requests on pods | HPA can’t calculate utilization percentage |
| Too low min replicas | Slow scale-up during sudden traffic |
| No scale-down stabilization | Flapping (scale up/down repeatedly) |
| Metrics Server not installed | HPA shows <unknown> for metrics |
What’s Next?
Right-size pods: VPA.