Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 1

Balancing algorithms and the tail

Compare round robin, least outstanding requests, power of two choices and hash-based balancing with a seeded simulation, and learn why the choice shows up in p99 latency more than in the average.

Contentsand lesson path

What you will learn

  • Choose a balancing algorithm (round robin, least requests, power of two choices, hash-based) for a workload and explain its effect on tail latency.

Prerequisites: Scalability Fundamentals

01. Why it matters

A load balancer makes one small decision thousands of times a second: which instance gets this request? The rule it uses is the balancing algorithm. Most rules look fine on average latency. The difference appears in the tail: the slowest 1% or 0.1% of requests, written as p99 and p99.9. A p99 of 400 ms means one request in a hundred took 400 ms or longer.

The tail matters more than it seems. Busy users make many requests, so they meet the tail often, and one page often fans out to many backend calls and waits for all of them. If each call is slow one time in 200 and a page needs 50 independent calls, the chance that at least one is slow is 1 − 0.995⁵⁰, about 22%. A rare event at the backend becomes the normal experience at the front. Dean and Barroso describe this effect in The Tail at Scale (linked below).

This lesson compares the main algorithms with a simulation you can run, then shows when to route by a hash instead. If you are unsure why we scale out at all, start with Scalability fundamentals.

02. Why round robin builds queues

Round robin sends request 1 to instance A, request 2 to B, request 3 to C, and starts again. It is simple, needs no information about the instances, and gives each one the same number of requests. That is exactly its weakness: it counts requests, not work.

Two things make work uneven in real systems:

  • Requests differ in cost. A search with many filters, a report export or a cache miss can cost ten or a hundred times more than a cache hit.
  • Instances differ in speed. One may sit on older hardware, share a host with a noisy neighbour, or pause for garbage collection.

Round robin keeps feeding a slow or busy instance at the same rate as the others, so a queue forms there. Queues grow non-linearly: as an instance nears 100% busy, waiting time rises steeply, so an instance at 90% utilisation can have a queue many times longer than one at 55%. The requests stuck in that queue are your tail.

Weighted round robin gives a fixed share to each instance, for example 2:1 for a server with twice the cores. It fixes differences you know in advance, but not ones that change minute by minute, and not uneven request costs.

03. A simulation: round robin, least outstanding requests and two choices

The script below is a small model, not a benchmark. Four servers each handle one request at a time; server 3 runs at 60% of the others' speed. Requests arrive at random (a Poisson process) at 115 per second; nine in ten cost 10 ms of work and one in ten costs 100 ms, an average of 19 ms. With a fixed seed, every run prints the same numbers.

It compares three policies:

  • Round robin: take turns.
  • Least outstanding requests: send to the server with the fewest requests in progress, counting both queued and running ones. Ties are broken at random.
  • Power of two choices: pick two servers at random and send to the one with fewer outstanding requests.

The last two tables give the balancer stale data: it refreshes its view every 50 ms or 200 ms and does not count its own recent sends, as happens when many balancers share a delayed load report or each sees only part of the traffic.

Python 3.12 · lb_sim.py (standard library only)
"""Compare balancing policies on servers of uneven speed (stdlib only)."""
import random
from collections import deque

SPEEDS = [1.0, 1.0, 1.0, 0.6]  # server 3 does 60% of the work per second
RATE = 115.0  # requests per second arriving at the balancer
N = 200_000  # requests per run
SEED = 7


def make_trace() -> list[tuple[float, float]]:
    """Arrival time and cost in seconds of work on a speed-1.0 server."""
    rng = random.Random(SEED)
    t, trace = 0.0, []
    for _ in range(N):
        t += rng.expovariate(RATE)  # random (Poisson) arrivals
        cost = 0.100 if rng.random() < 0.10 else 0.010  # 1 in 10 is heavy
        trace.append((t, cost))
    return trace


def pick(policy, view, rng, counter):
    if policy == "round_robin":
        return counter % len(view)
    if policy == "least_outstanding":
        low = min(view)
        return rng.choice([i for i, v in enumerate(view) if v == low])
    a, b = rng.sample(range(len(view)), 2)  # power of two choices
    if view[a] == view[b]:
        return rng.choice((a, b))
    return a if view[a] < view[b] else b


