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.

Time O(1) per pickSpace O(n) serversCode C#
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

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.