The Kubernetes HPA’s Scaling Algorithm: Tolerance, Stabilization, and Why Replicas Flap

Horizontal Pod Autoscaling looks like one of those features you can safely treat as magic: set a CPU target, get the right number of pods. Then production hands you a workload whose replica count oscillates between 3 and 12 every few minutes, and the magic needs explaining. The truth is that the HPA is not an exotic algorithm at all — it is a control loop that runs every 15 seconds, evaluates a one-line ratio, and then applies a handful of deliberately conservative guards before touching your Deployment. Once you know those guards, most autoscaling misbehavior becomes diagnosable.

This post walks through the algorithm exactly as the controller applies it: the ratio formula, the tolerance that suppresses small changes, the special handling of missing metrics and not-ready pods, the stabilization window, and the scaling policies. Then we’ll look at why flapping still happens on top of all that, and what to tune.

The core loop is a ratio

Every --horizontal-pod-autoscaler-sync-period (15 seconds by default), the controller fetches the current metric value for each pod, averages it, and computes:

desiredReplicas = ceil(currentReplicas * currentMetricValue / desiredMetricValue)

If you scale on CPU at averageUtilization: 60, the current metric value is the pod’s CPU usage divided by its CPU request, averaged across pods. A workload with 200m usage per pod against 100m requests has a ratio of 2.0, so the HPA doubles the replica count. A ratio of 0.5 at 8 replicas brings it down to 4.

Two consequences follow immediately from that formula. First, scaling on utilization means your requests are not just scheduling hints — they are the denominator of the entire control loop. Over-requested CPU suppresses autoscaling entirely; under-requested CPU makes it hysterical. Second, adding replicas dilutes the average: if load stays fixed and you double the pods, per-pod utilization halves, which is exactly what you want, but it also means the metric the controller sees is a function of its own past decisions. That feedback shape is where oscillation comes from.

The tolerance: no action for small drift

Before acting on any ratio, the controller checks its magnitude. If the ratio is within 10% of 1.0 — meaning the current metric value sits between 90% and 110% of the target — the HPA does nothing. This tolerance exists because the raw formula would otherwise react to noise: a load average wiggling between 61% and 59% of target would produce a replica change on every sync, burning scheduler capacity for nothing.

Historically that 10% band was hardcoded and cluster-wide, tunable only through the --horizontal-pod-autoscaler-tolerance flag on the controller manager. Since Kubernetes v1.37, per-HorizontalPodAutoscaler tolerance is stable: you can set it per direction under behavior:

behavior:
  scaleUp:
    tolerance: 0.05   # react to 5% overshoot instead of the default 10%
  scaleDown:
    tolerance: 0.15   # require a 15% undershoot before removing pods

Asymmetric tolerances are a practical pattern: stay sensitive when scaling up (latency is at stake) and lazy when scaling down (money can wait a few extra minutes). The two settings fight each other otherwise — a tight scale-up tolerance paired with the default scale-down behavior produces exactly the flapping you were trying to avoid.

Missing metrics and not-ready pods

The clean formula assumes the controller has a trustworthy number for every pod. It usually doesn’t. Pods being terminated are excluded up front. Pods whose metrics are missing are set aside, and pods that are not yet Ready — or whose latest metric sample predates their readiness — are set aside too, because a JVM warming up or a model loading weights can report absurd CPU numbers.

Then the controller makes a deliberately pessimistic assumption about the pods it set aside. If the tentative direction is scale down, missing pods are assumed to be consuming 100% of the desired value; if the direction is scale up, they are assumed to consume 0%. Not-yet-ready pods are likewise counted as 0% when the recomputation would otherwise scale up. The effect is always the same: the adjusted ratio shrinks the scale change or flips its direction. If it flips or lands within tolerance, no scaling happens this cycle.

Two cluster-wide flags govern startup specifically. --horizontal-pod-autoscaler-cpu-initialization-period (default 5 minutes) ignores CPU samples from a pod unless it was Ready for the entire sampling window. --horizontal-pod-autoscaler-initial-readiness-delay (default 30 seconds) treats pods flipping rapidly between Ready and Unready as still initializing. If your application has a genuinely long startup spike, the documented remedy is to keep it out of the metric rather than tune the flags: a startupProbe that only passes once the spike has passed keeps the pod out of autoscaling math until it is representative.

