Horizontal Pod Autoscaler Replica Count
Problem Statement
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.
Background
The HPA formula is:
desiredReplicas = ceil(currentReplicas * (currentMetric / targetMetric))
Two details keep it from oscillating and from running away:
- Tolerance. If the ratio is within 10% of 1.0 — that is, abs(ratio - 1) <= 0.1 — the HPA does nothing and keeps currentReplicas. Without this, a service sitting at 51% against a 50% target would flap up and down forever.
- Clamping. The result is clamped into [minReplicas, maxReplicas].
The ceiling matters: scaling to 7.2 pods means 8 pods, because under-provisioning is the expensive mistake.
Your Task
Implement:
def hpa_desired(current_replicas, current_metric, target_metric, min_replicas, max_replicas):
Return the replica count as an int.
Input Format
- current_replicas: int, pods currently running.
- current_metric: number, the observed average metric value per pod.
- target_metric: number, the configured target.
- min_replicas, max_replicas: ints, the autoscaler bounds.
Output Format
- A single int.
Sample
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.
Example
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.
Constraints
- 0 <= current_replicas <= 1000, 1 <= min_replicas <= max_replicas <= 1000
- Metrics are non-negative numbers
- Tolerance band: no change when
abs(current_metric / target_metric - 1) <= 0.1 - Otherwise
ceil(current_replicas * ratio), then clamp into[min_replicas, max_replicas] - If
current_replicasortarget_metricis 0, returnmin_replicas - Return an int