Start With One Server
One server is enough for longer than most people expect, and making it bigger is the cheapest fix there is. A load balancer earns its place at two moments: when one machine can no longer carry the peak, and when restarting that machine means an outage.
After that, the interesting problems aren't about spreading requests. They're about what happens when the servers stop being equal: one is busy with slow work, one is broken but still answering, one passes every check and returns errors anyway. The table above lists those signals in order. This article covers the layers and the algorithms, then the answer to each situation and a way to check it.
- You picked round-robin and one backend with a slow GC took the fleet down via timeouts
- You can't explain when to use Azure Front Door vs Application Gateway vs Load Balancer
- Your sticky sessions broke a rolling deploy
- You don't have outlier ejection and a half-dead instance is still in rotation
This is the load-balancer mental model — L4 vs L7, the algorithms that matter, health checks that work, and the Azure service that fits each tier.
Algorithms, Layers and Health Checks
Two layers, very different jobs:
- L4 (TCP/UDP) — Azure Load Balancer, AWS NLB. Routes packets by 5-tuple (src ip, src port, dst ip, dst port, protocol). Less processing than L7 and no app awareness. Best for raw TCP/UDP and traffic that doesn't need HTTP routing.
- L7 (HTTP/HTTPS) — Azure Front Door (global), Application Gateway (regional), nginx, Envoy. Understands HTTP — can route on host, path, headers; terminate TLS; rewrite; cache; WAF.
flowchart LR
USR["Users (global)"] --> FD["Azure Front Door<br/>L7 + WAF + CDN<br/>(global anycast)"]
FD -->|host: api.x.com| AG["App Gateway<br/>L7 (regional)"]
FD -->|host: cdn.x.com| BLOB["Storage Static<br/>(direct origin)"]
AG --> POOL["Backend Pool"]
POOL --> B1["Backend 1<br/>(healthy)"]
POOL --> B2["Backend 2<br/>(healthy)"]
POOL -.->|ejected| B3["Backend 3<br/>(5xx > 50%)"]
style FD fill:#0078D4,color:#fff,stroke:#005a9e
style AG fill:#0078D4,color:#fff,stroke:#005a9e
style B3 fill:#dc2626,color:#fff,stroke:#b91c1c
Configuring a Balancer That Helps
Each step answers one situation. The first three follow the table above; the last three cover what the balancer can't do for you.
Step 1: When requests differ in cost, choose the algorithm by what varies
Round-robin is fair only if every request costs the same and every server is equally fast. Most real traffic fails the first condition. Choose by what actually varies in yours.
Round-robin — simple, fair when backends are identical and fast
Weighted round-robin — different SKUs (canary at 5%, prod at 95%)
Least connections — long-lived connections (websockets, gRPC)
Least response time / EWMA — heterogeneous backends with variable latency
Power-of-two-choices — pick 2 random backends, send to the less loaded one
(nearly as good as a full scan, no global state)
Consistent hash — sticky-by-key (cache-friendly, session affinity)YARP uses P2C by default, and Envoy's least-request policy uses it when all weights are equal. Azure Front Door is different: it picks an origin by priority, latency and weight. Move to P2C or least-request when your backends have variable latency. In most proxies it's a small config change.
Check it: Slow one backend down on purpose in a test environment, for example with an added delay. Under round-robin its queue grows and overall latency climbs. Under least-request or P2C it should simply receive fewer requests.
Step 2: When a broken server still gets traffic, make the check prove readiness
A check that only confirms the process is up can't see a server that has lost its database connection. Readiness has to test what the server needs in order to do real work, and liveness should stay cheap.
// /healthz that actually verifies dependencies
app.MapHealthChecks("/healthz", new HealthCheckOptions
{
ResultStatusCodes =
{
[HealthStatus.Healthy] = 200,
[HealthStatus.Degraded] = 200, // serve traffic, but warn
[HealthStatus.Unhealthy] = 503 // remove from rotation
}
});
builder.Services.AddHealthChecks()
.AddSqlServer(connStr, name: "sql", failureStatus: HealthStatus.Unhealthy)
.AddRedis(redisConn, name: "redis", failureStatus: HealthStatus.Degraded)
.AddCheck("self", () => HealthCheckResult.Healthy());Health-check rules:
• Set the interval and failure threshold on purpose (Kubernetes defaults: 10s and 3 failures)
• Drain (stop new requests, finish in-flight) before marking down
• Liveness → "is the process responsive?" (cheap)
• Readiness → "should it get traffic?" (checks deps; may flap)
• Don't fail readiness on transient downstream blips — use a sliding windowCheck it: Break the database connection for one instance only. It should leave rotation after the failure threshold and come back once it recovers. Then take the shared database down for all of them. If every instance fails readiness at once, the balancer has nowhere to send traffic, so decide in advance what you want to happen then.
Step 3: When a server passes its checks but returns errors, eject it
A health check asks the server how it feels. Outlier ejection watches what it actually returns to real requests, and removes one that keeps failing.
# Envoy cluster config: eject a backend after consecutive 5xx responses
outlier_detection:
consecutive_5xx: 5
interval: 10s
base_ejection_time: 30s # multiplied by the number of ejections
max_ejection_percent: 50 # never eject more than half the pool (default 10)Check it: Make one instance return 500s. With the settings below it should be ejected after five in a row, for thirty seconds, then tried again. Check the cap as well: with max_ejection_percent at 50, a fault that hits every instance can remove at most half of them.
Step 4: When a user has to stay on one server, use affinity sparingly
Affinity ties a user to one instance, which undoes most of what the balancer is for. It's a workaround for state kept in server memory, and the better fix is to move that state out.
Stateless services don't need stickiness — every request is independent.
If you DO need session affinity (legacy in-memory sessions, websocket reconnects):
• Cookie-based affinity (App Gateway v2 sets ApplicationGatewayAffinity)
• Keep affinity short-lived where you can, so deploys move users off old pods
• Have a fallback: when the affine instance disappears, fail over cleanly
Better long-term: externalize session state (Redis) and lose stickiness entirely.Check it: Roll one instance during a test session. A user pinned to it should carry on with another instance, not get an error. If they lose their session, the state is still in memory.
Step 5: When you are on Azure, match the service to the layer
Azure has four services that all sound like load balancers. They differ by layer and by reach: HTTP or raw TCP, one region or many.
Azure Front Door (Standard/Premium)
• Global L7 + CDN + WAF; anycast routing to the nearest PoP
• Use as the public entry for global or multi-region web apps
• Premium: managed WAF rules, Private Link to origin
Application Gateway (v2)
• Regional L7; host and path routing; WAF; mTLS; autoscale
• Use behind Front Door for regional fan-out, or solo for internal apps
Azure Load Balancer (Standard)
• Regional L4; the usual choice for non-HTTP TCP/UDP
• The Basic SKU was retired on 30 September 2025; use Standard
Traffic Manager
• DNS-based global routing (priority/weighted/geographic)
• Clients connect to the endpoint directly, and cached DNS answers delay failoverCheck it: For each public entry point, write down whether it needs HTTP routing and whether it serves more than one region. Those two answers pick the service.
Step 6: When a request still fails, make the caller resilient too
A balancer can only route around a failure it has noticed. In the seconds before it notices, the caller sees errors, so the caller needs a timeout, a small number of retries and a circuit breaker of its own.
// Microsoft.Extensions.Http.Resilience (Polly v8) — retry, circuit breaker, timeout
builder.Services.AddHttpClient("api")
.AddResilienceHandler("std", builder =>
{
builder.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.HandleResult(r => (int)r.StatusCode >= 500)
});
builder.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5, MinimumThroughput = 20,
BreakDuration = TimeSpan.FromSeconds(30)
});
builder.AddTimeout(TimeSpan.FromSeconds(2));
});Check it: Count attempts during an outage. With two retries, a failing dependency should see at most three times its normal request rate, not a storm that keeps growing. If the breaker never opens while failures continue, its threshold is too loose.
How Load Balancing Fails
1. Round-robin with heterogeneous backends. One slow GC pause and round-robin keeps sending requests into the abyss. Use P2C or least-request and the slow node sheds load automatically.
2. Health checks that are too lenient. A liveness probe that just returns 200 from /health never catches a stuck DB connection pool. Verify dependencies in readiness; keep liveness cheap.
3. Health checks that are too strict. Failing readiness on a 50ms Redis blip can eject the whole fleet. Use a sliding window (3-of-5 failures) before marking down.
4. Sticky sessions that survive deploys. Cookie-affine to a pod that just got rolled — the user gets a 502. Short TTLs and graceful drains.
5. No retry budget. Polly retries on every 5xx; downstream dies; retries amplify load 3x; downstream takes longer to recover. Cap retries (2 attempts), require jitter, and pair with a circuit breaker.
6. TLS terminated only at the edge. Plain HTTP from the LB to backends is fine in a private VNet; on the public internet or untrusted network it's not. Use end-to-end TLS or service mesh mTLS.
What I Would Configure
- Global public entry → Azure Front Door. Regional fan-out → Application Gateway. TCP/UDP → Standard Load Balancer.
- Default algorithm: P2C or least-request the moment latency varies. Round-robin is the demo answer.
- Liveness = process responsive. Readiness = dependencies OK. Drain before marking down.
- Enable outlier ejection where your proxy has it. Cap
max_ejection_percentso a flap doesn't empty the pool. - Avoid sticky sessions if you can. Externalize session state instead.
- Pair the LB with client-side retries (capped + jittered) and circuit breakers — the LB alone isn't enough.
- End-to-end TLS over any network you don't fully control.
Try It on Your Own System This Week
Three things you can check on a running system, about an hour in total:
- Look at latency per instance, not just the average. One instance far from the others is the first sign of uneven work or a sick server.
- Read the code of your health endpoint. If it returns 200 without touching anything the server depends on, it can't catch the failure in Step 2.
- Ask what happens to an instance that returns errors but passes its check. If the answer is nothing, Step 3 is your next piece of work.
Balancing LLM Traffic
Round robin assumes that requests cost roughly the same. LLM requests don't. One takes 200 ms and 100 tokens, while the next takes 40 seconds and 50,000 tokens. Spread them evenly by count, and you get one GPU drowning while another sits idle. If you serve models yourself, this is the most important load-balancing problem you'll have.
Balance on real load. Good signals include the number of requests in flight, the waiting queue length in the model server, and the amount of KV cache in use. vLLM exposes these as metrics. GPU utilisation alone won't tell you how much work a replica has queued.
Cache-aware routing
Prefix caching changes the picture further. If a replica has already processed a long system prompt, routing the next request with that prefix to the same replica avoids recomputing it, which saves time and GPU work. A plain load balancer can't do this. Inference-aware routers, such as llm-d and the Kubernetes Gateway API Inference Extension, take the prompt prefix into account when they choose a replica.
There's a tension here: sending everything with the same prefix to one replica can overload it. Good routers balance affinity against load. Larger deployments go further, with prefill and decode on separate replicas, which keeps long prompts from blocking active streams. That complexity is only worth it at multi-node scale, though. Under a handful of GPUs, stick with continuous batching.
Long-lived connections
Streaming responses and WebSockets break some assumptions. A connection may last minutes, so "least connections" works better than round robin, and a deployment has to drain connections gracefully, or you cut off users mid-answer. Set idle timeouts on proxies longer than your slowest stream, and send keep-alive comments. Many streaming bugs turn out to be a proxy buffering the response, or a 60-second timeout at the load balancer. HTTP/2 multiplexing means that one connection can carry many requests, so connection-level balancing can pin all of a client's traffic to one backend. gRPC needs client-side or L7 balancing for this reason.
Health checks need care too. A model server may answer /health while its queue is full, so check readiness on capacity rather than on liveness alone.