AI Hints
Home›System Design Tutorial›Load Balancing
System Design · Lesson 26 of 120

Balancing Algorithms

Who gets the next request.

⏱ 2 min read▶ Video at 29:36🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

A load balancer has to pick a server for every single request. There are a few simple rules it can follow, and each one suits different traffic.

Balancing Algorithms
From the video: Balancing Algorithms
  • A choice for every request
  • A few simple rules
  • Each suits different traffic

Round robin vs least connections

Round robin just takes turns, one, two, three, one, two, three. Least connections picks the server with the fewest requests in progress. Here, server A is stuck with slow requests. Run it. Round robin keeps sending A its share, even though it's busy. Least connections notices, and sends new work to B and C instead.

balance.pypython
from itertools import cycle

servers = ["A", "B", "C"]
active = {"A": 5, "B": 1, "C": 0}  # requests in progress

rr = cycle(servers)
print("round robin:", [next(rr) for _ in range(6)])

picks = []
for _ in range(6):
    s = min(active, key=active.get)
    active[s] += 1
    picks.append(s)
print("least conn: ", picks)
Output
round robin: ['A', 'B', 'C', 'A', 'B', 'C']
least conn:  ['C', 'B', 'C', 'B', 'C', 'B']

Common algorithms

Here are the common choices. Round robin is simple, and works when requests are similar. Weighted round robin sends more to bigger servers. Least connections handles requests of different lengths. And hashing the user's IP sends the same user to the same server, which helps with caching.

AlgorithmGood when
Round robinrequests are similar
Weightedservers differ in size
Least connectionsrequest times vary
IP hashsame user, same server

Summary

Round robin takes turns, least connections avoids busy servers, and hashing keeps a user on one server. Next, two levels a balancer can work at.

Key takeaways
  • Round robin
  • Least connections
  • Hash for stickiness
Next up: L4 vs L7 Balancing — packets or requests