Load balancer algorithms: round robin, least connections
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite now runs on three servers, but customers still type one address. Something must choose a server for every request, and a poor choice leaves one server drowning while the others wait.
Your turn: who picks the server?
ShopLite runs app-1, app-2 and app-3. During a sale most requests are quick product views, and every third one is a 3-second report export. Take two minutes and sketch your own design before you read on, then compare it with the sections below.
- Who decides which server gets each request, and what breaks if everything goes to
app-1? - Write a one-sentence rule. What does it need to know about each server?
- What changes if
app-3is a small machine with half the CPU, or if the picking code runs on many threads at once?
What a load balancer does: L4 vs L7
Load balancer is a server or service in front of several servers. It gives clients one address, picks a healthy server for each request, forwards it and sends the response back, so servers can change without clients noticing.
ShopLite's balancer is a short Nginx block: a pool of three servers and the rule for choosing one. Example 1 then shows what the balancer can read in a request.
upstream shoplite_api { least_conn; # default is round robin; ip_hash is another option server 10.0.1.11:8080 weight=2; # bigger machine, twice the share server 10.0.1.12:8080; server 10.0.1.13:8080;}server { listen 80; location /api/ { proxy_pass http://shoplite_api; }}Example 1 · What an L4 and an L7 balancer can see
import java.util.List;import java.util.Map;
public class L4VsL7Demo { record Packet(String clientIp, int port, String httpLine) { }
// L4: sees only addresses and ports, so it can only pick from one pool static String l4Route(Packet p, List<String> pool, int counter) { return pool.get(counter % pool.size()); }
// L7: reads the HTTP request, so it can route by path static String l7Route(Packet p, Map<String, List<String>> poolsByPrefix, int counter) { String path = p.httpLine().split(" ")[1]; for (Map.Entry<String, List<String>> e : poolsByPrefix.entrySet()) { if (path.startsWith(e.getKey())) { List<String> pool = e.getValue(); return pool.get(counter % pool.size()); } } return "404 (no pool)"; }
public static void main(String[] args) { List<Packet> requests = List.of( new Packet("49.36.10.7", 443, "GET /api/v1/products/1 HTTP/1.1"), new Packet("49.36.10.7", 443, "POST /api/v1/orders HTTP/1.1"), new Packet("103.21.5.9", 443, "GET /admin/reports HTTP/1.1"), new Packet("103.21.5.9", 443, "GET /api/v1/categories HTTP/1.1"));
List<String> allServers = List.of("app-1", "app-2", "app-3"); Map<String, List<String>> byPath = new java.util.LinkedHashMap<>(); byPath.put("/api/", List.of("api-1", "api-2")); byPath.put("/admin/", List.of("admin-1"));
int i = 0; for (Packet p : requests) { System.out.printf("%-34s L4 -> %-6s L7 -> %s%n", p.httpLine().replace(" HTTP/1.1", ""), l4Route(p, allServers, i), l7Route(p, byPath, i)); i++; } }}GET /api/v1/products/1 L4 -> app-1 L7 -> api-1 POST /api/v1/orders L4 -> app-2 L7 -> api-2 GET /admin/reports L4 -> app-3 L7 -> admin-1 GET /api/v1/categories L4 -> app-1 L7 -> api-2
What this code does
- The L4 router sees only addresses and ports, so it rotates all requests over one pool of servers.
- The L7 router reads the path from the HTTP request line and sends
/api/traffic to the API pool and/admin/traffic to the admin server.
Popular choices are Nginx, HAProxy and cloud load balancers.
An L4 (transport layer) balancer looks only at IP addresses and ports and forwards whole TCP connections; it is very fast but cannot see URLs. An L7 (application layer) balancer reads the HTTP request, so it can route by path or header (/api/ to API servers, /admin/ to admin servers), add headers and end TLS. Most web apps use L7.
Round robin with AtomicInteger
Round robin is a balancing rule that sends requests to the servers in turn: 1, 2, 3, 1, 2, 3. It needs no knowledge of the servers and spreads requests evenly when they cost about the same.
A real balancer handles many requests at once, so the counter that picks the next server must be thread-safe. This one uses AtomicInteger.
Example 2 · Thread-safe round robin with AtomicInteger
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
class RoundRobinBalancer { private final List<String> servers; private final AtomicInteger next = new AtomicInteger();
RoundRobinBalancer(List<String> servers) { this.servers = List.copyOf(servers); }
String pick() { int i = next.getAndIncrement(); // atomic: no two threads get the same number return servers.get(Math.floorMod(i, servers.size())); // floorMod stays correct after int overflow }}
public class RoundRobinDemo { public static void main(String[] args) throws InterruptedException { RoundRobinBalancer lb = new RoundRobinBalancer(List.of("app-1", "app-2", "app-3"));
System.out.print("First 7: "); for (int i = 0; i < 7; i++) { System.out.print(lb.pick() + " "); } System.out.println();
RoundRobinBalancer shared = new RoundRobinBalancer(List.of("app-1", "app-2", "app-3")); Map<String, AtomicInteger> counts = new ConcurrentHashMap<>(); List<Thread> threads = new ArrayList<>(); for (int t = 0; t < 10; t++) { // 10 threads x 100 requests at the same time Thread th = new Thread(() -> { for (int r = 0; r < 100; r++) { counts.computeIfAbsent(shared.pick(), k -> new AtomicInteger()).incrementAndGet(); } }); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); } Map<String, Integer> result = new TreeMap<>(); counts.forEach((k, v) -> result.put(k, v.get())); System.out.println("1000 requests from 10 threads: " + result); }}First 7: app-1 app-2 app-3 app-1 app-2 app-3 app-1
1000 requests from 10 threads: {app-1=334, app-2=333, app-3=333}What this code does
getAndIncrementhands out 0, 1, 2, ... exactly once each, so the first 7 picks cycle through the three servers.- With 10 threads making 1,000 picks at the same time, the counts are exactly 334, 333 and 333: no number was lost or repeated.
AtomicInteger.getAndIncrement() gives every caller a different number even when threads call it at the same moment, without a lock.
Use Math.floorMod(i, n) for the index, so the result stays valid after the counter passes Integer.MAX_VALUE and becomes negative.
Find the bug
Spot the bug in the balancer
Each snippet has one wrong line. Tap it, then read the fix.
next is a plain int field. Two threads call pick() together and get the same server.
int next++ looks fine in a test with one thread. It fails only under load, as repeated picks and uneven counts, so look for it in code reviews.Weighted round robin
Weighted round robin is round robin where each server has a weight that matches its size. An 8-CPU server with weight 5 gets five requests for every one that a 2-CPU server with weight 1 gets.
The smooth version keeps one running counter per server. Example 3 runs it with weights 5, 1 and 1.
Example 3 · Smooth weighted round robin with weights 5, 1, 1
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
class WeightedServer { final String name; final int weight; int current = 0;
WeightedServer(String name, int weight) { this.name = name; this.weight = weight; }}
// "Smooth" weighted round robin (the method nginx uses): heavy servers get more turns,// but their turns are spread out instead of coming in one blockclass WeightedRoundRobin { private final List<WeightedServer> servers; private final int totalWeight;
WeightedRoundRobin(List<WeightedServer> servers) { this.servers = servers; this.totalWeight = servers.stream().mapToInt(s -> s.weight).sum(); }
synchronized String pick() { WeightedServer best = null; for (WeightedServer s : servers) { s.current += s.weight; // everyone moves forward by its weight if (best == null || s.current > best.current) { best = s; } } best.current -= totalWeight; return best.name; }}
public class WeightedRoundRobinDemo { public static void main(String[] args) { WeightedRoundRobin lb = new WeightedRoundRobin(List.of( new WeightedServer("big-8cpu", 5), new WeightedServer("small-a", 1), new WeightedServer("small-b", 1)));
StringBuilder order = new StringBuilder(); for (int i = 0; i < 7; i++) { order.append(lb.pick()).append(' '); } System.out.println("One cycle of 7: " + order.toString().trim());
Map<String, Integer> counts = new LinkedHashMap<>(); for (int i = 0; i < 700; i++) { counts.merge(lb.pick(), 1, Integer::sum); } System.out.println("700 requests: " + counts); }}One cycle of 7: big-8cpu big-8cpu small-a big-8cpu small-b big-8cpu big-8cpu
700 requests: {big-8cpu=500, small-a=100, small-b=100}What this code does
- In each cycle of 7 the big server gets 5 turns, spread out (
big big small-a big small-b big big) instead of 5 in a row. - Over 700 requests the split is exactly 500, 100 and 100, matching the weights.
The simplest version repeats each server in a list as many times as its weight, but then the big server gets five requests in a row. Smooth weighted round robin, the method Nginx uses, spreads them out.
On each pick every server's counter grows by its weight, the largest counter wins, and the winner's counter drops by the total weight.
Order of execution
One smooth weighted pick
Put the steps of one pick in the right order.
Least connections
Least connections is a balancing rule that sends each request to the server with the fewest requests currently open. The balancer counts a request when it forwards it and uncounts it when the response finishes.
Example 4 sends short requests and slow 3-second report exports through round robin and through least connections.
Example 4 · Round robin vs least connections with slow reports
import java.util.ArrayList;import java.util.List;import java.util.PriorityQueue;
public class LeastConnectionsDemo { record Finish(long at, int server) { }
// Simulates requests arriving every 10 ms; returns the highest number of open requests any server had static int simulate(String strategy, long[] durations, int servers) { int[] active = new int[servers]; int[] peak = new int[servers]; PriorityQueue<Finish> finishing = new PriorityQueue<>((a, b) -> Long.compare(a.at(), b.at())); int rr = 0; for (int i = 0; i < durations.length; i++) { long now = i * 10L; while (!finishing.isEmpty() && finishing.peek().at() <= now) { active[finishing.poll().server()]--; // requests that ended free their server } int chosen; if (strategy.equals("round robin")) { chosen = rr++ % servers; } else { // least connections; ties -> lowest index chosen = 0; for (int s = 1; s < servers; s++) { if (active[s] < active[chosen]) { chosen = s; } } } active[chosen]++; peak[chosen] = Math.max(peak[chosen], active[chosen]); finishing.add(new Finish(now + durations[i], chosen)); } List<Integer> peaks = new ArrayList<>(); for (int p : peak) { peaks.add(p); } System.out.printf("%-17s peak open requests per server %s%n", strategy, peaks); return peaks.stream().mapToInt(Integer::intValue).max().orElse(0); }
public static void main(String[] args) { long[] durations = new long[60]; for (int i = 0; i < durations.length; i++) { durations[i] = i % 3 == 0 ? 3_000 : 20; } simulate("round robin", durations, 3); simulate("least connections", durations, 3); }}round robin peak open requests per server [20, 1, 1] least connections peak open requests per server [8, 7, 7]
What this code does
- Every third request is a 3-second export. Round robin sends all of them to the first server, which ends up with 20 open requests while the others never have more than 1.
- Least connections sends new requests to the server with the fewest open ones, so the slow exports spread out and no server goes above 8.
Least connections beats round robin when request times differ a lot. If every third request is a 3-second report export, round robin keeps handing them to the same server in turn, and that server piles up open requests while the others sit idle.
Least connections notices the busy server and sends new work elsewhere. With similar, short requests, both give about the same result.
Predict the output
Predict the least-connections pick
Read the code, then pick what it prints.
Round 1 of 2
Ties: the loop uses < and not <=.
IP hash and random choice
IP hash is a balancing rule that picks the server from a hash of the client's IP address, so the same client always reaches the same server as long as the server list does not change.
The same IP must map to the same server every time, while random choice needs no memory at all. Example 5 shows both.
Example 5 · IP hash keeps a client on one server; random spreads load
import java.util.List;import java.util.Map;import java.util.Random;import java.util.TreeMap;
public class IpHashAndRandomDemo { static final List<String> SERVERS = List.of("app-1", "app-2", "app-3");
static String ipHash(String clientIp) { return SERVERS.get(Math.floorMod(clientIp.hashCode(), SERVERS.size())); // same IP, same server }
public static void main(String[] args) { for (String ip : new String[] {"49.36.10.7", "103.21.5.9", "49.36.10.7", "157.48.2.200"}) { System.out.println("IP hash " + ip + " -> " + ipHash(ip)); }
Random random = new Random(42); // fixed seed so the run is repeatable Map<String, Integer> counts = new TreeMap<>(); for (int i = 0; i < 3_000; i++) { counts.merge(SERVERS.get(random.nextInt(SERVERS.size())), 1, Integer::sum); } System.out.println("Random choice, 3000 requests: " + counts); }}IP hash 49.36.10.7 -> app-1
IP hash 103.21.5.9 -> app-2
IP hash 49.36.10.7 -> app-1
IP hash 157.48.2.200 -> app-1
Random choice, 3000 requests: {app-1=984, app-2=1025, app-3=991}What this code does
- The same IP
49.36.10.7maps toapp-1both times, because the hash of the same string is always the same. - Random choice with a fixed seed gives 984, 1,025 and 991 out of 3,000: close to even without any shared counter.
IP hash is a simple form of stickiness (the next lesson explains its costs), and adding a server re-maps most clients.
Random picks any server and spreads load evenly with no shared counter, which suits balancers that run as many copies. A refinement, power of two choices, picks two random servers and uses the less busy one, which keeps loads very close.
Next step
Check your understanding
11 quick questions