Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Systems · Networking

Spread the Load.

A load balancer sits in front of a fleet of identical servers and decides, for each incoming request, which server handles it. The policy it uses matters more than it looks. Round-robin deals requests out in strict rotation — simple, but blind to how busy each server actually is. Least-connections sends each new request to the server with the fewest requests in flight — it notices load. When every request takes the same time these behave alike, but real requests vary wildly in duration, and that’s where they diverge: round-robin can hand a burst of slow requests to one unlucky server while least-connections routes around the busy ones. Send traffic, switch the policy, and watch the load pile up or stay even.

round-robin (blind rotation) vs least-connections (load-aware) · uneven durations expose the gap
round-robin

Assign requests to servers in fixed rotation, ignoring current load.

least-connections

Assign each request to the server with the fewest active requests.

random

Pick a server uniformly at random — surprisingly decent, and stateless.

in-flight

How many requests a server is currently processing — its live load.

lb.js — pick the server for each request
Ready
Four backend servers. Each tick a new request (random duration) arrives and is routed by the current policy, and busy servers finish work. Watch the load balance — or not. Tick to run; switch the policy to compare.
round-robin
policy
0
busiest server
0
imbalance

How it works

The gap between the policies is entirely about information. Round-robin uses none: it advances a counter and hands the next request to the next server, so if request durations are equal, load stays perfectly even — but if a run of long requests happens to land on server 2, round-robin keeps dealing to server 3, 4, 1, 2… and dumps the next long one right back on the already-overloaded server 2. Least-connections uses the one piece of state that matters — each server’s current in-flight count — and always steers the new request to the least-loaded server, so slow requests naturally get routed around. The “imbalance” meter (busiest minus least-busy) makes this visible: it stays lower under least-connections than under round-robin when durations vary. With this lab’s short requests (1 to 5 ticks) the gap is modest: round-robin sits at an imbalance of 2 on about one tick in six, least-connections on fewer than one in a hundred. Longer, more uneven requests widen it, as the worked example below shows. Pure random is the noisiest of the three in this lab (no coordination at all, so it piles up by chance), which is why “power of two random choices” (pick two at random, send to the less-loaded) is a popular, nearly-stateless middle ground.

1

Requests arrive with varying durations

Real traffic is a mix of quick and slow requests. This variance is what separates good load balancing from bad — with equal durations, any policy looks fine.

2

Round-robin rotates blindly

The balancer hands out requests in fixed order, ignoring how loaded each server is. A cluster of slow requests on one server doesn’t change where the next request goes.

3

Least-connections routes to the least busy

The balancer tracks each server’s in-flight count and sends each new request to the least-loaded server, so slow requests get routed around rather than piled on.

✓

Watch the imbalance

The spread between the busiest and least-busy server stays lower under least-connections than under round-robin when durations vary, and the gap widens as requests get longer and more uneven. Least-connections adapts to real, uneven load.

Round-robin
blind, simple
Least-conn
load-aware
Power of 2
random ×2, pick less
Sticky
hash for affinity

The code

# choosing a backend server per policy def pick_server(servers, policy): if policy == "round_robin": s = servers[rr_index % len(servers)]; rr_index += 1 return s # blind rotation if policy == "least_connections": return min(servers, key=lambda s: s.in_flight) # load-aware if policy == "random": return random.choice(servers) if policy == "power_of_two": a, b = random.sample(servers, 2) return a if a.in_flight <= b.in_flight else b # near-optimal, cheap

The picture: the same traffic under two policies

round-robin balancer s0 1 5 9 s1 s2 s3 imbalance 3 least-connections balancer s0 1 s1 5 s2 9 s3 imbalance 1 bar = request in flight number = ticks left
Tick 9 of the worked example below. Both balancers saw the same nine requests, three of them slow. Round-robin’s counter happened to line up with the slow ones, so it stacked all three on s0 while three servers sat idle. Least-connections saw s0 and s1 were busy and sent the third slow request to s2. Nothing about the traffic differs, only what the balancer looked at.

Worked example: a slow request every fourth tick

Four servers, one request per tick, as in the lab. Every fourth request is slow (9 ticks); the rest take 1 tick. The lab draws durations from 1 to 5 at random, and there round-robin can never stack more than 2 requests on one server: each server gets a new request every 4 ticks, and only a 5-tick request is still running when the next one lands. So this pattern stretches the slow ones to 9 ticks. In-flight counts are listed s0 s1 s2 s3, taken after the tick’s new request lands.

TickRequestRR sends toRR in flightLC sends toLC in flight
1slow (9)s01 0 0 0s01 0 0 0
21s11 1 0 0s11 1 0 0
31s21 0 1 0s11 1 0 0
41s31 0 0 1s11 1 0 0
5slow (9)s02 0 0 0s11 1 0 0
61s12 1 0 0s21 1 1 0
71s22 0 1 0s21 1 1 0
81s32 0 0 1s21 1 1 0
9slow (9)s03 0 0 0s21 1 1 0
101s12 1 0 0s01 1 1 0
13slow (9)s03 0 0 0s01 1 1 0

