Sub topic 10
Horizontal autoscaling of replicas
This chapter assumes you can read a Kubernetes Deployment and a short YAML manifest, and that you know the metrics from earlier chapters: p99 latency, queue depth, and concurrency. You should also know that each replica runs its own dynamic batcher. Here you learn how a controller changes the replica count to follow load, and where that goes wrong for model servers.
What horizontal autoscaling does
Horizontal autoscaling changes the number of identical replicas behind a load balancer. Vertical scaling gives one replica more CPU, memory, or a bigger GPU. Horizontal scaling is the usual choice for inference for three reasons:
- Replicas are stateless. Any replica can answer any request.
- Capacity grows roughly linearly with replica count. If one replica handles 40 requests per second at its latency target, ten handle about 400.
- A failed replica loses only a fraction of capacity.
Batching and horizontal scaling work at different levels. Batching raises the throughput of one replica. Autoscaling decides how many replicas you run. If batching gives each replica more throughput, you need fewer replicas for the same load, so tune the two together (the final chapters cover this).
The control loop
The Kubernetes HorizontalPodAutoscaler (HPA) is a control loop. By default it runs about every 15 seconds:
- Read the current value of each configured metric.
- Compute a desired replica count for each metric.
- Take the largest of those counts.
- Clamp it between
minReplicasandmaxReplicas. - Apply the
behaviorrules, then update the Deployment's replica count.
For a metric with a target value, the core formula is:
desiredReplicas = ceil(currentReplicas * currentMetric / targetMetric)If the metric is twice the target, the replica count doubles. If the metric is half the target, the count halves. The HPA skips any change when the ratio is within a tolerance of 1.0 (10% by default), so small fluctuations cause no action. This function reproduces the calculation:
import math
def desired_replicas(current_replicas, current_metric, target_metric, tolerance=0.1):
"""Mirror of the core HPA calculation for one per-pod average metric."""
ratio = current_metric / target_metric
if abs(ratio - 1.0) <= tolerance:
return current_replicas
return math.ceil(current_replicas * ratio)
# Queue depth averages 10 per pod against a target of 4: scale up.
print(desired_replicas(4, 10, 4)) # 10
# Queue depth averages 2 per pod against a target of 4: scale down.
print(desired_replicas(10, 2, 4)) # 5
# Within 10% of the target: no change.
print(desired_replicas(5, 4.2, 4)) # 5The calculation is proportional control. It assumes the metric moves in proportion to the replica count. That holds for queue depth per pod, because total waiting work is shared across more pods. It holds poorly for metrics that saturate, such as CPU on a GPU-bound server.
A working HPA for a model server
This manifest scales the model-server Deployment on average queue depth per pod:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: model-server
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: model-server
minReplicas: 2
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: inference_queue_depth
target:
type: AverageValue
averageValue: "4"
behavior:
scaleUp:
stabilizationWindowSeconds: 0
scaleDown:
stabilizationWindowSeconds: 300The fields that matter most:
minReplicas: 2keeps a warm floor. A single replica is a single point of failure and a cold start waiting to happen.maxReplicas: 20caps cost and protects downstream systems. It also protects you from a runaway metric.type: PodswithAverageValuemeans the HPA averages the metric across pods and compares it to 4.scaleUphas no stabilization, so the HPA reacts to load at once.scaleDownwaits 300 seconds and uses the highest recommendation seen in that window. The next chapter covers these rules in detail.
A Pods metric is not built into Kubernetes. You must expose inference_queue_depth from the server (for example as a Prometheus gauge). A custom metrics adapter, such as Prometheus Adapter, then serves it through the Kubernetes custom metrics API. KEDA is an alternative that creates and manages an HPA from event-style triggers. It can also scale to zero, which a plain HPA cannot do by default.
Choosing the target value
The target of 4 is not arbitrary. Derive it from your latency objective and your batching configuration:
- Your batch size is
max_batch_size, and one batch takes a known time to run, say 40 ms. If the p99 target is 200 ms, a request can afford to wait for only a few batches. - A queue depth near the batch size means requests wait about one batch. A depth of several batch sizes means waits of several batch times.
- So pick a target queue depth that gives an expected wait well below the latency budget, then test it under load.
Load test first. Measure p99 latency at increasing queue depths on a single replica, and pick the target at the depth where p99 is still comfortably under the objective, not at the knee of the curve. Scaling takes time, so the target needs headroom for the load that arrives while new pods start.
Choosing between metric types
| Metric type | Example | Works well when | Common problem |
|---|---|---|---|
| Resource | CPU utilization | CPU-bound models on CPU | Does not reflect GPU saturation. Needs CPU requests set on pods. |
| Pods | Queue depth per pod | Batched servers with a visible queue | Needs a metrics adapter. Averages hide one stuck pod. |
| Pods | In-flight requests per pod | Servers with a concurrency limit | Needs the server to expose a gauge. |
| External | Requests per second at the load balancer | Throughput is known per replica | Ignores latency and slowing requests. |
If you list several metrics, the HPA computes a count for each and uses the largest. This lets you combine a queue-depth signal with a CPU guard.
Common errors
- Scaling on GPU-bound CPU. A GPU model server often shows low CPU while the GPU is saturated and requests queue. The HPA sees nothing wrong. Use a queue or concurrency metric.
- Long-lived connections pin traffic. gRPC and HTTP/2 clients keep connections open. A Kubernetes Service balances per connection, so new replicas may receive no traffic. Use client-side or proxy-level load balancing that balances per request.
- Slow readiness. A new pod counts as capacity only after it passes its readiness probe. Loading weights and warming up can take minutes (see the cold start chapter). During that time load stays high, and the HPA may keep asking for more pods. Set
maxReplicasand scale-up limits so this overshoot is bounded. - Pods stay Pending. The HPA can request pods that the cluster cannot place, for example when GPU nodes are exhausted. Pair the HPA with a node autoscaler and check GPU quotas.
- Missing resource requests. Resource-type metrics require
requestson every container in the pod. Without them the HPA reports the metric as unknown and does not scale. - Flapping. If the metric oscillates around the target, the replica count oscillates. Each scale-down can also push queue depth up on the remaining pods. A long scale-down stabilization window is the first fix.
- Metric lag. Prometheus scrape intervals, adapter caching, and the HPA sync period add up. A scrape every 15 seconds plus a 15-second sync means decisions use data that is 15 to 30 seconds old. Factor this into your headroom.
Checking that it works
Watch the HPA's own view of the world:
kubectl get hpa model-server --watch
kubectl describe hpa model-serverThe describe output shows the current metric value, the target, and recent events such as SuccessfulRescale or FailedGetPodsMetric. If you see the latter, the adapter or metric name is wrong. Then run a load test that ramps up and back down, and confirm three things: p99 stays under the objective during the ramp, the replica count follows the load without oscillating, and scale-down happens without a latency spike.
Exercise
A model Deployment has 6 replicas. The HPA target is an average queue depth of 5 per pod, and the current average is 12. With the default 10% tolerance, what replica count does the HPA request, assuming maxReplicas is 20? After the change, the load stays the same and the average falls to 5.1. What does the HPA do then?
Show answer
The ratio is 12 / 5 = 2.4, so desired = ceil(6 * 2.4) = ceil(14.4) = 15 replicas, which is under maxReplicas of 20. When the average falls to 5.1, the ratio is 1.02, within the 10% tolerance of 1.0, so the HPA makes no change and stays at 15. This is the tolerance preventing churn from small deviations.