def run(policy, trace, data_age=0.0):
    rng = random.Random(SEED + 1)
    free_at = [0.0] * len(SPEEDS)  # when each one-at-a-time server is idle
    pending = [deque() for _ in SPEEDS]  # finish times of accepted requests
    view, next_refresh, ms, served = [], 0.0, [], [0] * len(SPEEDS)
    for i, (arrival, cost) in enumerate(trace):
        for q in pending:
            while q and q[0] <= arrival:
                q.popleft()  # this request has finished
        if arrival >= next_refresh:  # data_age=0 means a fresh view
            view = [len(q) for q in pending]  # outstanding requests
            next_refresh = arrival + data_age
        s = pick(policy, view, rng, i)
        free_at[s] = max(arrival, free_at[s]) + cost / SPEEDS[s]
        pending[s].append(free_at[s])
        ms.append((free_at[s] - arrival) * 1000)
        served[s] += 1
    ms.sort()
    p50, p99, p999 = (ms[int(q * N)] for q in (0.5, 0.99, 0.999))  # by rank
    share = " ".join(f"{100 * c / N:4.1f}" for c in served)
    mean = sum(ms) / N
    print(f"{policy:<17} {mean:6.1f} {p50:6.1f} {p99:7.1f} {p999:7.1f} | {share}")


if __name__ == "__main__":
    trace = make_trace()
    head = "policy              mean    p50     p99   p99.9 | % per server"
    for age, names in [(0.0, ["round_robin", "least_outstanding", "power_of_two"]),
                       (0.05, ["least_outstanding", "power_of_two"]),
                       (0.2, ["least_outstanding", "power_of_two"])]:
        label = "fresh" if age == 0 else f"up to {age * 1000:.0f} ms old"
        print(f"Load data {label}; latency in ms")
        print(head)
        for name in names:
            run(name, trace, age)
Terminal
python3 lb_sim.py
Expected output (seeded, identical on every run)
Load data fresh; latency in ms
policy              mean    p50     p99   p99.9 | % per server
round_robin        128.4   20.1  1408.7  2559.6 | 25.0 25.0 25.0 25.0
least_outstanding   30.9   10.0   181.7   307.5 | 26.9 27.0 27.0 19.1
power_of_two        38.9   15.0   207.5   351.3 | 26.8 26.6 26.8 19.9
Load data up to 50 ms old; latency in ms
policy              mean    p50     p99   p99.9 | % per server
least_outstanding   50.6   17.3   303.6   492.1 | 26.9 27.0 27.0 19.0
power_of_two        47.4   16.7   268.6   419.6 | 26.8 26.6 26.8 19.8
Load data up to 200 ms old; latency in ms
policy              mean    p50     p99   p99.9 | % per server
least_outstanding   97.9   44.7   563.8   878.9 | 26.9 26.9 26.7 19.5
power_of_two        68.5   24.8   370.4   584.6 | 26.9 26.6 26.5 20.0

Round robin gives every server exactly 25% of the requests. The three fast servers then run at about 55% busy, but the slow one runs at about 91% (28.75 requests per second × 19 ms ÷ 0.6). Its queue explodes, and its requests set the p99 at 1,408.7 ms. The average, 128.4 ms, hides how bad that tail is.

Least outstanding requests reacts to the queue it can see. It sends only 19.1% of requests to the slow server, and p99 drops to 181.7 ms. Notice that the median also halves: fewer cheap requests wait behind expensive ones. Power of two choices, with only a sample of two, gets most of the way there: p99 207.5 ms.

Now look at the stale tables. With data up to 200 ms old, least outstanding requests gets much worse (p99 563.8 ms) and falls behind power of two choices (370.4 ms). The reason is herding: every request in one stale window sees the same "least loaded" server, so they all go there and build a queue the balancer cannot see yet. Two random choices spread those decisions, so no single server gets the whole burst. In Mitzenmacher's 2001 analysis of large server pools, going from one random choice to two gives an exponential improvement in the expected time a request spends in the system, while a third choice adds only a constant factor.

Many proxies therefore combine the two ideas. When all hosts have equal weight, Envoy's least-request balancer picks two random hosts by default and sends to the one with fewer active requests; HAProxy's random(2) and NGINX's random two least_conn work the same way.

