# Autoscaling: Pods and nodes

Scale on demand at two levels: the Horizontal Pod Autoscaler adds Pods under load, and the Cluster Autoscaler adds nodes when Pods have nowhere to run. Both shown live on EKS, plus where VPA fits.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 10. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/10-autoscaling

## What you will learn

- Configure a Horizontal Pod Autoscaler on CPU and watch it scale under load
- Explain why the HPA needs resource requests and metrics-server
- Install the Cluster Autoscaler on EKS and watch it add a node for Pending Pods
- Explain what the Vertical Pod Autoscaler does and when to use it

> **Lab status.** **Verified lab:** the HPA scaling shop-web from 3 to 8 Pods under load, and the Cluster Autoscaler adding a third node and removing it, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** the Vertical Pod Autoscaler and Karpenter (explained, not run). <br />**Cloud lab:** adding nodes needs a cloud cluster; the HPA also works on kind with metrics-server.

Traffic isn't flat. A shop is quiet at 4 a.m. and busy at 8 p.m. Running enough for the peak all day wastes
money; running for the average falls over at the peak. Kubernetes scales at two levels: **more Pods** when the
app is busy, and **more nodes** when the Pods have nowhere to run.

## Horizontal Pod Autoscaler

The **HPA** watches a metric and changes a Deployment's replica count:

```yaml
# 10-hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: shop-web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: shop-web
  minReplicas: 2
  maxReplicas: 8
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 50 # percent of each Pod's CPU request
```

How it decides, every 15 seconds:

1. It reads the Pods' CPU use from metrics-server.
2. It divides by the CPU **request** (100m for shop-web) to get a utilisation percentage.
3. It computes `desired = current replicas x (current utilisation / target)`, rounds up, and stays within
   `minReplicas` and `maxReplicas`.

> **Figure.** Animated, with the lab's real readings. A chart of CPU utilisation against the 50 percent target: 1 percent at rest, 334 percent after 30 seconds of load, then 167, 137, 123, 121, 122, 131 and 110 percent as Pods are added. On the right, the HPA loop: every 15 seconds read CPU from metrics-server, divide by the 100m request, desired equals 3 times 334 over 50, which is 21, capped at maxReplicas 8. The replica row grows from 3 Pods to 6, then to 8. CPU stays above target because 8 is the cap.
>
> The lab run, replayed: every number on the chart is a real kubectl get hpa reading.

A load-generator Pod then called `/burn` (200 ms of CPU per request) in a loop. The real readings, every 30
seconds:

```text
$ kubectl get hpa shop-web
NAME       REFERENCE             TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
shop-web   Deployment/shop-web   cpu: 1%/50%   2         8         3          39s
$ kubectl get hpa shop-web   # after 30s of load
shop-web   Deployment/shop-web   cpu: 334%/50%   2         8         3          79s
$ kubectl get hpa shop-web   # after 60s of load
shop-web   Deployment/shop-web   cpu: 167%/50%   2         8         8          112s
$ kubectl get hpa shop-web   # after 120s of load
shop-web   Deployment/shop-web   cpu: 123%/50%   2         8         8          2m59s
$ kubectl get hpa shop-web   # after 240s of load
shop-web   Deployment/shop-web   cpu: 110%/50%   2         8         8          5m14s
$ kubectl describe hpa shop-web
...
Events:
  Normal  SuccessfulRescale  4m1s   horizontal-pod-autoscaler  New size: 6; reason: cpu resource utilization (percentage of request) above target
  Normal  SuccessfulRescale  3m46s  horizontal-pod-autoscaler  New size: 8; reason: cpu resource utilization (percentage of request) above target
```

At 334% the HPA wanted far more than 8 Pods, scaled to 6, then to 8 (the maximum) 15 seconds later. CPU stayed
above target because 8 was the cap: in real life that's the signal to raise `maxReplicas` or make the app
cheaper per request. When load stops, the HPA waits 5 minutes (its scale-down stabilisation window) before
removing Pods, so a short dip doesn't cause flapping.

Two requirements trip people up: the Pods must have a **CPU request** (otherwise the target shows `<unknown>`),
and **metrics-server** must be running. The HPA can also scale on memory or on custom metrics, such as requests
per second from Prometheus.

## Cluster Autoscaler

