# Autoscaling pods

The control plane runs the HorizontalPodAutoscaler (HPA) and VerticalPodAutoscaler (VPA) controllers. An HPA changes a workload's replica count, and can scale an idle workload to zero and start it again on its next connection. A VPA recommends or sets container CPU and memory requests. To try both, follow [Autoscale a workload](/docs/autoscale/).

## Metrics

The control plane serves `metrics.k8s.io/v1beta1` from the CPU and memory usage that each node reports, so you do not need to install metrics-server. CPU and memory are the only usage metrics. A new pod has no metrics for its first few seconds. The control plane does not serve the custom or external metrics APIs. An HPA can also read whether a Service has traffic, to [scale to zero](#scale-to-zero).

## Horizontal Pod Autoscaler

The API serves `autoscaling/v1` and `autoscaling/v2` HPAs. An HPA scales a `Deployment` or `StatefulSet` on `cpu` or `memory` `Resource` metrics with `target.type: Utilization`. By default, a scale-down waits five minutes. To change the wait, set `behavior.*.stabilizationWindowSeconds`.

When you read an HPA at `autoscaling/v1`, the fields that only v2 has, such as `metrics` and `behavior`, appear in `autoscaling.alpha.kubernetes.io/` annotations, as they do upstream. If you write the HPA back with those annotations, it keeps those fields. A v1 HPA with no `targetCPUUtilizationPercentage` targets 80% CPU.

The HPA computes a new replica count each time a node reports usage, not every 15 seconds as upstream does. It does not limit how many pods one scale-up adds.

### When an HPA does not scale

The HPA sets the condition `ScalingActive=False` and does not change the replica count when:

| Field or state                                                                                     | Reason                    |
| -------------------------------------------------------------------------------------------------- | ------------------------- |
| The target is not a `Deployment` or `StatefulSet`                                                  | `FailedGetScale`          |
| A metric other than `Resource` with `Utilization` or `kiteplane.dev/service-traffic`, or no metric | `InvalidMetric`           |
| `policies` or `selectPolicy` under `behavior`                                                      | `InvalidBehavior`         |
| Target pods have no usage yet, or no request for the metric                                        | `FailedGetResourceMetric` |
| You scaled the target to zero                                                                      | `ScalingDisabled`         |

### Scale to zero

An HPA can scale a workload to zero replicas when its Service has had no traffic for a set idle time, and start one replica when a connection arrives. To opt in, set `minReplicas: 0` and add an `Object` metric named `kiteplane.dev/service-traffic` that describes the Service, with a `Value` target of `1`:

```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 0
  maxReplicas: 3
  metrics:
    - type: Object
      object:
        describedObject:
          apiVersion: v1
          kind: Service
          name: web
        metric:
          name: kiteplane.dev/service-traffic
        target:
          type: Value
          value: "1"
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 600
```

The metric reads `1` while the Service has traffic and `0` when it has none. Once it has read `0` for the idle time, `behavior.scaleDown.stabilizationWindowSeconds`, the HPA scales the workload to zero and sets the condition `ScaledToZero=True`.

- The idle time defaults to five minutes, and can be at most an hour.
- The idle time starts up to two of the nodes' report intervals after the last traffic: 20 seconds on a cluster of up to 500 nodes, and at most two minutes on a larger one.
- A workload gets a whole idle time after you create the HPA and after it comes back up from zero.
- A restart of the control plane does not start the idle time again, but the HPA scales no workload to zero until every node has reported after the restart.
- When the nodes' agents restart with the control plane, traffic in the two minutes before the restart may not count.

```bash
kubectl get hpa web
```

```text
NAME   REFERENCE        TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
web    Deployment/web   0/1       0         3         0          2m19s
```

While the workload is at zero, a TCP connection to the Service's cluster address or node port waits up to 10 minutes while Kite starts one replica, and then reaches it. Other traffic is refused, as for any Service with no backend. The Service must select the pods of the HPA's target, a `Deployment` or `StatefulSet`.

The API refuses:

- `minReplicas: 0` without an `Object` or `External` metric, as upstream does.
- A `kiteplane.dev/service-traffic` metric that describes anything but a Service.
- A `kiteplane.dev/service-traffic` metric with a metric selector.
- A `kiteplane.dev/service-traffic` metric with a target other than `type: Value` with `value: "1"`.

#### What counts as traffic

A packet counts when a node sends it to the Service's cluster address or node port, from a pod, from the node itself or from outside the cluster. These do not count, so they neither keep the workload up nor wake it:

- The node's liveness, readiness and startup probes, which go to the pod's own address.
- Requests through the API's `services/proxy` and `pods/proxy`, and `kubectl port-forward`.
- Traffic sent straight to a pod's address, such as to a headless Service (`clusterIP: None`) or from an ingress controller that routes to pods.
- Traffic through a node while it cannot reach the control plane, until the node reports it.

#### With CPU or memory metrics

An HPA can have `cpu` or `memory` metrics as well. Above zero, they set the replica count between one and `maxReplicas` as they would alone. Only the traffic metric scales the workload to zero, whatever the pods' CPU and memory use. While a CPU or memory metric has no reading at all, the HPA does not scale to zero.

#### When you scale to zero yourself

If you scale the workload to zero, the HPA leaves it there and sets `ScalingActive=False` with the reason `ScalingDisabled`, as upstream does. Connections to the Service are refused, not held. The HPA starts again when you scale the workload above zero.

:::caution
Scaling to zero deletes every pod. Data in an `emptyDir` volume or in a container's own filesystem is lost. Keep state that must survive in a PersistentVolumeClaim, such as a StatefulSet's `volumeClaimTemplates`.
:::

## Vertical Pod Autoscaler

Kite serves `autoscaling.k8s.io/v1` `VerticalPodAutoscaler` objects that target a `Deployment`, `StatefulSet` or `DaemonSet`. Kite runs its own recommender, which computes the requests that a VPA recommends. Kite ignores a VPA that sets `spec.recommenders`, and that VPA reports `RecommendationProvided=False`.

### Update modes

`updatePolicy.updateMode` defaults to `Auto`.

| Mode                 | Result                                                                              |
| -------------------- | ----------------------------------------------------------------------------------- |
| `Off`                | Records recommendations and never changes pods.                                     |
| `Initial`            | Applies the recommendation when a pod is created.                                   |
| `Auto` or `Recreate` | Applies it at creation, and evicts a pod of the wrong size so that it is recreated. |

The VPA does not resize a running pod in place, so `Auto` and `Recreate` behave the same. The API rejects any other mode.

### Eviction limits

A VPA respects PodDisruptionBudgets. It keeps at least `updatePolicy.minReplicas` pods running, two by default. At one time, it evicts at most:

- half of a Deployment's pods,
- one StatefulSet pod, or
- a DaemonSet's `maxUnavailable`.

When it cannot evict any pod, it sets an `EvictionBlocked` condition.

:::note
With the default `minReplicas`, a VPA never evicts from a workload with two or fewer running pods.
:::

## Next

- [Autoscale a workload](/docs/autoscale/) — apply an HPA and read a VPA recommendation.
- [Node pools](/docs/node-pools/) — add nodes when replicas need more capacity.
