Sub topic 3
Static batching and its limits
This chapter assumes you can serve a model behind an HTTP or gRPC endpoint, read basic Python, and interpret p50 and p99 latency. The previous chapter explained why accelerators run faster per item on larger batches. Here you will see the simplest way to get those batches, and why it breaks down under real traffic.
What static batching means
Static batching groups inputs into a batch whose size is decided in advance and does not react to traffic. The batch size is fixed by the code that builds the batch, not by what is waiting at the server.
It appears in two common forms:
- Offline batching. A job reads a dataset, splits it into chunks of exactly N rows, and runs the model on each chunk. Nobody waits on a single answer, so this is a good fit.
- Client-side batching. The caller collects N items, sends them in one request, and the server runs the request as one batch. The server does no grouping of its own.
A third form is a server that holds requests until it has exactly N of them. That is the form this chapter simulates, because it shows the latency cost most clearly.
The appeal is simplicity. Shapes are known ahead of time, so you can compile or warm the model for one batch size. Throughput is predictable, and the code is short.
Where it works well
Static batching is a good choice when all of these hold:
- Latency per item does not matter, only total completion time.
- The input is available up front, so batches always fill.
- Item shapes are uniform, or you can sort and bucket them cheaply.
Nightly scoring, embedding a document archive, and evaluation runs fit this description. You can pick the largest batch that fits in accelerator memory and keep the device busy.
The core problem: waiting for a full batch
In an online service, requests arrive one at a time at random moments. If the server dispatches only when exactly N have accumulated, early arrivals wait for later ones.
For arrivals at rate r requests per second, the k-th request in a batch of size B waits for the remaining B − k arrivals, which takes about (B − k) / r seconds. The first request waits about (B − 1) / r. Averaged over the batch, the added wait is about (B − 1) / (2r).
This wait is independent of how fast the model is. It depends only on the batch size and the arrival rate, and it grows as traffic falls. The following simulation makes that concrete.
import random
def simulate_static(arrival_rate_rps, batch_size, n_requests=20000, seed=0):
"""Fixed-size batching: a batch is dispatched only when it is full.
Returns (mean_wait_s, p99_wait_s), the time requests spend waiting
for the batch to fill. Model compute time is not included.
"""
rng = random.Random(seed)
t = 0.0
arrivals = []
for _ in range(n_requests):
t += rng.expovariate(arrival_rate_rps) # Poisson arrivals
arrivals.append(t)
waits = []
for start in range(0, n_requests - batch_size + 1, batch_size):
group = arrivals[start:start + batch_size]
dispatch_time = group[-1] # the last arrival completes the batch
waits.extend(dispatch_time - a for a in group)
waits.sort()
mean = sum(waits) / len(waits)
p99 = waits[int(0.99 * (len(waits) - 1))]
return mean, p99
for rate in (5, 50, 500):
mean, p99 = simulate_static(rate, batch_size=16)
print(f"{rate:>4} req/s mean wait {mean * 1000:8.1f} ms p99 wait {p99 * 1000:8.1f} ms")With a batch size of 16, the mean wait should land near 7.5 / r. That is about 1.5 s at 5 req/s, 150 ms at 50 req/s, and 15 ms at 500 req/s. The p99 is higher, because it is set by the first requests in each batch.
The same configuration is acceptable at 500 req/s and unusable at 5 req/s. A server tuned at peak load will behave badly overnight.
Limit 1: unbounded wait and the stuck last batch
If traffic stops while a partial batch is waiting, those requests never run. The queue holds them until enough new requests arrive, which may be minutes or never. A strict fixed-size server therefore has no upper bound on waiting time.
The usual patch is a timeout that flushes a partial batch. That fixes the stuck request but changes the design: batch size now varies with traffic, and you have moved to dynamic batching. The next chapter covers it.
Limit 2: padding waste with variable-length inputs
Most batched tensors must have one shape. When inputs differ in length, short ones are padded to the longest in the batch, and the accelerator computes on the padding.
Take four sequences of 12, 40, 128, and 7 tokens. Padded to 128, the batch holds 4 × 128 = 512 token positions, but only 12 + 40 + 128 + 7 = 187 carry real data. That is about 36.5% useful work. A larger fixed batch makes this worse, since it raises the chance that one long input forces padding on everyone.
Common mitigations:
- Sort or bucket inputs by length before batching. This works offline and is hard online, because you cannot reorder requests that have not arrived.
- Cap input length and truncate or reject longer inputs.
- Use a model or runtime that supports ragged inputs.
Limit 3: coupling clients to server internals
With client-side batching, every caller must know the right batch size, and that value depends on the server's hardware, model, and memory. If you change the GPU type or the model, every client may need updating.
It also pushes work onto the callers. A web frontend serving one user at a time has nothing to batch with. It would need a shared gateway to collect requests from many users, and that gateway is a batcher you now have to build and operate.
Limit 4: all-or-nothing failures and head-of-line blocking
A client-submitted batch succeeds or fails as one request in most APIs. One malformed item can reject the other 31, or force the client to retry everything. Error handling then has to split the batch, which is extra logic on both sides.
A large batch also occupies the accelerator for its full runtime. A small urgent request that arrives just after must wait for the entire batch to finish. This is head-of-line blocking, and it inflates tail latency. Tail latency gets its own chapter.
Limit 5: poor fit with bursty traffic and autoscaling
A fixed batch size is a single point tuned for one load level. At low load it is too large and requests wait. At high load it may be too small, and you pay per-batch overhead more often than needed. Under bursts, a fixed batch gives you no way to trade latency against throughput on the fly.
It also interacts badly with scaling. When you add replicas, traffic is split across more queues, so each queue fills more slowly and waits grow. Scaling out can raise latency under static batching, the opposite of what you want.
Summary of trade-offs
| Property | Static batching | What you would want online |
|---|---|---|
| Batch size | Fixed in advance | Adapts to arrivals |
| Wait for a full batch | About (B − 1) / (2r) on average, unbounded at low load | Bounded by a deadline |
| Padding | Set by the longest item in the group | Reduced by grouping or ragged input |
| Client coupling | Clients must know the batch size | Clients send single items |
| Failure scope | Whole batch | Per request |
| Best use | Offline jobs, uniform inputs | Interactive services |
Choosing between them
Use static batching when the work is a job, not a service. Ask three questions:
- Does a person or another service wait on each individual result?
- Does arrival rate vary enough that a full batch could take longer than your latency budget?
- Are inputs of very different sizes mixed in the same stream?
If the answer to any of these is yes, fixed-size batching will cost you latency or compute. The server should form batches from whatever has arrived, within a time limit. That is the subject of the next chapter.
Exercise
A service uses server-side static batching with a batch size of 8 and receives 20 requests per second on average, with Poisson arrivals. Estimate (a) the average wait added by batching and (b) the average wait of the first request in each batch. Then say what happens when traffic drops to 2 requests per second.
Show answer
(a) The average added wait is about (B − 1) / (2r) = 7 / (2 × 20) = 0.175 s, or 175 ms. (b) The first request waits for 7 more arrivals, about 7 / 20 = 0.35 s, or 350 ms. At 2 requests per second the average wait grows to 7 / (2 × 2) = 1.75 s, and the first request waits about 3.5 s. Any partial batch left when traffic stops waits indefinitely, because nothing flushes it.
Exercise
A fixed batch contains inputs of 20, 20, 20, and 100 tokens, padded to the longest. What fraction of the computed positions is real data, and what does this tell you about mixing lengths in a static batch?
Show answer
The batch computes 4 × 100 = 400 positions. Real tokens are 20 + 20 + 20 + 100 = 160, so 160 / 400 = 40% is useful. One long input forces the other three to pad to 100, so mixing very different lengths in a fixed batch wastes most of the compute. Bucketing by length before batching would reduce this.