Load Balancing
Distribute inference traffic across replicas and regions fairly.
In plain words
A load balancer is a traffic director that spreads incoming requests over several copies of your app so none gets swamped, and skips copies that are broken.
Think of it like…
A supermarket opening checkout lanes: sending each customer to the next lane in turn ignores that one has a full trolley and another a single item; directing people to the shortest queue, or sending regulars to their usual cashier who knows their coupons (cache), works better.
Where you’ve seen it
Two replicas receive alternating requests that take 1 second and 9 seconds. With round-robin, replica A gets every 1-second request and replica B every 9-second one: over 20 requests A is busy 10 s and B 90 s, a 9 : 1 imbalance, so B's queue grows and the p95 latency suffers while A idles. A least-outstanding-requests policy routes each new request to the replica with fewer in-flight requests and balances the load to roughly 50 s each. For a self-hosted model fleet the team uses consistent hashing on a prompt-prefix key (system prompt + conversation id) with bounded loads, which lifts the prefix-cache hit rate from 12% (random routing) to 78% and cuts time to first token by about 0.3 s. The Layer 7 balancer has an idle timeout of 300 seconds (the default was 60 and was cutting off long streams), health checks that mark a replica unhealthy after 3 failed /readyz probes, connection draining of 120 seconds on deployments so in-flight streams finish, retries limited to idempotent calls with a retry budget, and cross-zone balancing for availability. A latency-based DNS or global load balancer routes users to the nearest healthy region with failover.
Words you’ll hear
- Least outstanding requests
- Route to the backend with the fewest in-flight requests.
- Power of two choices
- Sample two backends and pick the less loaded, giving near-optimal balance cheaply.
- Consistent hashing
- Map keys (prefix, user) to backends so the same key goes to the same replica.
- Connection draining
- Letting in-flight requests finish before removing a backend.
Visual diagram
Theory & deep dive
Layers, algorithms and health
L4 (TCP/UDP) balancers (NLB, HAProxy in TCP mode) forward connections quickly with minimal inspection; L7 (HTTP/gRPC) balancers (ALB, NGINX, Envoy, Traefik, cloud gateways) parse requests, so they can route by host, path or header, terminate TLS, add authentication and rate limits, retry and support HTTP/2, WebSockets and SSE. Algorithms: round-robin and random are simple and fine for uniform requests; least connections (or least outstanding requests) accounts for in-flight work; weighted variants handle heterogeneous replicas (a larger GPU gets more traffic); power of two choices (pick two at random, send to the one with fewer in-flight requests) is almost as good as global least-loaded with far less coordination, and its maximum load grows like ln ln n instead of ln n / ln ln n for purely random assignment.
Health checks remove bad backends: active probes to /readyz every few seconds with a failure threshold (3 consecutive failures), plus passive detection from error rates. Use the readiness semantics (model loaded, dependencies reachable) so a replica receiving traffic can really serve it, and add outlier detection to eject replicas with high error or latency. Sticky sessions (cookie or IP hash) are usually unnecessary if conversation state lives in a shared store, and they reduce balance; use them only when a replica holds irreplaceable local state. For multi-region, use latency-based or geolocation routing with health-based failover and consider data residency rules.
Requests alternate 1 s and 9 s across two replicas. Round-robin: replica A gets ten 1 s requests (10 s of work), replica B ten 9 s requests (90 s): imbalance 9:1. Least-outstanding-requests spreads the work to about 50 s each, cutting the worst queue by 44%.
AI-specific concerns: streaming, caches and deployments
Streaming and timeouts: SSE and WebSocket connections stay open for seconds to minutes, so raise idle and request timeouts (the default 60 s on many balancers cuts long generations; 300 s in the example), disable response buffering, enable HTTP/2 or keep-alive and send periodic heartbeats. Cache-aware routing: serving engines reuse KV cache for shared prefixes, so route requests with the same prefix key to the same replica with consistent hashing (with bounded loads so a hot key can't overload one replica), lifting the prefix hit rate from 12% to 78% and trimming TTFT by about 0.3 s in the example. For conversational traffic, hash on the conversation id; for multi-tenant systems, hash on tenant plus prefix and mind cross-tenant cache isolation.
Deployments and failures: use connection draining (for example 120 s) so in-flight streams finish before a replica is terminated; align it with the pod termination grace period. Limit retries to idempotent requests and set a retry budget so retries don't amplify an outage; avoid retrying after tokens have started streaming. Consider queue-aware gateways for GPU fleets that track per-replica running and waiting requests and route to the least loaded (or use an inference gateway with model-aware metrics). Balance across availability zones to survive a zone outage, keep capacity for failover (N + 1) and test failures with game days. Monitor per-backend request rate, latency, error rate, active connections and cache hit rate, and alert on imbalance (one replica carrying more than twice the average).
Key = hash(system prompt + conversation id). Each replica may receive at most 1.25 × the average load; if the hashed replica is above that, the request goes to the next replica on the ring. This keeps cache affinity for most requests (hit rate 78%) without letting a viral prompt overload one GPU.
How it works, step by step
Step 1 of 41. Choose the layer and algorithm
Use an L7 balancer with least-outstanding or P2C routing and weights for heterogeneous replicas.
- Avoid
- sticky sessions by default
When to use it & trade-offs
What it is
Load balancing distributes requests across multiple backends (replicas, regions, model servers) so no single instance is overloaded and failures are routed around. Layer 4 balancers work on TCP connections; Layer 7 balancers (ALB, NGINX, Envoy, an API gateway) understand HTTP and can route by path or header, terminate TLS, retry and rate-limit. The algorithm matters: round-robin assumes equal request cost, least connections or least outstanding requests adapt to uneven durations, power of two choices picks the less-loaded of two random backends, and consistent hashing sends related requests (a shared prompt prefix, a user or tenant) to the same replica to improve cache hit rates. For LLM traffic, requests last seconds to minutes and vary enormously in cost, so queue-aware and cache-aware balancing, correct timeouts for streaming and graceful draining are central.
Why it matters: LLM requests are long-lived and wildly unequal: a 20-token reply and a 2,000-token reply can differ by a factor of 100 in GPU time. Round-robin, which works for uniform web requests, can pile slow requests onto one replica while others idle, inflating tail latency. Default idle timeouts (often 60 seconds) cut off long streams, and sending a conversation's turns to different replicas defeats prefix caching. Choosing the right balancing strategy improves latency, cost and availability without adding hardware.
When to reach for it
- Spreading traffic across LLM gateway replicas
- Routing to self-hosted model servers with prefix caches
- Multi-region failover
When to avoid or be careful
- Default 60-second idle timeouts for streaming
- Round-robin across wildly unequal requests
- Retrying after a stream has started
Balancing algorithms
Strengths: Simple; no state.
Watch out: Imbalance when request costs vary.
Strengths: Adapts to load; low coordination.
Watch out: Needs in-flight tracking.
Strengths: High cache hit rates.
Watch out: Hot keys need load bounds.
Interview signals & numbers to know
When this topic comes up
- “One replica is hot while others idle”
- Least outstanding requests
- Power of two choices
- Consistent hashing
- Connection draining
Benchmarks & rules of thumb
- 9 : 1
- load imbalance of round-robin with alternating 1 s and 9 s requests
- 12% → 78%
- prefix-cache hit rate with random versus hash routing
- 300 s
- example idle timeout for streaming
Common mistakes & follow-ups
Common interview mistakes
- Using sticky sessions to hold conversation state instead of a shared store.
- Retrying non-idempotent paid calls at the balancer.
- Forgetting to align drain time with the pod termination grace period.
Likely interviewer follow-ups
- Why is round-robin a poor fit for LLM inference?
- How would you route to improve prefix-cache hits?
- How do you avoid cutting off long streams?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Load Balancing with generative AI interview Q&A and hands-on practice.