Medium java docker

How do you implement autoscaling in Kubernetes?

The 30 second answer

The usual mechanism is the HorizontalPodAutoscaler: I set a minimum and maximum replica count and a target such as CPU utilisation or a custom metric, and the HPA controller adds or removes Pods in the Deployment. I also size requests and limits honestly, because the HPA compares usage to requests. Vertical scaling and cluster autoscaling are different knobs: they change Pod resources or Node count, not the replica count of my app.

Could you say this in an interview?

Kubernetes autoscaling has three common layers, and I name which one I mean.

HorizontalPodAutoscaler (HPA). The workload (a Deployment or StatefulSet) is scaled in replicas. The HPA API documents metrics such as resource utilisation (CPU, memory) or custom/external metrics (requests per second, queue depth). I set minReplicas and maxReplicas so a bad metric cannot go to zero or to infinity. Cool-down behaviour is controlled by the HPA algorithm; I do not expect instant scale-down.

**CPU targets only work if resources.requests are set.** The utilisation is usage divided by request. A tiny request makes the HPA think the Pod is "hot" all the time.

Vertical Pod Autoscaler adjusts CPU/memory requests, not replica count. Cluster Autoscaler (or a managed node autoscaler) adds or removes Nodes when Pods cannot be scheduled, or when Nodes are underused. An HPA that creates unschedulable Pods is a cluster-capacity problem, not an application-metrics problem.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: checkout
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
Sources (3)
  1. Kubernetes: Horizontal Pod Autoscalingkubernetes.io
  2. Kubernetes: HorizontalPodAutoscaler referencekubernetes.io
  3. Kubernetes: Resource management for Pods and Containerskubernetes.io