Multiple metrics take the maximum

An HPA can watch several metrics — CPU, memory, a requests-per-second custom metric from Prometheus Adapter or KEDA. Each metric independently produces a desired replica count; the controller applies the largest. This makes the autoscaler effectively an OR gate: whichever pressure is strongest wins, and any one misconfigured metric silently takes over the whole scaling decision. If your pod count follows your memory request-shaped ceiling instead of your traffic-shaped CPU target, this is why.

Stabilization windows and rate policies

After the ratio math, the controller consults its history before acting. For scale-down it keeps every recommendation from the past stabilizationWindowSeconds — 300 by default — and applies the highest one, approximating a rolling maximum. A scale-down can only happen when the last five minutes of recommendations all agree that fewer pods suffice. Scale-up has no stabilization window at all: the default is to react immediately.

Rate limiting is separate from smoothing. The default policies allow adding 4 pods or 100% of current replicas every 15 seconds (whichever policy allows more), and removing up to 100% every 15 seconds — the stabilization window is the only brake on the way down. You can shape both directions:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 30
      policies:
        - type: Percent
          value: 100
          periodSeconds: 30
    scaleDown:
      stabilizationWindowSeconds: 600
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60
        - type: Pods
          value: 2
          periodSeconds: 60
      selectPolicy: Min

The selectPolicy: Min in that scale-down block means the controller applies whichever policy removes fewer pods: at most 10% per minute, and never more than 2 pods per minute. For scale-up, selectPolicy: Max (the default when multiple policies exist) does the opposite. A selectPolicy: Disabled on a direction switches it off entirely — a common choice for workloads that should never shrink below some event-driven baseline.

Simulating the decision in Go

The whole decision fits in a function, which makes it easy to test against your own load traces before you touch cluster config:

func desiredReplicas(current int, ratio, tolerance float64,
	window []float64, scaleDown bool) int {
	if math.Abs(ratio-1) <= tolerance {
		return current // within tolerance: no action
	}
	rec := float64(current) * ratio
	if scaleDown {
		for _, past := range window {
			if past > rec {
				rec = past // rolling max over the stabilization window
			}
		}
	}
	return int(math.Ceil(rec))
}

Replaying a week of your metric data through this logic — with your real tolerance, window, and policies — tells you what the replica count would have done, and usually pinpoints the cause within minutes: a scale-up policy that fires faster than your pods become Ready, so each new wave of not-ready pods triggers another conservative scale-up.

Why flapping still happens

The guards suppress noise, but they cannot fix a control loop whose actuator is slower than its sensor. Three recurring causes:

  • Slow readiness. Pods that take 60 seconds to become Ready make the effective actuator lag far larger than the 15-second sync period. Every scale-up is judged before the pods it added can influence the metric, so the controller scales again. Fix readiness speed first, or add a scale-up stabilization window.
  • Wrong denominator. Utilization against stale or arbitrary requests produces a ratio that crosses the tolerance on noise. Requests should reflect steady-state usage at normal load, not worst-case peaks.
  • Aggregate metrics that don’t dilute. A custom metric like total queue depth does not shrink as you add pods, so the ratio stays above target and the HPA scales to max. Custom metrics must be expressed per-pod — average it across replicas in the adapter, or switch to an external metric with explicit math.

Wrapping up

The HPA is a humble controller: one ratio, one tolerance, a rolling maximum on the way down, and maximum-of-metrics arbitration. Nearly every “autoscaling is broken” incident traces back to one of those five mechanisms interacting with workload reality — usually readiness lag or a badly shaped request. The algorithm details page in the Kubernetes docs documents each guard precisely, and the autoscaling/v2 API exposes all of them declaratively. Read the formula once, then spend your tuning effort on the denominator and the readiness path — that is where the leverage is.

Leave a Reply

Your email address will not be published. Required fields are marked *