Sub topic 13
Sizing Replicas and Planning Capacity
Prerequisites
This chapter assumes you have read the earlier chapters on dynamic batching, latency objectives, Little's law, and horizontal autoscaling. You should be comfortable with p50 and p99 latency, Python, and a Kubernetes Deployment with a HorizontalPodAutoscaler (HPA). The chapter covers how to turn a traffic forecast and a latency target into a replica count, and how to set the autoscaler's limits so they match that count.
What capacity planning answers
The autoscaler reacts to load. Capacity planning decides the limits it works within:
- The minimum replica count that keeps the service inside its latency objective during a normal traffic dip.
- The maximum replica count that the budget and the hardware quota allow.
- The load level at which one replica should be considered full.
Without a plan, minReplicas and maxReplicas are guesses. A minReplicas that is too low turns every traffic ramp into a cold-start event. A maxReplicas that is too low makes the service saturate during a peak, and no scaling signal can fix that.
From Little's law to a replica count
Little's law says that the average number of requests in the system equals the arrival rate times the average time each request spends there: L = λ × W. For a model service, L is the number of in-flight requests across all replicas. Divide L by the number of requests one replica can handle at once, and you get a replica count.
import math
def required_replicas(arrival_rate_rps, avg_latency_s, concurrency_per_replica, target_utilization=0.7):
"""Little's law: in-flight requests L = arrival rate * latency."""
in_flight = arrival_rate_rps * avg_latency_s
usable = concurrency_per_replica * target_utilization
return math.ceil(in_flight / usable)
# 200 req/s at 120 ms average latency, 8 concurrent requests per replica
print(required_replicas(200, 0.120, 8)) # 5The numbers work out as follows. 200 req/s × 0.120 s gives 24 requests in flight. Each replica handles 8 at once, but only 8 × 0.7 = 5.6 of those slots are planned for use. 24 / 5.6 is about 4.3, which rounds up to 5.
Two inputs need care:
- Latency must be measured under load. The
Win Little's law includes queue wait and batch wait. A latency measured on an idle server is too small, and the plan will undersize the fleet. - Use the right arrival rate. Plan for the peak you must serve within the objective, not the daily average. A service averaging 100 req/s with 400 req/s bursts needs capacity for the bursts, or an explicit decision to accept degraded latency during them.
Why the utilization target is below 100%
Queue wait grows non-linearly as utilization approaches 1. In the simplest single-server queue model (M/M/1), mean wait scales with ρ / (1 − ρ), where ρ is utilization.
| Utilization ρ | ρ / (1 − ρ) |
|---|---|
| 0.5 | 1.0 |
| 0.7 | 2.3 |
| 0.9 | 9.0 |
| 0.95 | 19.0 |
Going from 70% to 90% utilization multiplies the queueing term by almost four. Tail latency suffers first, because p99 reflects the worst queueing episodes. A target of 0.6 to 0.75 is a common starting point. Pick it from your load test, not from convention.
Where concurrency per replica comes from
"Concurrency per replica" is not a free parameter. It follows from how you configure the server:
- The maximum batch size sets how many requests one batch carries.
- The number of model instances on the accelerator sets how many batches run at the same time.
- Accelerator memory caps both.
A rough rule is concurrency ≈ max_batch_size × concurrent batches, but treat it as a hypothesis. Confirm it with a load test that raises concurrency until latency or error rate breaks your objective.
A throughput-based sizing from benchmarks
Little's law needs a latency that already reflects the batch size. A more direct approach starts from a benchmark of one replica and works in throughput. Measure the p99 batch latency at several batch sizes. The values below are illustrative, so replace them with your own measurements.
import math
# One replica, measured: batch size -> p99 batch execution latency in seconds
BENCHMARK = {1: 0.020, 4: 0.032, 8: 0.050, 16: 0.090, 32: 0.170}
def plan(peak_rps, p99_budget_s, max_queue_delay_s, headroom=0.7, spare=1):
"""Pick the batch size with the highest throughput that fits the latency budget."""
best = None
for batch_size, batch_latency in sorted(BENCHMARK.items()):
# Worst case for a request: wait for the batch to fill, then run it.
if max_queue_delay_s + batch_latency > p99_budget_s:
continue
throughput = batch_size / batch_latency
if best is None or throughput > best[1]:
best = (batch_size, throughput)
if best is None:
raise ValueError("No batch size meets the latency budget")
batch_size, throughput = best
replicas = math.ceil(peak_rps / (throughput * headroom)) + spare
return batch_size, throughput, replicas
batch_size, throughput, replicas = plan(
peak_rps=400, p99_budget_s=0.150, max_queue_delay_s=0.010
)
print(f"batch={batch_size} per-replica={throughput:.0f} rps replicas={replicas}")This prints batch=16 per-replica=178 rps replicas=5. Batch size 32 is rejected because 0.010 + 0.170 exceeds the 0.150 s budget. At batch size 16, one replica serves about 178 req/s. At a 0.7 headroom factor, that is about 124 req/s of planned load, so 400 req/s needs 4 replicas. The spare of 1 adds a fifth.
The latency check is optimistic. A request can also wait behind a batch that is already running, so under load the worst case is closer to max_queue_delay + 2 × batch_latency. Tighten the check if your p99 budget is close to the limit.
Spare capacity and failure
Add headroom for three separate reasons, and do not let one number stand in for all of them:
- Utilization headroom keeps queueing delay small. This is the 0.7 factor above.
- Failure headroom keeps the service in its objective when a replica or a node is lost. With 4 replicas, losing one removes 25% of capacity. The
sparereplica in the example covers this. Spread replicas across nodes or zones so one failure removes only one replica. - Scaling lag headroom covers the time between a load increase and new replicas becoming ready. This is cold start time plus the autoscaler's metric and decision delay. If load can grow by 50 req/s per minute and a replica takes 3 minutes to become ready, you must already hold capacity for the extra 150 req/s.
From plan to autoscaler settings
Map the plan onto the HPA you configured in the previous chapters:
| Plan output | Autoscaler setting |
|---|---|
| Replicas needed at the off-peak floor, plus failure spare | `minReplicas` |
| Replicas needed at the forecast peak, plus failure spare, within budget and quota | `maxReplicas` |
| Per-replica concurrency or queue depth at the target utilization | The metric `averageValue` target |
| Scaling lag headroom | A lower metric target, or a higher `minReplicas` |
For example, if a replica reaches the target utilization at 8 concurrent requests, a target of about 5 or 6 in-flight requests per replica (the 0.7 factor) is a sensible starting averageValue. Check that maxReplicas times the per-replica accelerator count fits your cluster quota. If it does not, the HPA will request pods that stay Pending, and the capacity you planned never appears.
Common errors
- Sizing from average latency measured at low load. The plan then breaks at the first real peak.
- Planning for the average rate. The service meets its objective only half of the day.
- Ignoring quota.
maxReplicas: 20is meaningless if the cluster has accelerators for 12 pods. - Treating the plan as permanent. A new model version, a new batch size, or a changed input mix changes per-replica throughput. Repeat the benchmark when any of these change.
- Planning cost only at the peak. Compare the cost of idle capacity at
minReplicasagainst the latency cost of scaling up from a lower floor. RaisingminReplicasis often the cheapest fix for a slow cold start.
Exercises
Exercise
A service receives 300 req/s at a peak. Average latency under load is 80 ms. Each replica handles 6 concurrent requests, and you target 75% utilization. How many replicas does Little's law suggest, and how many do you deploy if you add one spare replica for failures?
Show answer
In-flight requests = 300 × 0.080 = 24. Usable concurrency per replica = 6 × 0.75 = 4.5. 24 / 4.5 is about 5.33, which rounds up to 6 replicas. With one spare replica for failure headroom, deploy 7.
Exercise
A benchmark shows a replica serving batches of 32 in 0.170 s. The p99 budget is 0.150 s and the max queue delay is 0.010 s. Why can this batch size not be used, and what can you change?
Show answer
The worst-case time for a request is 0.010 + 0.170 = 0.180 s, which exceeds the 0.150 s budget. You can lower the maximum batch size so batch latency drops, shorten the queue delay, use a faster accelerator, or negotiate a larger latency budget. Lowering the batch size reduces per-replica throughput, so the replica count rises.