Load balancer

Spread requests over several servers, steer around the one that's down, then see why a server that keeps sessions to itself gets people logged out (stateless vs stateful).

Level: BasicWatch: 8 steps · ~50 secondsPlay freelyRecall: 3 questions · 8 cardsCompare 5 ways to pick a serverTypeScript · Go · Python · nginx

What you'll take away

  • Tell round robin, least connections and ip hash apart, and which traffic each one suits
  • Know why people get 502s until the next health check, and what shortens that gap
  • Explain why sessions in a server's memory log people out when it dies, sticky or not
  • Move sessions to a shared store or a token, so servers are stateless and any can go

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
Load balancerround robin · session: none
load balancer · round robin
server 1 0/7
server 2 0/7
server 3 0/7
User A
User B
User C
User D
4 users send straight to server 1. No load balancer yet.
Step 1 / 8 · step by step
–Avg. response time (simulated)
1/1Servers up
0OK 200
0Failed 5xx
0Logged out 401

The simulation: 4 users in front, the load balancer a gate on the avenue, up to 4 servers as buildings (press one to turn it off or on). Each colored light is one person's request; the faint ring is a health check. The numbers come from a model on this page, not from real servers.

Step 4 · Every option at once, on one clock

Compare them all: Load balancer

The same requests in every tile: 6 users (two of them heavy), some jobs 2.4 seconds long. S1 is the big machine and runs 4 jobs at once; S2 and S3 run 2. A square is a job in progress, a yellow dot is a job waiting in the queue.

0.0 s (simulated)
Round robinavg – · worst – · done 0

Use it when Equal servers and jobs of about the same length: the simplest there is

Skip it when Servers of different power, or long jobs mixed with short ones

A model: the numbers come from the same set of requests on this page, not from real measurements. Press any tile to see it large above, with when it fits.

A load balancer does 3 things

  • Picks a server for each request, using the algorithm you set
  • Checks health (the health check) and steers around servers that are down. Between checks, the load balancer doesn't know yet.
  • Is the only way in: clients only know the load balancer's address, so you can add or remove servers behind it and nobody notices

Which one to pick

MethodWhat it doesGood when
Round robinGoes in order: 1 → 2 → 3Requests take about the same time
Least connectionsSends to whoever has the least work openRequests vary in length
IP hashSame person, same server (sticky)Only when you really need it: it hides the state problem

Stateless vs stateful

A stateful server keeps sessions in its own memory: the next request has to come back to the same server, and if that server dies, the session dies with it. A stateless server remembers nothing between requests: sessions live in a shared store (Redis, say) or in a token the client holds, so you can add, remove or turn off any server.

L4 vs L7

L4 only sees the IP and port (TCP / UDP): fast, and blind to what's inside. L7 reads HTTP, so it can send /api to one group and /static to another, or look at cookies and headers, at the cost of more work.

In real code

balancer.ts
// Two ways a load balancer picks a server, behind one interface (the Strategy pattern).
// Run: node balancer.ts   (Node 23.6+; on Node 22: node --experimental-strip-types balancer.ts)
import assert from "node:assert/strict";

interface Server { name: string; healthy: boolean; active: number }
interface Strategy { pick(servers: Server[]): Server | undefined }

class RoundRobin implements Strategy {
  private next = 0;
  pick(servers: Server[]): Server | undefined {
    for (let tried = 0; tried < servers.length; tried++) {
      const s = servers[this.next++ % servers.length];
      if (s.healthy) return s;
    }
    return undefined; // every server is down: answer 503
  }
}

class LeastConnections implements Strategy {
  pick(servers: Server[]): Server | undefined {
    let best: Server | undefined;
    for (const s of servers) if (s.healthy && (!best || s.active < best.active)) best = s;
    return best;
  }
}

const servers: Server[] = [
  { name: "s1", healthy: true, active: 4 },
  { name: "s2", healthy: false, active: 0 }, // failed its health check
  { name: "s3", healthy: true, active: 1 },
];

const rr: Strategy = new RoundRobin();
const picks = Array.from({ length: 4 }, () => rr.pick(servers)?.name);
assert.deepEqual(picks, ["s1", "s3", "s1", "s3"]); // s2 is skipped
assert.equal(new LeastConnections().pick(servers)?.name, "s3"); // fewest open connections
assert.equal(new RoundRobin().pick(servers.map((s) => ({ ...s, healthy: false }))), undefined);
console.log(`round robin: ${picks.join(" → ")} · least connections: s3`);
Run: node balancer.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: round robin: s1 → s3 → s1 → s3 · least connections: s3

Round robin and least connections sit behind the same interface, so the load balancer can switch methods without touching any other code. That's the Strategy pattern. Servers that fail the health check get skipped.

Common questions

What does a load balancer actually do?

It's the only address clients know. It picks a server for each request, checks which servers are healthy and skips the ones that are down, so you can add or remove servers behind it without anyone noticing.

Round robin or least connections: which one should I use?

Round robin goes in turn and fits requests that take about the same time. Least connections sends to whoever has the least work open, so it copes better when some requests run much longer than others.

Table: which one to pick

Why should the servers behind a load balancer be stateless?

If a server keeps sessions in its own memory, the next request may land on a server that doesn't have them, and when that server dies its sessions go with it. Keep them in a shared store or a signed token and any server can answer anyone.

Aren't sticky sessions (IP hash) enough?

They keep each person on the same server, which works until that server dies and everyone on it is logged out. Hashing by remainder also moves other people to new servers. Sticky hides the state problem; it doesn't make it go away.

What happens in the seconds after a server goes down?

The load balancer doesn't know yet, so requests sent there get a 502 until the next health check takes it out. Checking more often shortens that gap, and requests that are safe to resend, like a GET, can be retried on another server.

How do active and passive health checks differ?

Active: the load balancer sends its own request (to /health, say) every few seconds. Passive: it counts real requests that fail and rests that server for a while. Free nginx does passive checks.

What's the difference between an L4 and an L7 load balancer?

L4 sees only the IP and port (TCP / UDP), so it's fast but blind to what's inside. L7 reads HTTP, so it can send /api and /static to different groups or look at cookies and headers, at the cost of more work.

Next lesson

CachingLevel: Basic

Several servers now share the work; next, keep most requests from reaching the database at all.