Round-robin’s imbalance climbs to 3 by tick 9 and stays at 2 or 3 from then on, because the slow requests repeat every 4 ticks and there are exactly 4 servers. The counter is in lock-step with the traffic. Least-connections never puts a second request on a busy server here: its imbalance never goes above 1. Change one thing, a slow request every fifth tick instead of every fourth, and round-robin deals the slow ones to s0, s1, s2, s3 in turn and never holds more than 2 on a server. That is the real lesson. Round-robin is not always bad. It is bad when a pattern in the traffic happens to match the rotation, and you cannot see that coming.

Policy trade-offs: cost per pick and state

Here n is the number of servers. Time is the work per routing decision; Space is the state the balancer has to keep current.

CaseTimeSpaceWhy
Round-robinO(1)one counterCheapest possible. Blind to load, so it is only safe when requests cost about the same.
RandomO(1)noneNo coordination at all, so many balancers can run it independently. Imbalance comes from luck, not from lock-step.
Least-connectionsO(n) scan, O(log n) with a heapn live countersEvery request start and finish updates a counter. Accurate on one balancer; across several, each one sees only its own share.
Power of two choicesO(1)reads 2 countersNearly the balance of least-connections for the price of two lookups, and it tolerates slightly stale counts.
Hash (modulo n)O(1)noneSame key, same server, until n changes. Then almost every key moves.
Consistent hashingO(log n) ring lookupa ring of pointsKeeps affinity, and adding or removing a server moves only about 1/n of the keys.

The axis that matters is how much the balancer knows. Round-robin and random know nothing and cost nothing. Least-connections knows everything about its own traffic and pays for it in shared state. Power of two choices buys most of that knowledge with a constant amount of work, which is why it suits fleets of balancers that cannot share counters cheaply. For one balancer in front of a handful of servers, the O(n) scan is nothing. The cost that bites is keeping counters right across many balancers.

Common mistakes

  • Load-testing with identical requests

    A benchmark that replays one request type makes every policy look the same, as the worked example shows. Replay real traffic, with its slow tail, or the test cannot tell the policies apart.

  • Least-connections on several balancers

    Each balancer counts only the requests it sent. With four balancers, each sees about a quarter of a server’s real load and can keep picking the same “idle” server. Share the counts, or use power of two choices, which copes with partial information.

  • Counting connections when the cost is requests

    HTTP/2 and gRPC carry many requests over one long-lived connection. An L4 balancer counting connections sees one per client and balances nothing. Balance per request at L7.

  • The failing server that looks idle

    A server that returns errors instantly finishes every request at once, so it always has the fewest in flight, and least-connections sends it more traffic. Pair the policy with health checks that eject servers on error rate, not only on timeouts.

  • A new server gets a stampede

    A server just added has zero connections, so least-connections routes every new request to it until it catches up, often while its caches are still cold. Ramp new servers in gradually; HAProxy’s slowstart server setting does exactly this.

Where this shows up in production

  • NGINX and HAProxy

    NGINX upstreams default to weighted round-robin, with least_conn, ip_hash, hash and random two least_conn (power of two choices) as options. HAProxy offers roundrobin, leastconn and hash-based modes, and recommends leastconn for long sessions such as database connections.

  • Envoy and service meshes

    Envoy’s least-request policy samples two hosts at random and picks the one with fewer active requests: power of two choices, built for many proxies that never share counters.

  • Cloud load balancers

    AWS Application Load Balancer target groups route round-robin by default and can switch to “least outstanding requests”, the same idea as least-connections counted per request. The choice follows the lab’s rule: when request durations vary a lot, a load-aware policy is worth the state it keeps.

  • The interview angle

    In “design a load balancer”, naming a policy is the start. The follow-ups are the mistakes above: what happens with several balancers, with long-lived connections, with a server that fails fast, and with a server you just added. Then comes the question every design must answer: what happens when the balancer itself fails? A pair of balancers, or several behind DNS, removes that single point of failure.

Quick check

1. When do round-robin and least-connections behave differently?

2. What information does least-connections use that round-robin ignores?

3. What is the "power of two choices" load-balancing trick?

FAQ

What is a load balancer?

A component that distributes incoming requests across a pool of backend servers so none is overwhelmed, improving throughput, latency, and availability, and routing around failures via health checks. It operates at L4 (connections) or L7 (HTTP-aware) and uses a policy like round-robin or least-connections.

What are the common load-balancing algorithms?

Round-robin, weighted round-robin, least-connections, least-response-time, random, power-of-two-choices, and hash-based (IP-hash / consistent hashing for affinity or cache locality). The choice depends on request uniformity, whether you need stickiness, and how much state the balancer keeps.

When would you use hash-based (sticky) load balancing?

When the same client or key should consistently hit the same server — for session affinity (server-held session state) or cache locality (same key to same cache node for hit rate). Consistent hashing is preferred because it keeps most keys mapped to the same server when the pool changes.

What is the difference between L4 and L7 load balancing?

L4 works at TCP/UDP, forwarding by IP and port without inspecting content — fast and protocol-agnostic. L7 understands HTTP, routing by path, host, headers, or cookies, terminating TLS, and doing content-based routing — more capable, more costly per request. Systems often use both.

Keep going

▶  Watch it explained

Load Balancing Algorithms: How the Load Balancer Picks a Server

Finished this one? 0 / 61 Labs done
NextRaft: The Election Closest lab to this one

This idea in other formats

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs