Sub topic 15
Tuning batching and autoscaling together
This chapter assumes you know how dynamic batching works (max batch size, max queue delay), how a Kubernetes HorizontalPodAutoscaler (HPA) scales a Deployment, and how to read p50 and p99 latency. It covers how the two mechanisms interact and gives a procedure for tuning them in the right order.
Why the two cannot be tuned separately
Batching and autoscaling both trade latency and cost, and each changes the inputs of the other.
- Batching sets how much traffic one replica can carry. A larger batch size usually raises per-replica throughput, so fewer replicas are needed.
- Batching also sets per-request latency. Larger batches run longer, and the queue delay adds waiting time on top.
- Autoscaling sets how much traffic each replica receives. Fewer replicas means more load per replica, which means fuller batches and a longer queue.
- Autoscaling reacts slowly. New replicas need time to start, load the model, and warm up. During that time the existing replicas absorb the extra load through bigger batches and longer queues.
If you tune batching on a lightly loaded replica and autoscaling on a different assumption, the two will disagree under real traffic.
Effects at a glance
| Change | Per-replica throughput | Per-request latency | Replicas needed | Side effect on scaling |
|---|---|---|---|---|
| Raise max batch size | Up, with diminishing returns | Up at high load | Down | Queue depth targets must grow |
| Raise max queue delay | Up at low load | Up by up to the delay | Down | Idle replicas still add the delay |
| Lower target utilization | Unchanged | Down (less queuing) | Up | More cost, more headroom |
| Raise scale-down window | Unchanged | Unchanged | Higher on average | Fewer scaling oscillations |
The tuning loop
Work in this order. Each step depends on the one before it.
- Fix the objective. Pick a p99 latency target for the whole request, not just the model call.
- Measure the profile. On one replica, run the model at each batch size and record batch latency. Do this on the production hardware and model version.
- Pick batching parameters. Choose the largest batch size whose worst-case latency fits the objective.
- Derive capacity. Convert per-replica throughput into a replica count with a utilization target.
- Pick the scaling signal and policy. Express the signal in units that match the batching settings.
- Verify under a ramp. Test with rising traffic, not only steady traffic.
Step 3 and 4 in code
A request in a busy replica may wait for the batch already running, then for its own batch. A conservative worst-case estimate is max_wait + 2 * batch_latency. The script below picks the best batch size under that bound and computes replicas.
import math
# Measured on the target hardware: batch size -> batch latency in seconds
PROFILE = {1: 0.020, 2: 0.024, 4: 0.032, 8: 0.048, 16: 0.080, 32: 0.144}
def choose_batch(profile, p99_budget_s, max_wait_s):
"""Return (batch_size, per_replica_rps) with the highest throughput
whose worst-case latency fits the budget."""
best = None
for size, lat in sorted(profile.items()):
worst = max_wait_s + 2 * lat
if worst > p99_budget_s:
continue
rps = size / lat
if best is None or rps > best[1]:
best = (size, rps)
if best is None:
raise ValueError("no batch size meets the latency budget")
return best
def replicas_for(target_rps, per_replica_rps, utilization=0.7, minimum=2):
return max(minimum, math.ceil(target_rps / (per_replica_rps * utilization)))
size, rps = choose_batch(PROFILE, p99_budget_s=0.150, max_wait_s=0.005)
print(f"max_batch_size={size}, per-replica throughput={rps:.1f} req/s")
print("replicas for 400 req/s:", replicas_for(400, rps))With a 150 ms budget, batch size 16 is rejected because 0.005 + 2 * 0.080 = 0.165 s is over budget. Batch size 8 passes at about 101 ms. The script prints a throughput of 166.7 req/s per replica and 4 replicas for 400 req/s.
The profile shows why bigger is not always better. Going from batch 8 to 16 doubles latency from 48 to 80 ms (not quite double) but raises throughput only from 166.7 to 200 req/s. Going to 32 gives 222 req/s at 144 ms. The gains flatten while latency keeps growing.
Matching the scaling signal to the batch size
The spine's HPA example scales on inference_queue_depth with an average target of 4 per pod. That number is not arbitrary. It should relate to the batch size.
- With
max_batch_size = 8, a queue of 4 means a batch is about half full and waiting. The replica is not yet saturated. - A queue of 16 means two full batches are waiting. A request at the back waits for about two batch runs plus its own.
- A queue target well above one or two batches means the HPA will not react until latency has already broken the objective.
A practical starting rule: set the queue depth target to between half a batch and one batch per replica. Then raise it only if load tests show you can afford more waiting.
Avoid GPU utilization as the only signal. A GPU running batch size 1 constantly can show high utilization while carrying little traffic. A GPU running full batches can show the same number. Utilization does not tell you how close you are to the latency limit, but queue depth and in-flight requests do.
Headroom for cold start
A new replica is useless until it has pulled the image, loaded weights, and run warmup requests. If that takes 90 seconds, the existing replicas must carry any traffic growth for 90 seconds.
A rough headroom rule:
extra_capacity_rps = traffic_growth_rps_per_s * cold_start_s
If traffic can grow by 2 req/s every second and cold start is 90 seconds, you need about 180 req/s of spare capacity, or 1 to 2 additional replicas at 167 req/s each, before the scale-up even starts. You can pay for this headroom in three ways:
- A lower target utilization, such as 0.6 instead of 0.7.
- A higher
minReplicas. - A shorter cold start, through smaller images, cached weights, and faster warmup.
The scale-up policy in the spine example uses stabilizationWindowSeconds: 0 so scaling out is immediate. Keep scale-down slow (300 seconds in the example) so that a brief dip does not remove replicas you will need again in a minute.
Failure modes seen in practice
- Queue delay hides in the latency budget. A 50 ms queue delay on a 100 ms objective leaves 50 ms for two batch runs. Start with a delay of a few milliseconds.
- Scaling on the wrong signal. CPU-based scaling for a GPU model usually never fires. Choose a signal that rises when the model is the bottleneck.
- Flapping. Scale-up shrinks the queue, the signal drops, the HPA scales down, and the queue returns. A long scale-down stabilization window and a signal averaged over a minute prevent this.
- Scale-down during a batch burst. Removing a replica that holds in-flight batches can fail requests. Set a termination grace period longer than your worst batch latency plus the queue delay, and drain before exit.
- Testing at steady state only. Steady traffic hides cold-start gaps and scale-up lag. Always include a ramp and a spike.
- Idle overhead at low traffic. At low load, batches rarely fill, so every request pays the full queue delay for no throughput gain. Check p50 at the lowest traffic level, not only at peak.
Validation checklist
Run a ramp from about 20% of expected peak to 150% over several minutes, then hold. During the run, watch these for each stage:
- p99 end-to-end latency against the objective.
- Mean batch size actually formed (it should rise with load and stay below the maximum at low load).
- Queue depth per pod and its relationship to the HPA target.
- Replica count over time, and the delay between the signal crossing the target and new pods becoming ready.
- Error and timeout rates during scale-down.
If p99 breaks while the queue depth is still below target, the signal is too slow or the target too high. If p99 holds but the replica count is far above what the capacity math predicted, the batches are not filling, so check the queue delay and traffic mix.
Exercise
A model service has a 200 ms p99 objective and a 10 ms max queue delay. Its measured batch latencies are 30 ms at batch 4, 60 ms at batch 8, and 100 ms at batch 16. Using the worst-case rule maxwait + 2 * batchlatency, which batch size gives the highest throughput within the objective, and how many replicas are needed for 500 req/s at 0.7 utilization? Then state a reasonable starting queue depth target per pod for the HPA.
Show answer
Worst case at batch 4 is 10 + 60 = 70 ms, at batch 8 is 10 + 120 = 130 ms, and at batch 16 is 10 + 200 = 210 ms, which is over 200 ms. So batch 16 is out. Throughput is 4/0.030 = 133 req/s at batch 4 and 8/0.060 = 133 req/s at batch 8, which are equal, so choose batch 4 for lower latency (or batch 8 if you prefer fewer, fuller batches). Using 133.3 req/s: replicas = ceil(500 / (133.3 * 0.7)) = ceil(5.36) = 6. A starting queue depth target is about half a batch to one batch per pod: 2 for batch 4. Adjust it after a ramp test.