Load balancing
Spread requests across replicas so none overloads and dead ones get skipped; for LLM serving, pick by live load (queue depth, KV-cache use) and prefix affinity, because request costs differ by orders of magnitude.
Analogy: Supermarket checkouts: a greeter sending shoppers to each lane in turn (round robin) ignores that one cart holds 80 items. Glancing at two lanes and picking the shorter (power of two choices) works almost as well as checking them all.
How it works
- L4 balances TCP connections; L7 parses HTTP and balances requests, routing by path or header.
- gRPC multiplexes many requests on one HTTP/2 connection, so behind L4 they all land on one replica.
- Power of two choices: sample two replicas, send to the less loaded; nearly as good as checking all.
- Combine active probes with passive outlier ejection, which pulls a host after consecutive 5xx.
- For LLMs, add prefix-aware routing: requests sharing a system prompt go to the replica already caching it.
Check yourself
Answer to mark it learned; your answers aren't scored.
You added prefix-aware routing to 8 LLM replicas. A launch puts one shared system prompt on ~70% of traffic: its home replica's queue explodes while the other 7 sit idle. Best fix?
Go deeper
Full explanation
A load balancer sits in front of N replicas and picks one per connection or request, skipping unhealthy ones.
L4 vs L7. L4 (AWS NLB, Google Maglev, IPVS) balances TCP connections: fast and protocol-blind. L7 (Envoy, NGINX, HAProxy, AWS ALB) parses HTTP/gRPC, balances requests, routes by path or header and can retry. gRPC multiplexes many requests on one long-lived HTTP/2 connection, so behind L4 they all land on one replica.
Algorithms:
- Round robin: fine when requests cost the same.
- Least connections / outstanding requests: adapts to slow requests.
- Power of two choices (P2C): sample two replicas, send to the less loaded. Nearly as good as checking all, no global state; Envoy's least-request default.
- Consistent hashing: same key → same replica, for cache affinity.
Health: active probes plus passive outlier ejection (pull a host after consecutive 5xx). Sticky sessions pin users to replicas; avoid them unless state truly lives there.
LLM serving breaks round robin. A 100k-token RAG prompt costs hundreds of times a 200-token chat turn. Route on queue depth and KV cache usage exported by each server, and add prefix-aware routing: requests sharing a system prompt or conversation go to the replica already caching that prefix, skipping most of the prefill. The Kubernetes Gateway API Inference Extension, llm-d and the SGLang router do this.
Code P2C picker with prefix affinity for LLM replicas
import hashlib, random
from dataclasses import dataclass
@dataclass
class Replica:
url: str
queued_tokens: int = 0 # prompt + expected output tokens waiting (scraped)
kv_usage: float = 0.0 # 0..1 KV-cache utilization (scraped)
healthy: bool = True # active probe + outlier ejection
def load(r: Replica) -> float:
# Near-full KV cache means preemptions soon: penalize it hard
return r.queued_tokens * (1 + 10 * max(0.0, r.kv_usage - 0.9))
def home_for(prefix: str, live: list[Replica]) -> Replica:
# Rendezvous hashing: same prefix -> same replica; few keys move on churn
return max(live, key=lambda r: hashlib.sha1(f"{r.url}|{prefix}".encode()).digest())
def pick(replicas: list[Replica], prompt: str, slack: float = 1.5) -> Replica:
live = [r for r in replicas if r.healthy]
home = home_for(prompt[:4000], live) # system prompt + early turns
a, b = random.sample(live, 2) if len(live) > 1 else (live[0], live[0]) # P2C
best = min(a, b, key=load)
# Prefer the cache hit unless home is clearly busier than a random alternative
return home if load(home) <= slack * load(best) + 1000 else bestReal example
A team serves a 70B model on 8 vLLM replicas behind round robin. Traffic mixes 300-token chat turns with 60k-token document reviews. Round robin stacks three reviews on one replica: its queue hits 40 requests and TTFT p95 reaches 12 s while others idle. Switching to P2C on queued tokens flattens the queues; adding prefix affinity for the shared 4k-token system prompt and each conversation raises prefix-cache hits, and TTFT p95 drops to ~1.5 s on the same GPUs.
Trade-offs +3 · −3
+ You gain
- Horizontal scale and zero-downtime deploys: drain, replace and re-add replicas.
- Health checks and outlier ejection route around failures automatically.
- Load- and prefix-aware routing raises LLM throughput and cuts TTFT on the same GPUs.
− You pay
- The balancer must itself be redundant, or it becomes the single point of failure.
- L7 costs CPU and latency per request: TLS termination, parsing, routing logic.
- Load signals are stale by the time you act on them, and affinity pulls against balance.
Use it when
Any service with more than one replica. L7 for HTTP/gRPC and per-request decisions; load- and prefix-aware routing for self-hosted LLM fleets with mixed prompt lengths.
Avoid it when
Plain round robin when request costs vary widely, as in LLM inference. Sticky sessions as a substitute for moving state into Redis or a database.
Numbers to know 4
- Placing n requests on n servers: one random pick gives a max load of ~log n / log log n; best of two random picks gives ~log log n.
- Consistent hashing moves ~1/N of keys when one of N nodes leaves; hash mod N moves almost all of them.
- Envoy outlier detection defaults: eject after 5 consecutive 5xx, 30 s base ejection, at most 10% of hosts.
- LLM prefill cost spans ~500×: a 100k-token prompt vs a 200-token chat turn, before counting output.
Common pitfalls 4
- L4 balancing for gRPC/HTTP2: long-lived connections pin all traffic to a few replicas, and new ones get none.
- Health checks that only prove the process is up: a replica with a broken GPU or full KV cache still gets traffic.
- Round robin across LLM replicas with mixed prompt lengths: some queues explode while GPUs elsewhere idle.
- Prefix affinity without a load cap: one viral system prompt melts its home replica.
Interview questions 3
Answer out loud first, then reveal.
Why is round robin a bad fit for an LLM serving fleet, and what do you use instead?Show answer
Round robin assumes requests cost about the same, and LLM requests don't: prompt length varies 100× and output length is unknown upfront. Queues diverge, and one replica's TTFT explodes while others idle. I route on live signals each replica exports, queued tokens and KV-cache usage, with power of two choices so I don't need a global view. On top I add prefix affinity: requests sharing a system prompt or conversation go to the replica that already caches that prefix, with a load cap so a hot prefix can spill over.
L4 or L7 load balancer for a gRPC microservice?Show answer
L7. gRPC runs on HTTP/2, which multiplexes a client's requests over one long-lived connection. An L4 balancer picks a backend per connection, so each client stays pinned to one replica and new replicas get nothing after a scale-up. An L7 proxy like Envoy, or client-side balancing through a service mesh, balances each request. I'd still keep L4 at the very edge for raw TCP throughput and DDoS absorption, with L7 behind it.
A replica is up but returning errors. How does the balancer find out?Show answer
Active health checks catch dead processes, not sick ones, so I add passive outlier detection on real traffic: eject a host after consecutive 5xx or when its success rate is far below the fleet's, for a period that grows with each ejection, and cap the ejected percentage so a bad detector can't empty the pool. For LLM replicas, the readiness probe should exercise the model with a tiny generation, not just get a 200 from the web server.