A load balancing algorithm is the rule a balancer uses to choose which server gets the next request. Static rules such as round robin, weighted round robin, random and hashing ignore the live state of the servers. Dynamic rules such as least connections, least response time and power of two choices read live signals. The right choice depends on how uneven your requests and servers are.
We continue with BusTrack, the Hyderabad bus tracking app from Load Balancing: Introduction. Its three servers are named hyd-api-1 to hyd-api-3. Six runnable programs in Java, with Python and C++ versions, compare the algorithms on the same simulated traffic: turn-taking and weights, random choices, queue lengths, a slow server, hashing for stickiness and a cold server joining the pool.
Key takeaways
Weights 5:3:2 given naively send 5 requests in a row to one server. Smooth weighted round robin keeps the same shares but the longest run is 2.
Random choice left a gap of 173 requests between the busiest and the idlest of 10 servers. Picking 2 at random and taking the lighter one cut it to 8.
With identical servers and uneven requests, least connections gave p99 18.5 ms against 37.1 ms for round robin and 78.3 ms for random.
When one server became 4 times slower, round robin kept sending it 33% and p99 reached 10,890 ms. Least connections cut that to 36 ms.
Choosing "fastest average" backfired: it herded traffic and starved a recovered server, with p99 18,477 ms.
Adding a fourth server moved 74.7% of sessions with modulo hashing, but only 25.0% with rendezvous hashing.
A new, cold server got 10% of requests under least connections and p99 46.7 ms; a slow start ramp kept p99 at 26.4 ms.
1. What Is a Load Balancing Algorithm?
The balancer already knows who is in the pool and who is healthy, as explained in Load Balancing: Introduction. The algorithm only answers one question for each request: of the healthy servers, which one? A bad answer shows up as one hot server, longer queues and a worse tail latency, even when the pool as a whole has plenty of spare capacity.
Static rules ignore load; dynamic rules read it.
What an algorithm can know depends on where it runs. DNS can only rotate or weight answers, a layer 4 balancer sees connections, and a layer 7 balancer can measure response times per request.
The layer you balance at limits which signals you can use.
2. Round Robin and Weighted Round Robin
Round robin sends request 1 to server 1, request 2 to server 2, and so on in a circle. It needs no state beyond a counter and divides requests perfectly equally. It is the right default when servers are identical and requests cost about the same.
If servers differ, give each a weight proportional to its capacity. Suppose hyd-api-1 is a large machine with weight 5, hyd-api-2 has weight 3 and hyd-api-3 has weight 2. The naive way repeats each server as many times as its weight: five requests to api-1, then three to api-2, then two to api-3.
Same shares, but the naive order sends bursts to one server.
The smooth version, used by NGINX, keeps a running score per server. On each pick add every weight to its score, choose the highest, then subtract the total weight from the winner.
Smooth weighted round robin: add the weights, pick the highest, subtract the total.
Output
Weights hyd-api-1:hyd-api-2:hyd-api-3 = 5:3:2, first 20 picks
round robin : 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2
naive weighted : 1 1 1 1 1 2 2 2 3 3 1 1 1 1 1 2 2 2 3 3
smooth weighted : 1 2 3 1 1 2 1 3 2 1 1 2 3 1 1 2 1 3 2 1
over 1000 picks api-1 api-2 api-3 longest run
round robin 334 333 333 1
naive weighted 500 300 200 5
smooth weighted 500 300 200 2
Over 1,000 picks all three weighted policies delivered the right shares, 500, 300 and 200.
The longest run on a single server was 5 for the naive order and 2 for the smooth one. A run of 5 at the peak means api-1 sees a burst and everyone else idles.
Plain round robin ignores weights: it gave 334, 333 and 333, which would overload the weight-2 server.
3. Random and Power of Two Choices
Pure random needs no counter, which makes it handy when many balancers run in parallel, but it is lumpy by nature. Power of two choices (P2C) improves on it with one small addition: pick two servers at random, compare their load and send the request to the lighter one.
Power of two choices: two random candidates, take the lighter one.
The second program sends 50,000 requests to 10 servers and tracks the worst gap between the busiest and idlest server at any moment. It also tries a stale view, where the balancer refreshes loads only every 500 requests, as happens when several balancers share information with a delay.
Output
50000 requests over 10 servers, ideal share 5000 each
'stale' means the balancer sees loads refreshed only every 500 requests
policy busiest idlest final gap worst gap at any moment
round robin 5000 5000 0 1
random 5104 4937 167 173
two random choices 5001 4998 3 8
two choices, stale 5021 4977 44 92
least loaded 5000 5000 0 1
least loaded, stale 5000 5000 0 500
Random ended with a spread of 167 requests, and a worst gap of 173. Two random choices cut that to 3 and 8, with no global state at all.
Always picking the least loaded server is perfect when the data is fresh (gap 1) but dangerous when it is stale. With a refresh every 500 requests, the "idlest" server received all 500 requests and the gap reached 500. This is the herd effect.
Two choices barely suffers from stale data (92 against 500), because not everyone picks the same server.
Stale information makes every request chase the same server.
4. Least Connections
When requests vary a lot in cost, turn-taking cannot keep up. A fast request leaves its server free, a slow one keeps it busy. Least connections counts the open requests on each server and picks the smallest, so slow requests naturally steer new work elsewhere.
The server with the fewest open requests takes the next one.
The third program uses three identical servers handling one request at a time, with 1 ms, 3 ms and 9 ms requests in a 55/35/10 mix at about 1,020 requests per second.
Output
40000 BusTrack requests, 3 identical servers, about 1020 requests per second
Each server handles one request at a time. Mix: 55% 1 ms, 35% 3 ms, 10% 9 ms.
policy p50ms p95ms p99ms maxms work on busiest server
round robin 6.3 24.9 37.1 67.0 33%
random 9.5 45.7 78.3 127.9 34%
least connections 3.0 12.1 18.5 38.1 36%
Round robin has p99 37.1 ms and random 78.3 ms. Least connections brought it to 18.5 ms, half the best static result, using the same hardware.
The share of work was almost the same everywhere (33%, 34%, 36% on the busiest server), so the average is not the story; the tail is. Queues form behind unlucky 9 ms requests, and least connections avoids joining them.
Weighted least connections divides the open count by the server weight, which handles unequal servers.
5. When a Server Gets Slow
This is the case that separates algorithms. At 20 s into a 60-second run, hyd-api-3 becomes 4 times slower (a bad disk, a noisy neighbour, a garbage collection storm). It is still passing health checks, so no one ejects it. The fourth program compares five policies; the fault lasts until 40 s.
One server slows down; the policies react very differently.
Output
42000 requests, about 700 per second, 60 s. hyd-api-3 runs 4 times slower from 20 s to 40 s.
policy share to api-3 p99 in fault share to api-3 p99 whole run
during fault window ms in 40-50 s ms
round robin 33% 10890.0 33% 10528.9
least connections 10% 36.0 18% 16.9
fastest average 12% 18477.4 0% 18186.6
fastest avg + 2% probe 10% 2007.0 34% 1340.2
ewma x (open + 1) 4% 24.9 34% 17.4
Round robin kept sending api-3 a third of the traffic and p99 in the fault window reached 10,890 ms.
Least connections reduced api-3's share to 10% on its own, because its open requests piled up, and p99 was 36.0 ms.
Fastest average (always choose the lowest measured latency) sounds clever but the numbers are the worst: 18,477 ms p99. It herds onto whichever server looks fastest and it never sends api-3 anything after the fault ends (0% in 40-50 s), so the balancer never learns that the server recovered.
Adding a 2% probe fixed the recovery (34% by 40-50 s) but the herd still hurt during the fault, with p99 2,007 ms.
EWMA times (open + 1) was best on both counts. It keeps an exponentially weighted moving average of response time and multiplies it by the open requests plus one, so a slow server is expensive for two reasons. api-3 got only 4% in the fault and 34% once it recovered, and the whole-run p99 was 17.4 ms.
The EWMA update is cheap, in integers: ewma = (3 * old + new) / 4. If a server receives no traffic, let the value decay slowly toward a baseline so that it gets another chance.
Cost = recent response time times open requests; idle servers decay toward the baseline.
6. Hashing for Stickiness
Sometimes a given key (user, session, cache key) must reach the same server: a warm local cache or a WebSocket connection, for example. Hashing maps the key to a server without storing a table. The question is what happens when the pool changes. The fifth program hashes 20,000 session keys and counts how many keys move when a fourth server is added or one of four is removed.
Output
20000 session keys. Ideal: adding a 4th server moves 25.0%, removing one of 4 moves 25.0%.
method add 4th remove api-2 busiest / idlest share of 4 servers
modulo (hash % servers) 74.7% 75.3% 25.5% / 24.5%
ring, 1 point per server 4.0% 0.8% 67.5% / 0.8%
ring, 100 points per server 27.4% 24.4% 27.4% / 23.2%
rendezvous (highest score) 25.0% 24.9% 25.0% / 24.9%
Modulo (
hash % servers) is even but moved 74.7% of the keys when the pool grew from 3 to 4. Almost every user lands on a cold server. The ideal is 25%.A hash ring with one point per server moved few keys, 4.0%, but one server owned 67.5% of the traffic. Rings need many points, and with 100 points per server the balance is 27.4% against 23.2%, with 27.4% of keys moved.
Rendezvous hashing (every server scores each key; the highest wins) reached 25.0% moved on adding and 24.9% on removing, with a perfectly even spread and no ring to maintain. Its cost is O(servers) per lookup, which is fine for pools of tens.
A ring maps keys clockwise to the next server point.
Ring ideas are explained at length in Consistent Hashing. Remember the cost of any hashing scheme: a hot key still goes to one server, and a server that crashes sends its keys to the next owners all at once.
7. Slow Start for New Servers
A server that has just joined has cold caches, an unwarmed JIT and empty connection pools. Give it a full share at once and it is slow, and the queues behind it grow. Slow start ramps its weight from a small value to full over a window, for example from 10% to 100% over 20 seconds.
A new server gets a full share at once or ramps up gradually.
In the last program a new hyd-api-3 starts 5 times slower and returns to normal speed after 20 seconds.
Output
hyd-api-3 joins at 0 s with cold caches. Fair share would be 33%.
policy share to api-3 p99 first 2 s p99 from 2 s to 20 s
in first 2 s ms ms
round robin 33% 3627.4 7433.5
least connections 10% 46.7 24.3
least connections + slow start 0% 26.4 19.8
Round robin gave it 33% of traffic from the first second and p99 was 3,627.4 ms, then 7,433.5 ms in the following 18 s as the queue built up.
Least connections protected the pool on its own: 10% share, p99 46.7 ms.
Adding slow start was better again. The new server received 0% in the first 2 s, p99 was 26.4 ms and later 19.8 ms. Slow start matters most for algorithms that ignore load, and for deployments that restart servers one by one.
8. Choosing an Algorithm
Use these questions in order.
A short decision path from requirements to algorithm.
| Situation | Good choice | Why |
|---|---|---|
| Identical servers, similar requests | Round robin | Simple, perfectly even |
| Different server sizes | Smooth weighted round robin | Right shares without bursts |
| Many balancers, no shared state | Two random choices | Almost as good as global least-loaded |
| Request cost varies a lot | Least connections or EWMA | Avoids queues behind slow requests |
| A server may get slow | EWMA x (open + 1) | Reacts fast and recovers |
| Same key to same server | Rendezvous or ring | Few keys move on a change |
| Servers join often | Add slow start | Cold caches get time to warm |
9. Common Mistakes
Using round robin with servers of different sizes and no weights.
Ignoring the variance of request cost; the average looks fine while the tail is awful.
Choosing the globally "least loaded" server on stale numbers, which causes herding.
Picking the fastest average response time without exploring, so a recovered server is never used again.
Using
hash % serversfor anything with state, then scaling the pool.A hash ring with one or a few points per server.
Sending full traffic to a freshly started server.
10. Best Practices
Start with round robin or least connections and measure p99 per backend before getting clever.
Add health checks and passive ejection on top of any algorithm, since a slow server still passes health checks.
Prefer two random choices when load data is delayed or when several balancers run side by side.
Use rendezvous hashing or a ring with 100 or more points for stickiness.
Enable slow start for new instances, and cap the share a single server can take.
Keep a small amount of probe traffic to any server that looks bad, so you notice when it recovers.
11. Practice Problems
In the first program, change the weights to 4:4:2. What is the longest run now, and what order does the smooth algorithm produce?
In the second program, change the refresh interval to 50 requests. How does the worst gap of "least loaded, stale" change?
In the fourth program, make the fault 8 times slower. Which policies degrade most?
In the fifth program, try 200 points per ring. What happens to the moved keys and the spread?
12. Interview Questions
Round robin vs least connections? Round robin is stateless and equal in count; least connections adapts to unequal request cost and slow servers at the price of tracking open requests.
Why does smooth weighted round robin exist? To give the same shares as naive weights without sending bursts of consecutive requests to one server.
What is the power of two choices? Pick two random servers and take the less loaded; it gives nearly the balance of global least-loaded with tiny state and little herding.
What is the herd effect? Many requests all chase the server that looked idlest in stale data, overloading it.
Why is
hash % Nbad when the pool grows? Nearly all keys change server, which empties caches and breaks sessions; ring and rendezvous hashing move only about 1/N of the keys.What is slow start? Gradually raising the traffic share of a newly added server so it can warm up.
Summary
Static rules are simple and cheap; dynamic rules protect the tail when requests or servers are uneven.
Smooth weighted round robin removes bursts; two random choices removes most of random's lumpiness.
Least connections and EWMA times open requests keep latency low when a server slows down.
Rendezvous hashing and rings keep users on the same server with the fewest moves when the pool changes.
Slow start and a little probing keep new and recovered servers safe.
Conclusion
There is no best algorithm, only one that fits your servers and requests. Start simple, measure the 99th percentile for each backend, and change the rule when the data says that a slow server or an uneven request is hurting you. The next lessons look at balancing before a request even reaches your data centre, with DNS and anycast.
Previous topic: Load Balancing: Introduction.