Implementing Horizontal Pod Autoscaling

1. Creating HPA

kubectl autoscale deploy web --min=2 --max=10 --cpu-percent=70
FlagEffect
--min / --maxReplica bounds
--cpu-percentTarget avg CPU utilization (% of request)

2. Creating HPA from YAML

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: web }
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: web }
  minReplicas: 2
  maxReplicas: 20
  metrics:
  - type: Resource
    resource: { name: cpu, target: { type: Utilization, averageUtilization: 70 } }
  - type: Resource
    resource: { name: memory, target: { type: AverageValue, averageValue: 512Mi } }

3. Listing HPAs

kubectl get hpa
kubectl get hpa web -o yaml
ColumnMeaning
TARGETScurrent / desired
MINPODS / MAXPODSBounds
REPLICASCurrent

4. Describing HPA Details

FieldInfo
ConditionsAbleToScale, ScalingActive, ScalingLimited
EventsSuccessfulRescale, FailedGetResourceMetric

5. Setting Min and Max Replicas

FieldDetail
minReplicasFloor (default 1; can be 0 in 1.16+ alpha)
maxReplicasCeiling — required

6. Using CPU-Based Scaling

metrics:
- type: Resource
  resource:
    name: cpu
    target: { type: Utilization, averageUtilization: 70 }
Note: Utilization is % of requests.cpu. Requires Metrics Server.

7. Using Memory-Based Scaling

target.typeMeaning
Utilization% of requests.memory
AverageValueAbsolute per-pod value

8. Using Custom Metrics

metrics:
- type: Pods
  pods:
    metric: { name: requests_per_second }
    target: { type: AverageValue, averageValue: "100" }
- type: External
  external:
    metric:
      name: kafka_lag
      selector: { matchLabels: { topic: orders } }
    target: { type: Value, value: "1000" }
TypeSource
PodsPer-pod metric (custom.metrics.k8s.io)
ObjectMetric on a single K8s object
ExternalExternal system (external.metrics.k8s.io)
Note: Requires prometheus-adapter or KEDA for non-resource metrics.

9. Configuring Scale Up Behavior

behavior:
  scaleUp:
    stabilizationWindowSeconds: 0
    policies:
    - { type: Percent, value: 100, periodSeconds: 15 }
    - { type: Pods,    value: 4,   periodSeconds: 15 }
    selectPolicy: Max
FieldEffect
policiesLimit add per window
selectPolicyMax / Min / Disabled

10. Configuring Scale Down Behavior

behavior:
  scaleDown:
    stabilizationWindowSeconds: 300   # default
    policies:
    - { type: Percent, value: 10, periodSeconds: 60 }

11. Setting Stabilization Window

BehaviorDefault
scaleUp0s (immediate)
scaleDown300s (avoid flapping)

12. Troubleshooting HPA

IssueCause
<unknown> targetMetrics Server missing/unreachable
No scalingPod requests not set; can't compute %
FlappingStabilization window too short
Custom metric failprometheus-adapter not configured