Load balancing¶
What you'll be able to do¶
- Choose a routing rule for replicas with equal, unequal, or long-running requests.
- Explain how health checks and draining keep a deploy from sending work to an unready instance.
- Identify when a load balancer, its state, or its own failure becomes the bottleneck.
One address, many workers¶
Suppose one inference API process handles 20 requests per second and you need 50. Three replicas provide a nominal 60, if work is similar and dependencies keep up. A load balancer (LB) directs traffic to a pool of backends, choosing a destination for each request or connection. It can stop choosing failed instances, add new ones during scale-out, and shift traffic during rolling deploys.
The choice can happen in several places. A client library may select an instance. DNS round robin can return multiple addresses, but cached answers give coarse control over health and distribution. A hardware appliance, software proxy, or managed cloud LB can choose near the service entrance. A sidecar or service mesh proxy can choose between services. Each layer learns about failures at a different pace.
What the balancer can see¶
An L4 balancer routes using source and destination IP addresses and ports, without reading an HTTP path. TCP has connections; UDP is connectionless, though a balancer may track UDP flows by their address and port tuples. An L7 balancer understands application requests, commonly HTTP. It can route /embed and /generate to different pools, or choose by host or header. Depending on configuration, an L7 proxy can terminate TLS, enforce rate limits, retry eligible requests, and attach a sticky-session cookie. Parsing and TLS termination consume resources. L4 usually has less parsing overhead and can be faster when content-based routing is unnecessary.
A reverse proxy accepts client traffic and forwards it to servers; balancing is one possible job. An API gateway usually adds API policy such as authentication, quotas, and request transformation. These names overlap: check actual features. If the LB terminates TLS, consider encryption on the backend hop and size the termination tier.
Choosing a backend¶
Round robin cycles through healthy replicas and fits similar work on similar servers. Weighted round robin sends more to stronger servers: weights 3 and 1 target about six and two picks over eight. Weights express planned capacity, not queue length. This Python example cycles through two destinations:
from itertools import cycle
pick = cycle(("replica-a", "replica-b"))
print([next(pick) for _ in range(4)])
# ['replica-a', 'replica-b', 'replica-a', 'replica-b']
When durations differ, least connections chooses the replica with the fewest active connections; least outstanding requests considers work still in flight. One long connection makes connection count a poor work estimate. A latency-aware rule can track an exponentially weighted moving average (EWMA) and favor a quicker replica. Observed latency also reflects request mix; routing everything to the quickest-looking replica can overload it.
Power of two choices samples two healthy replicas and selects the less busy one, using two load observations rather than ranking the pool. If half the pool is overloaded, one random choice lands there ½ of the time. Two independent draws with replacement both hit the overloaded half with probability 1/2 × 1/2 = 1/4. Sampling two distinct backends makes that slightly lower: 2/4 × 1/3 = 1/6 when two of four are overloaded. This can smooth hotspots with modest state.
For affinity, IP hash maps a client address to a replica; shared or changing addresses can hurt distribution. Consistent hashing maps a key around a ring with virtual positions per backend. Removing one backend then remaps mainly its keys; adding one moves keys mainly to the newcomer. See partitioning for the same trade-off with stored data. Affinity preserves warm caches but can produce uneven load.
Healthy enough to receive traffic¶
An active health check probes at an interval; a passive check uses real request outcomes, such as connection failures. Checking every 5 seconds and requiring three consecutive failures detects a continuously failing instance after roughly 10–15 seconds, plus any time the last probe waits before timing out. Require several successes before restoring it. Thresholds reduce flapping, where an instance repeatedly enters and leaves the pool.
Liveness asks whether a process should restart. Readiness asks whether it should receive traffic now. A process can be alive while loading weights. A check returning 200 from / regardless of application health proves little. Probe enough of the route to reflect its ability to serve, without making the probe fragile.
After readiness, slow start gradually increases traffic so caches and connections warm. During removal, connection draining stops new assignments and lets in-flight work finish, up to a deadline. Passive checks may eject an outlier with far more errors than peers. Limit ejection: removing many replicas can send a thundering herd to survivors. Retries amplify that surge; retry suitable failures with a budget and deadline.
State and long connections¶
Sticky sessions keep a client on one backend, often by cookie or hash. They can hide session data held only in one process. When that process fails, users lose the state; uneven traffic also limits scale-out. Prefer stateless handlers with needed state in a shared store. Use affinity for a measured benefit, such as cache locality, with a plan for backend failure.
WebSockets and streams are long-lived. A balancer usually chooses a backend when the connection starts; adding replicas does not move existing connections. Count open connections and their work, not just new requests. Drain with a deadline or client reconnect plan.
Global routing and LB redundancy¶
A single LB is a single point of failure. Run redundant balancers with failover capacity. In active-active, both receive traffic; in active-passive, a standby takes over. DNS or anycast can direct users toward available LB endpoints, with different convergence behavior. Size survivors for traffic and TLS work.
Global load balancing chooses a region before a regional LB chooses a replica. Geo routing can reduce distance, but a nearby region may be overloaded or down. Region choice also affects data location and writes. For recovery targets, see failover and disaster recovery.
For AI engineers¶
For AI engineers
Your inference endpoint may receive a 20-token prompt followed by a short answer, then a 20,000-token prompt followed by a long generation. Round robin treats these as equal turns even though their service time and memory needs differ. Least outstanding work can be better if the router can estimate cost; active request count is a useful but imperfect fallback. Keep batching in mind: a scheduler that groups requests on each GPU can improve throughput, while the router still must avoid sending all expensive work to one replica.
Prefix or KV caches make affinity tempting because repeat work on a warm GPU may be cheaper. The trade-off is cache reuse versus even load. Measure queue time and cache benefit before pinning keys. A serving process that has started but is still loading weights is alive and unready: its readiness check should keep traffic away until it can answer a real request.
Common mistakes¶
- Using round robin when request costs differ sharply; track in-flight work or queue pressure.
- Using sticky sessions to hide process-local state; store durable session data where another replica can read it.
- Checking a
/page that always returns 200; test the route's actual readiness. - Removing a backend on deploy without draining its active connections or streams.
- Running one LB instance or sizing the pair so neither can carry failover traffic.
- Retrying every error through the LB; non-retryable errors and retry storms waste capacity.
Check yourself¶
Two replicas get ten requests each, but one receives all the long generations. Why can round robin still leave a queue?
Round robin equalizes request counts, not service time. Route using in-flight work or a useful load estimate, while watching queue time and GPU saturation.
A new model process returns 200 from / while weights are still loading. Which signal should keep it out of the pool?
Readiness should stay false until it can serve the model route. Liveness may be true because the process is running.
One of four backends fails, and the LB immediately retries every failed request twice. What new risk appears?
The three survivors receive both the failed backend's original share and retry traffic. A bounded retry budget, health-based removal, and capacity headroom reduce the overload risk.
You add two replicas but WebSocket clients remain concentrated on the old ones. Why?
The backend was selected when each connection began. New replicas receive new connections but do not inherit existing ones; use a reconnect or drain plan if redistribution is needed.
Lab¶
Build a deterministic in-process router in code/load-balancing/. Implement round robin, weighted round robin, least connections, two-choice routing, and consistent hashing. Make every picker skip unhealthy backends and report an empty healthy pool. Add a health checker with consecutive-failure and recovery thresholds. Use the simulation test to compare routing under unequal request durations. Run: cd code/load-balancing && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Interactive: Designed to Scale – load balancing
- Your handbook: Software Engineering Handbook, ch. 5 "Load Balancer & API Gateway"
- Reference: Google SRE books
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.


