Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Load balancer / router | The component that chooses which replica receives each request. |
| Round robin | Send each request to the next replica in turn: 1, 2, 3, …, 1, 2, 3. |
| Prefix cache | A replica’s store of KV cache for prompt beginnings it has already seen, so it need not compute them again (12.m). It is local to that replica. |
| Session affinity | Sending every turn of one conversation to the same replica, so its earlier turns are already cached there. |
| Power of two choices | Pick two replicas at random and send the request to the less loaded one. |
| Herding | Many routers seeing the same “least loaded” replica and all sending to it at once, overloading it. |
| Endpoint picker | In Kubernetes, the service that scores replicas for each request and tells the gateway which one to use. |
1. Problem → Why → Optimization#
PROBLEM Standard load balancing (round robin, least connections) works badly for LLM
serving: some replicas queue while others idle, and prefix cache hit rates
collapse.
WHY LLM requests differ in cost by 1,000×, last seconds to minutes, and run much
faster on a replica that already holds their prefix. None of that is true of
ordinary web traffic.
OPTIMIZE Route on real load signals, sample instead of searching (power of two
choices), keep conversations where their cache is, and separate the very
long requests.This lesson covers choosing a replica inside one pool. Choosing a model and a pool (21.g) and scoring replicas by the exact cached blocks they hold (21.h) build on it.
Facts checked on 12 November 2026.
2. Why the standard algorithms fail#
ROUND ROBIN
Assumes every request costs about the same. They do not. One replica can get three
100,000-token prompts in a row while another gets three 50-token ones.
RANDOM
The same problem, plus extra variance.
LEAST CONNECTIONS
Better: it counts requests in flight. But it cannot see that 2 huge requests are more
work than 8 tiny ones.
LEAST RESPONSE TIME
Reacts to the symptom after it has happened. For requests lasting minutes, the signal
arrives far too late.And all four throw away the prefix cache. Turn 5 of a conversation lands on a different replica from turn 4, which must compute the whole history again. With 8 replicas, only about 1 turn in 8 lands where its history is cached.
3. Simple analogy#
Sending patients to doctors.
Round robin: the next patient goes to the next doctor in rotation. Fine if every appointment is 10 minutes; terrible when they range from 5 minutes to 4 hours.
Least connections: the next patient goes to the doctor with the fewest patients. Better, but a doctor with one 4-hour operation is busier than one with three quick check-ups.
What you want: send by remaining work, and send returning patients to the doctor who already has their file (affinity), unless that doctor is swamped.
4. Tiny example: five routers, one workload#
Eight replicas, each with 16 slots. Chat traffic from 2,000 conversations; each turn adds 300 tokens of history, and answers have heavy-tailed lengths. A replica that served a conversation’s last turn has its history cached and prefills only the new 300 tokens; any other replica must prefill the whole history. Load is 34 requests per second, about 85% of capacity when nothing is cached.
// lb.go — ways to pick a replica, on multi-turn chat traffic with a prefix cache.
package main
import (
"fmt"
"math"
"math/rand"
"slices"
)
const (
replicas = 8
slots = 16 // concurrent requests per replica
prefillTPS = 20000.0 // prompt tokens per second per replica
itl = 0.03 // seconds per output token
turnTokens = 300 // new tokens each conversation turn adds
rate = 34.0 // requests per second, about 85% of capacity without cache hits
)
type replica struct {
free []float64 // when each slot frees up
done []float64 // finish times of requests not yet finished
}
// inFlight is the load signal the router sees: requests running or queued at time t.
func (r *replica) inFlight(t float64) int {
live := r.done[:0]
for _, d := range r.done {
if d > t {
live = append(live, d)
}
}
r.done = live
return len(live)
}
func run(policy string) (p50, p99, hit float64) {
rng := rand.New(rand.NewSource(7))
rs := make([]*replica, replicas)
for i := range rs {
rs[i] = &replica{free: make([]float64, slots)}
}
ctx := make([]float64, 2000) // each conversation's history, in tokens
home := make([]int, len(ctx)) // replica that served its last turn (-1: none)
for i := range home {
home[i] = -1
}
next := 0
var ttfts []float64
hits, reqs := 0, 0
for t := 0.0; t < 1800; t += rng.ExpFloat64() / rate {
c := rng.Intn(len(ctx))
if ctx[c] > 30000 || rng.Float64() < 0.02 { // conversation ends; a new one starts
ctx[c], home[c] = 0, -1
}
ctx[c] += turnTokens
out := math.Min(4000, 60*math.Exp(rng.NormFloat64())) // heavy-tailed answer length
p2c := func() int { // power of two choices
a, b := rng.Intn(replicas), rng.Intn(replicas)
if rs[a].inFlight(t) <= rs[b].inFlight(t) {
return a
}
return b
}
var i int
switch policy {
case "round robin":
i, next = next, (next+1)%replicas
case "random":
i = rng.Intn(replicas)
case "least loaded (all 8)":
for j := range rs {
if rs[j].inFlight(t) < rs[i].inFlight(t) {
i = j
}
}
case "power of two":
i = p2c()
case "p2c + affinity":
i = p2c()
if h := home[c]; h >= 0 && rs[h].inFlight(t) <= rs[i].inFlight(t)+4 { // release valve
i = h
}
}
uncached := ctx[c]
if home[c] == i {
uncached = turnTokens // the rest of the prompt is in this replica's prefix cache
hits++
}
reqs++
home[c] = i
r := rs[i]
k := slices.Index(r.free, slices.Min(r.free))
start := math.Max(t, r.free[k])
first := start + uncached/prefillTPS
r.free[k] = first + out*itl
r.done = append(r.done, r.free[k])
if t > 300 { // skip the warm-up
ttfts = append(ttfts, first-t)
}
}
slices.Sort(ttfts)
n := len(ttfts)
return ttfts[n/2], ttfts[n*99/100], float64(hits) / float64(reqs)
}
func main() {
fmt.Println("policy p50 TTFT p99 TTFT prefix hits")
for _, p := range []string{"round robin", "random", "least loaded (all 8)", "power of two", "p2c + affinity"} {
p50, p99, hit := run(p)
fmt.Printf("%-21s %7.2f s %7.2f s %5.0f%%\n", p, p50, p99, hit*100)
}
}Output:
policy p50 TTFT p99 TTFT prefix hits
round robin 0.24 s 4.10 s 12%
random 0.29 s 5.40 s 12%
least loaded (all 8) 0.19 s 0.59 s 12%
power of two 0.20 s 0.87 s 12%
p2c + affinity 0.02 s 0.59 s 85%How to read it:
- Round robin and random have fine medians and terrible tails (4–5 s at p99): some replicas queue while others sit idle.
- Looking at load fixes the tail. Checking all 8 is best here, because this simulation has one router with perfect, instant information. Real fleets have many router instances reading metrics a second or more old, and “everyone picks the same least-loaded replica” (herding) appears. Power of two choices gets most of the benefit and cannot herd.
- Affinity is the big jump: 85% of turns hit the cache, so the median time to first token falls tenfold and the GPUs do far less prefill. The release valve (go elsewhere if the home replica has 4 more requests in flight than the alternative) keeps the tail in check.
- Hit rate stays at 1 in 8 (12%) for every policy without affinity: chance.
The load signal here is requests in flight, because slots are what runs out in this model. In a real engine, use whatever is binding, usually KV cache use and queued work (section 5).
5. Technical explanation#
The load signals#
SIGNAL QUALITY WHERE IT COMES FROM
requests in flight poor the router counts them
queue depth (waiting) ok the replica: vllm:num_requests_waiting
KV cache use GOOD the replica: vllm:kv_cache_usage_perc
running batch size good the replica: vllm:num_requests_running
queued prompt tokens GOOD the replica, or the router's own count
chance the prefix is cached GOOD the router's view of each replica's cache
recent p95 TTFT lagging the router measures itKV cache use is usually the best single load signal, because KV memory is usually the binding constraint: a replica at 95% cannot start more work, however few requests it holds. Combine it with the waiting queue, since a replica can have free memory and a long queue of prefills.
Replicas expose these on /metrics (19.c). Routers scrape them every few hundred milliseconds
to a few seconds, or count in-flight work themselves between scrapes so they are never far out
of date.
Power of two choices#
// Power of two choices: sample 2 replicas, not all N, and take the less loaded.
func route(replicas []*Replica) *Replica {
a, b := replicas[rand.Intn(len(replicas))], replicas[rand.Intn(len(replicas))]
if a.KVUtilization() < b.KVUtilization() {
return a
}
return b
}This is the right default. Mitzenmacher showed that sampling two and taking the better one gives almost all the benefit of checking every replica. Because each router samples a different pair, many routers acting on the same stale numbers do not all choose the same replica.
Affinity: keep a conversation near its cache#
The simplest version routes by a conversation id:
hash(conversation_id) → replica consistent hashing, so adding or removing a
replica moves only about 1/N of conversationsIt captures most of the benefit for chat, because every turn of a conversation starts with the same history. Always pair it with a release valve: if the home replica is much busier than the alternative, go elsewhere and accept one cold cache.
Prefix-aware routing generalises this: the router tracks which prompt prefixes (system prompts, shared documents, agent tool lists) each replica holds and scores replicas on expected cache hit and load together:
score(replica) = w1 × expected cached fraction of this prompt
− w2 × KV cache use
− w3 × queued workHow to track prefixes, approximate versus exact cache views, and how to set the weights are in lesson 21.h.
Separate the expensive requests#
if prompt_tokens > 32,000: send to the long-context pool
elif max_tokens > 4,000: send to the long-generation pool
else: send to the general poolSeparating long requests is one of the most valuable routing decisions. One 128,000-token request on a replica tuned for 4,000-token chat takes the KV memory of 32 normal requests and a long prefill that every streaming user on that replica feels. A pool of its own can use a different token budget and memory setting (20.d). Pool design is in 21.g.
Kubernetes: the Gateway API Inference Extension#
On Kubernetes, model-aware routing has a standard. The Gateway API Inference Extension
defines InferencePool, a stable v1 resource that stands for a set of model-server pods. A
gateway that implements it (Istio, agentgateway, NGINX Gateway Fabric, GKE’s Inference Gateway
and others) asks an endpoint picker which pod to use for each request. The picker scores the
pods on queue depth, KV cache use and prefix affinity, and can hold requests back when every pod
is full.
In release v1.6 (August 2026) the full endpoint picker, and the alpha InferenceObjective API
for request priority, moved to the llm-d project; the Inference Extension now keeps the core
API, conformance tests and a small reference picker. If you are on Kubernetes, start from these
rather than writing a balancer (21.i, 21.j).
6. Under the hood: the load balancer’s own constraints#
Streaming responses hold a connection for the whole generation:
- the load balancer must not buffer responses (9.a)
- per-backend connection limits must be high
- idle timeouts must be longer than the longest pause in a stream
- draining a replica means waiting for its in-flight generations (20.g)
Health checking:
- use the cheap health endpoint, never a real generation (20.b)
- a replica at 100% KV cache use is BUSY, not unhealthy:
keep it in the pool, just stop preferring itThat last point matters. A balancer that removes saturated replicas from the pool pushes their load onto the others, which then saturate and are removed too. The failure cascades across the fleet.
7. Performance implications#
- The tail is where routing pays. Section 4: a load-aware router cuts p99 time to first token from 4 s to under 1 s at the same load, with no extra GPUs.
- Affinity cuts work, not just waiting. Every cache hit is prefill the GPU does not do, so the same fleet carries more traffic. How much depends on how much of each prompt repeats: multi-turn chat and agents with long histories gain most; one-shot requests with unique prompts gain nothing.
- Stale signals cost more as load rises. At 50% load almost any policy works; near the knee (20.c), a few seconds of staleness decides whether replicas take turns being overloaded.
- Affinity has a ceiling. Push it too hard and one popular prefix or one long conversation overloads its replica. The release valve threshold is the knob; tune it on p99, not p50.
8. Production implications#
- Do not use a stock HTTP balancer’s default for LLM traffic. It will be round robin or least connections.
- Expose load metrics from replicas and route on KV cache use and queued work.
- Use power of two choices rather than global least-loaded across many router instances.
- Add session affinity for chat and agents, with a release valve.
- Separate long-context and long-generation traffic into their own pools.
- Never remove a busy replica from the pool. Lower its preference instead.
- Turn off response buffering, raise connection limits, extend idle timeouts at every proxy.
- On Kubernetes, use an
InferencePooland an endpoint picker (llm-d’s, or your gateway vendor’s) before writing your own.
9. Common mistakes#
- Round robin with prefix caching enabled. You built the cache and then made it miss.
- Global least-loaded across many router instances. They all pick the same replica at once; it overloads; they all move together. Oscillation.
- Removing busy replicas from the pool. Cascading failure.
- Health checks that run real generations. GPU time wasted on checks.
- Mixing very long and short requests in one pool.
- Buffering at the load balancer. Streaming arrives in one lump at the end.
- Affinity without a release valve. One heavy conversation overloads a replica.
10. Hands-on exercise#
A. Run the simulation. Run lb.go. Raise rate to 38 and lower it to 20. At which load do
the policies stop differing?
B. Stale signals. Make the routers see load as it was 2 seconds ago (record in-flight counts every 2 s and route on the recorded value). How do “least loaded (all 8)” and “power of two” compare now?
C. Tune the valve. Change the affinity release threshold from +4 to +0, +2, +8 and
+1000 (never release). Plot prefix hit rate and p99 time to first token. Where is the best
trade?
D. Real routing. Put a small router in front of 2–4 real vLLM replicas. Route on
vllm:kv_cache_usage_perc scraped from /metrics, then add affinity on a conversation id
header. Compare time to first token and vllm:prefix_cache_hits against round robin.
E. Separation. Add 1% of requests with 100,000-token prompts to the simulation. Measure p99 time to first token for short requests with one shared pool, then with the long ones sent to a pool of their own.
11. Interview questions#
- Give two independent reasons round robin performs badly for LLM serving.
- What is the best load signal for an LLM replica, and why?
- What is power of two choices, and what problem does it solve that “pick the least loaded” does not?
- How do you balance prefix cache affinity against load?
- Why should you not remove a saturated replica from the pool?
- Why separate long-context requests, and what does it buy?
- What must a load balancer be configured for, to carry streaming responses?
- What does the Gateway API Inference Extension standardise, and what does it leave to an endpoint picker?
12. Further reading#
Checked on 12 November 2026.
- [FUNDAMENTAL] Mitzenmacher, “The Power of Two Choices in Randomized Load Balancing” (IEEE TPDS, 2001)
- [ESTABLISHED] Zheng et al., “SGLang: Efficient Execution of Structured Language Model Programs” — cache-aware scheduling and routing
- [REFERENCE] Gateway API Inference Extension and its v1.6.0 release notes — endpoint picker and
InferenceObjectivemoved to llm-d - [REFERENCE] Inference Extension gateway implementations
- [REFERENCE] Envoy load balancers — the general algorithms, including least request with power of two choices