Load balancing: round robin and least connections
How a load balancer picks a server, skips unhealthy ones, and why the choice of algorithm matters for slow requests.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Round robin hands requests out in turn, which is fair only when every request costs the same. Least connections sends each request to the server with the fewest requests in flight, so a server stuck on slow work stops receiving more. Health checks remove dead servers from the pool either way.
Code
class LeastConnections
{
readonly List<Server> _servers;
public Server Pick()
{
var healthy = _servers.Where(s => s.Healthy);
var best = healthy.MinBy(s => s.Active);
best.Active++;
return best;
}
public void Done(Server s) => s.Active--;
}Tips
- Layer 4 balancers route by IP and port and are very fast; layer 7 balancers read HTTP and can route by path or header.
- Sticky sessions pin a user to one server. They work, but they undo the benefit of stateless servers; prefer a shared session store.
- Mention health checks and connection draining: a server being deployed finishes its in-flight requests before leaving the pool.
In the .NET library
YARP (Yet Another Reverse Proxy) is a .NET library for building layer 7 proxies and supports round robin, least requests and power-of-two-choices policies.