04. Least requests or least connections?

Older balancers count connections. HAProxy's leastconn, for example, picks the server with the fewest connections, and its manual recommends it for very long sessions such as LDAP or SQL. NGINX's least_conn also counts active connections; idle keep-alive connections waiting in its cache do not count. That works when one connection carries one request at a time.

It stops working when connections and requests drift apart: with HTTP/2 or gRPC one connection carries many requests at once, and an L4 balancer in front of long-lived client pools counts open connections, busy or idle, rather than work. Then the number to watch is outstanding requests, sent and not yet answered, which Envoy's least-request policy and the AWS Application Load Balancer's "least outstanding requests" algorithm count. Read the documentation, not the name: Caddy's least_conn policy counts current requests too.

Any load-aware policy has one trap. A server that fails fast, for example returning an error in 2 ms because it lost its database connection, looks idle. A least-requests balancer then sends it more traffic, and the error rate climbs. The Google SRE book describes this exact problem; its fix is to count recent errors as if they were active requests. Pair load-aware balancing with health checks and with passive error tracking, both covered in the next lesson.

05. Hash-based balancing: trading balance for affinity

Sometimes you want the same key to reach the same instance every time: a cache tier works best when each key has one home, and a stream processor may need all events for one account on one worker to keep them in order. A hash-based policy hashes a key, such as a user ID, a URL or a cache key, and maps it to an instance.

The naive mapping, hash(key) % N, moves almost every key when N changes, which empties caches exactly when you are scaling. Consistent hashing and rendezvous (highest-random-weight) hashing fix that: when one of N instances is added or removed, only the keys that belong to it move, roughly 1/N of them when keys spread evenly. The exact share depends on the number of virtual nodes, replicas and how skewed the keys are. The Consistent hashing skill covers the algorithms in depth.

The price is that a hash ignores load. A hot key overloads its home while other instances idle; the hot keys lesson shows ways around that. Hashing on the client's source IP adds a trap: thousands of users behind one corporate or mobile carrier NAT share a few addresses, so a few instances receive most of the traffic. Consistent hashing with bounded loads (Mirrokni and colleagues, 2018) is a middle ground: each instance accepts keys only up to a cap slightly above the average, and overflow moves to the next instance.

A starting point for choosing, not a rule
Workload                                        Start with
Similar, cheap requests on similar servers      round robin or random
Uneven request cost or uneven server speed      least outstanding requests
Many balancers, or load data that is not fresh  power of two choices
Known, fixed capacity differences               weighted round robin
Per-key locality (cache tier, ordered streams)  consistent or rendezvous hash

06. Check your understanding

Practice check · 3 questions

Algorithms and their effect on the tail

Three questions about load signals, hashing and connection counts.

Q1. A pool of 12 servers uses a plain least-outstanding-requests policy that counts only requests in progress. One server loses its database connection and answers every request with a 500 error in about 2 ms. Nothing else is wrong. What happens next?
Q2. A stateless API switches to source-IP hashing "to spread load evenly". Most of its traffic arrives from two corporate NAT gateways and one mobile carrier gateway. What should the team expect?
Q3. An NGINX upstream uses `least_conn` and caches up to 32 idle keep-alive connections to each server. A teammate says least_conn therefore cannot steer traffic away from a server that has become slow, since every server always shows 32 connections. Is the teammate right?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice task for this skill asks you to compare round robin with least requests under uneven request costs behind a real proxy. Prepare for it with the simulation:

  1. Set SPEEDS = [1.0, 1.0, 1.0, 1.0] and run again. Which policy gains the most when only request cost varies?
  2. Raise RATE from 115 to 140. Write down p99 for each policy and explain why round robin degrades first.
  3. Change the stale ages to 20 ms and 500 ms. At what age does least outstanding requests fall behind power of two choices?

Keep the numbers for the lab, where Caddy runs the same comparison on three real processes.

08. Review prompt

Without looking back, explain to a colleague why round robin can give one server a long queue even though every server receives the same number of requests. Then explain why a balancer that always picks the least loaded server can do worse than one that compares only two random servers, and name one workload where you would choose a hash-based policy despite its uneven load.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check