More Pods need more room. When no node has enough unreserved CPU or memory, new Pods stay **Pending**. The
**Cluster Autoscaler** watches for exactly that and grows the node group; it also removes nodes it can empty.

On EKS it runs in the cluster, finds node groups by their tags, and changes the Auto Scaling group's desired
count. It needs IAM permissions, given here through Pod Identity, and installs with Helm:

```text
$ helm install cluster-autoscaler autoscaler/cluster-autoscaler -n kube-system \
    --set autoDiscovery.clusterName=academy --set awsRegion=ap-south-1 \
    --set rbac.serviceAccount.name=cluster-autoscaler --wait
NAME: cluster-autoscaler
NAMESPACE: kube-system
STATUS: deployed
REVISION: 1
```

(The first attempt failed with a timeout downloading the chart from GitHub; running the same command again
worked. Network errors during `helm install` are worth one retry before digging deeper.)

Then a Deployment of 6 Pods, each requesting 600m of CPU, on two nodes with 1930m allocatable each:

```text
$ kubectl get pods -l app=big
  ... 4 Running, 2 Pending ...
  Warning  FailedScheduling  ...  0/2 nodes are available: 2 Insufficient cpu. ...
$ kubectl logs -n kube-system deployment/cluster-autoscaler-aws-cluster-autoscaler | grep -iE "scale-up plan|setting group"
I1109 06:40:04.897347       1 orchestrator.go:1095] "Estimated nodes needed" iterationId="a538b217-65" nodeCount=1 nodeGroupId="eks-default-4f8ac3296b79a6f028385674b6-..."
I1109 06:40:04.897367       1 orchestrator.go:168] "Final scale-up plan" ...
I1109 06:40:04.897397       1 executor.go:148] "Scale-up: setting group size" ...
$ kubectl get nodes -L topology.kubernetes.io/zone
NAME                                          STATUS   ROLES    AGE   VERSION               ZONE
ip-10-42-0-115.ap-south-1.compute.internal    Ready    <none>   51m   v1.37.1-eks-6e7947a   ap-south-1a
ip-10-42-14-248.ap-south-1.compute.internal   Ready    <none>   28s   v1.37.1-eks-6e7947a   ap-south-1a
ip-10-42-28-149.ap-south-1.compute.internal   Ready    <none>   51m   v1.37.1-eks-6e7947a   ap-south-1b
$ kubectl get pods -l app=big -o wide
NAME                   READY   STATUS    RESTARTS   AGE   IP             NODE
big-6688b8d444-gwpjr   1/1     Running   0          71s   10.42.1.185    ip-10-42-14-248.ap-south-1.compute.internal
big-6688b8d444-qqngk   1/1     Running   0          71s   10.42.2.24     ip-10-42-14-248.ap-south-1.compute.internal
...
$ aws autoscaling describe-auto-scaling-groups --query "AutoScalingGroups[?contains(AutoScalingGroupName,'eks-default')].{min:MinSize,desired:DesiredCapacity,max:MaxSize}" --output table
| desired |  max  |  min  |
|  3      |  3    |  2    |
```

(Columns trimmed.) The autoscaler estimated one node was needed, set the Auto Scaling group's desired size from
2 to 3, and a new node, 28 seconds old, took the two Pending Pods. A node takes a couple of minutes to boot and
join, so Pod autoscaling reacts in seconds while node autoscaling reacts in minutes. After the big Deployment was
deleted, the autoscaler removed the extra node again once it had been underused for its scale-down delay.

> **Figure.** Animated, from the lab. Two nodes, ip-10-42-0-115 in ap-south-1a and ip-10-42-28-149 in ap-south-1b, 1930m CPU allocatable each, already run other Pods plus two big Pods each (600m CPU requested per Pod). Two more big Pods, gwpjr and qqngk, are Pending: 0/2 nodes are available, 2 Insufficient cpu. The Cluster Autoscaler estimates one node is needed and sets the Auto Scaling group from 2 to 3. A third node, ip-10-42-14-248 in ap-south-1a, joins, and the two Pending Pods run on it.
>
> Pending Pods are the trigger. The autoscaler grows the Auto Scaling group; the scheduler then places the Pods on the new node.

It looks at **requests**, not real usage: an idle node full of requested CPU is "full". That's another reason to
set requests honestly. **Karpenter** is the main alternative on AWS: instead of resizing fixed node groups, it
launches whichever instance type fits the Pending Pods, usually faster and cheaper.

