← All lessons
How load balancing works
Send a request through the load balancer
You
Load balancer
Servers
load-balancer.js
const servers = ["10.0.0.11", "10.0.0.12", "10.0.0.13"];let next = 0; http.createServer((req, res) => { const host = servers[next]; next = (next + 1) % servers.length; const upstream = http.request({ host, port: 8080, path: req.url, method: req.method, headers: { ...req.headers, "x-forwarded-for": req.socket.remoteAddress }, }, (reply) => { res.writeHead(reply.statusCode, reply.headers); reply.pipe(res); }); req.pipe(upstream);}).listen(80);Pick how it spreads the load and watch each server fill up
Open requests
app-10 open0 served
app-20 open0 served
app-30 open0 served
Every third request is a slow export that stays open for 9 seconds
pick.js
// take turns, one after anotherfunction roundRobin(servers) { return servers[count++ % servers.length];} // the server with the fewest open requestsfunction leastConnections(servers) { return servers.reduce((a, b) => (b.open < a.open ? b : a));} // the same visitor always lands on the same serverfunction ipHash(servers, ip) { return servers[fnv1a(ip) % servers.length];}Take a server down and the health check routes around it
Servers
app-1in pool
app-2in pool
app-3in pool
Last requests
Real load balancers check every few seconds. Here you run it by hand
load-balancer.js
setInterval(async () => { for (const s of servers) { const res = await fetch(`http://${s.host}/health`).catch(() => null); s.healthy = res?.ok ?? false; }}, 5000); function pick() { const pool = servers.filter((s) => s.healthy); if (pool.length === 0) return null; return pool[count++ % pool.length];} // a server that died since the last checkconst reply = await forward(pick(), req).catch(() => 502);Where does your cart live? when any server can answer
You
Load balancer
Servers
Redis
server.js
const sessions = new Map(); // in this server's memory app.post("/cart", (req, res) => { const cart = sessions.get(req.cookies.sid) ?? []; sessions.set(req.cookies.sid, [...cart, req.body.item]);}); app.get("/cart", (req, res) => { res.json(sessions.get(req.cookies.sid) ?? []);});load-balancer.js
// sticky sessions: the load balancer pins you to one serverconst host = req.cookies.lb ?? pick();res.setHeader("Set-Cookie", `lb=${host}`);server.js
// a shared store: every server reads the same Redisconst key = `cart:${req.cookies.sid}`;const cart = JSON.parse(await redis.get(key)) ?? [];await redis.set(key, JSON.stringify([...cart, item]));Topics
Next: How retries and backoff work
Open lesson