AlgoViz

Load balancing

medium 25 min

A load balancer gives many servers one address, sends each request to a healthy one and hides failures and upgrades.

See it run

Watch four algorithms choose a server, then health checks and draining keep requests away from the wrong one.

Operations

Round robin

Servers take turns. Nothing else is considered.

Step 1 of 5

Request 1

Our systemClientsLoad balancerServer A1 requestServer BServer CServer D

Turn 1: A

The first request goes to server A.

Step 1: Request 1

def round_robin():    pool = healthy(servers)    server = pool[turn % len(pool)]    turn += 1    return server
Looks at
The turn
Keeps
A counter
Least connections
looks at open work

Equal turns are not equal work.

In the real world

The same introduction to load balancing doing real jobs. Pick one and step through it.

Least connections, and a server that returns errors in 2 ms.

Step 1 of 4

Normal

Our systemClientsLoad balancerServer A10 openServer B10 openServer C10 open

Even

Three servers share the load.

Step 1: Normal

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Only one balancer

    critical

    Ten servers behind one balancer still go down together.

    Wrong
    clients -> balancer -> 10 servers
    Right
    clients -> balancer 1 or 2 -> 10 servers
  • A health check that queries the database

    critical

    A slow database then makes every server look dead.

    Wrong
    def health():    db.query("SELECT COUNT(*) ...")
    Right
    def health():    return 200   # this process can serve
  • Counting an ended request twice

    major

    Decrementing on error and again on close makes the count negative, and the server a magnet.

    Wrong
    on_error: open -= 1on_close: open -= 1
    Right
    on_close: open -= 1   # always, once
  • Stopping a server without draining

    major

    Uploads, calls and sockets are cut in the middle.

    Wrong
    stop(server)
    Right
    drain(server)stop(server)

Interview tips

  • How to explain it

    • One address in front, many servers behind.
    • Choose, forward, watch health.
    • Two balancers, never one.
  • Memory trick: LRWI

    • Least connections, Round robin.
    • Weighted, IP hash.
    • Load Routing With Intelligence.
  • Choose by

    • Similar requests: round robin.
    • Unequal servers: weights.
    • Unequal work: least connections.
  • Watch out for

    • Fast-failing servers.
    • Shared addresses with IP hash.
    • No room to lose one server.