## Vertical Pod Autoscaler

The **VPA** adjusts a Pod's **requests** instead of its count: it watches real usage and recommends, or applies,
better CPU and memory requests. It's an add-on (not installed in the lab), and in "recommendation" mode it's a
safe way to size requests from real data. Don't let the VPA and an HPA both act on CPU for the same Deployment,
since they'd fight.

Its `updateMode` decides how far it goes: `Off` only recommends, `Initial` sets requests on new Pods, and
`Recreate` also evicts running Pods so their replacements get the new requests.

> **Figure.** Left: shop-web's real numbers. CPU request 100m; kubectl top showed 1m per Pod at rest and the HPA measured 121m per Pod under load. Memory request 64Mi; real use 11Mi. The requests are what the scheduler reserves, so wrong requests waste nodes or starve Pods. Right: the three VPA parts. The Recommender watches real usage and writes a recommendation into the VPA object. In updateMode Off that is all: you read it and update the Deployment yourself. In Initial or Recreate mode the Updater evicts Pods whose requests are far off, and the admission controller writes the recommended requests into the replacement Pods. Warning: do not let a VPA and an HPA both act on CPU for the same Deployment.
>
> shop-web asks for 100m CPU and 64Mi, uses 1m and 11Mi at rest and 121m under load: the gap a VPA is built to close.

## Mission: Watch both autoscalers react

Apply the HPA to shop-web and start the load Pod. Record kubectl get hpa every 30 seconds for 3 minutes and the SuccessfulRescale events. On EKS with the Cluster Autoscaler, create a Deployment that requests more CPU than your nodes have free and record the node count until the Pending Pods run.

- You need: 10-hpa.yaml, 10-load.yaml and 10-big.yaml
- You'll have: ~/autoscaling.txt

```sh
$ kubectl apply -f 10-hpa.yaml -f 10-load.yaml
$ for i in 1 2 3 4 5 6; do sleep 30; kubectl get hpa shop-web --no-headers; done > ~/autoscaling.txt
$ kubectl describe hpa shop-web | grep SuccessfulRescale >> ~/autoscaling.txt
$ kubectl delete pod load
$ kubectl apply -f 10-big.yaml && kubectl scale deployment big --replicas=6
$ for i in $(seq 1 12); do sleep 20; kubectl get nodes --no-headers | wc -l; done >> ~/autoscaling.txt
$ kubectl delete deployment big
```

The HPA should climb within a minute. If TARGETS shows `<unknown>`, check the Pods have a CPU request and
metrics-server is running.

## Try it

- Apply the HPA and run `kubectl get hpa shop-web` before any load.
- Start the load Pod and watch the TARGETS and REPLICAS columns every 30 seconds.
- Read `kubectl describe hpa shop-web` for the SuccessfulRescale events.
- On EKS, scale the big Deployment until Pods go Pending and watch the node count.
- Do the mini mission and keep `~/autoscaling.txt`.

## Quiz

1. The HPA target is 50% CPU and the Pods report 334%. What does the HPA do?
   - Nothing until an admin approves
   - **Calculates the replicas needed for 50% and scales up, within maxReplicas** (answer)
   - Restarts the Pods
   Why: desired = current x (current utilisation / target). In the lab it went from 3 to 6 to 8, the maximum.

2. What does the Cluster Autoscaler react to?
   - High CPU on nodes
   - **Pods stuck Pending because no node has room, and nodes that stay underused** (answer)
   - The number of Services
   Why: It adds nodes when Pods can't be scheduled and removes nodes it can empty. It looks at requests, not real usage.

3. Why does an HPA on CPU need the Pod's CPU request to be set?
   - It doesn't
   - **Utilisation is measured as a percentage of the request; with no request there is no percentage** (answer)
   - Requests make Pods faster
   Why: The HPA reads usage from metrics-server and divides by the request. Without one it reports unknown and doesn't scale.

## Resources

- [Horizontal Pod Autoscaling](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) (Kubernetes)
- [Cluster Autoscaler on AWS](https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/cloudprovider/aws/README.md) (Kubernetes autoscaler)
- [Vertical Pod Autoscaler](https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler) (Kubernetes autoscaler)
- [Karpenter](https://karpenter.sh/) (Karpenter)
