Loading...
The Horizontal Pod Autoscaler reads one metric per pod — average CPU utilisation, or queue depth, or inference latency — compares it to a target, and rescales the Deployment. Implement its control loop.
The HPA formula is:
desiredReplicas = ceil(currentReplicas * (currentMetric / targetMetric))
Two details keep it from oscillating and from running away:
The ceiling matters: scaling to 7.2 pods means 8 pods, because under-provisioning is the expensive mistake.
Implement:
def hpa_desired(current_replicas, current_metric, target_metric, min_replicas, max_replicas):
Return the replica count as an int.
print(hpa_desired(4, 90, 50, 1, 10))
Output:
8
The ratio is 1.8, well outside the tolerance band, so ceil(4 * 1.8) = 8 — within the [1, 10] bounds.
print(hpa_desired(4, 90, 50, 1, 10))
8
ratio = 90 / 50 = 1.8. abs(1.8 - 1) = 0.8 > 0.1, so the tolerance band does not apply. ceil(4 * 1.8) = ceil(7.2) = 8, and 8 lies inside [1, 10], so the HPA scales the Deployment to 8 pods.
abs(current_metric / target_metric - 1) <= 0.1ceil(current_replicas * ratio), then clamp into [min_replicas, max_replicas]current_replicas or target_metric is 0, return min_replicas