Load Balancing

Spread traffic across many servers so no single one becomes the bottleneck or the single point of failure.

Load balancing in 30 seconds

  • What: a traffic cop in front of a pool of identical servers — it picks which one handles each request and routes around dead ones.
  • Why: it lets you scale out and survive failures without the client noticing anything changed.
  • L4 vs L7: Layer 4 balances fast on TCP/IP; Layer 7 reads HTTP so it can route by path, terminate TLS, and retry smartly.
  • Algorithms: round robin (equal work), least-connections (uneven durations), weighted (mixed hardware), consistent hash (affinity).
  • Avoid sticky sessions: keep servers stateless with session state in a shared store, so any server can take any request.
  • The balancer is a SPOF: run it as a redundant pair with health checks that eject dead backends automatically.

The host at a busy restaurant

Walk into a packed restaurant and you don't pick your own table or wander into the kitchen to find a free cook. A host stands at the door, sees which servers have capacity, and seats you with whichever one can take you fastest. If a server calls in sick, the host simply stops seating their section — you never notice. A load balancer is that host for your servers: it stands at the one front door, knows who's free and who's overloaded or down, and quietly sends each request to a server that can handle it. The diners (your users) only ever see the host; they never need to know how many cooks are back there or that one just went home early.

The problem it solves

One server has a ceiling: so many requests per second, so much memory, one power cable. A load balancer sits in front of a pool of identical servers and decides which one handles each request. That lets you scale out (add more servers) and survive failures (route around a dead one) without the client knowing anything changed.

There are really two separate pains hiding here, and a load balancer cures both at once. The first is capacity: when a single machine is saturated, your only escape is to put more machines to work — but clients know one address, so something must spread the load across the pool. The second is failure: hardware dies, deploys go wrong, a process crashes. With one server, its death is your outage. With a pool and a balancer, one death is a shrug — the traffic just flows to the survivors.

The gap a single bigger server can't fill

The naive alternative is 'just buy a bigger box' — more CPU, more RAM, scale up instead of out. It works for a while and it's genuinely simpler. But it hits two hard walls that no cheque can knock down, and seeing those walls is the whole case for load balancing.

  • There's a biggest box. You can always add another machine to a pool, but the single most powerful server money can buy is a fixed ceiling. Past it, scaling up is simply not an option.
  • One box is one point of failure. However powerful, a single server has one set of hardware, one OS to patch, one process that can crash. When it goes, everything goes. A pool spreads that risk across many independent machines.

So scaling out — many modest servers behind a balancer — beats scaling up on both the ceiling and the failure story. The price is that you now need a component to distribute work and track health. That component is the load balancer, and the rest of this page is about how it makes its two decisions well.

The core idea, plainly

A load balancer is a traffic cop with a health checklist. It knows which servers are alive, applies a rule to pick one, and forwards the request. The two decisions that matter are how it picks (the algorithm) and what it tracks about each connection (whether it needs to remember a user's session).

The load balancer hides the server pool behind one address.

Health checks: how it knows who's alive

Before a balancer can route around a dead server, it has to notice the server died. It does this with health checks: on a short interval, it pings each backend (often a tiny HTTP request to a /health endpoint) and watches the reply. A server that fails a few checks in a row is pulled out of rotation; when it starts passing again, it's quietly let back in.

A periodic health check marks backends up or down (python)
def health_loop(pool):
    for server in pool:
        try:
            resp = http_get(f"http://{server.addr}/health", timeout=1)
            server.healthy = (resp.status == 200)   # quick, cheap probe
        except TimeoutError:
            server.healthy = False                   # no answer -> eject
    # only servers with healthy == True are eligible to receive traffic.
    # run this every few seconds so a dead node leaves rotation fast.

This is the mechanism that turns a pool into something resilient rather than just big. Without health checks, the balancer would keep cheerfully routing a share of traffic to a corpse, and those users would see errors. With them, a failure is detected in seconds and the load silently reshapes around it.

Health checks plus redundancy turn a server's death into a non-event.

Layer 4 vs Layer 7

Layer 4 balances on TCP/UDP — it sees IPs and ports, forwards fast, and doesn't understand the request. Layer 7 balances on HTTP — it can read the path, headers, and cookies, so it can route /api to one pool and /images to another, terminate TLS, and do smart retries. Layer 7 is more capable and slightly more expensive per request.

Layer 7 content-based routing (javascript)
// A Layer 7 balancer can read the HTTP request and route by content.
// A Layer 4 balancer only sees IP:port and couldn't do this.
function routePool(req) {
  if (req.path.startsWith('/api'))    return apiPool;      // service pool
  if (req.path.startsWith('/images')) return staticPool;   // static assets
  if (req.headers['x-canary'] === '1') return canaryPool;  // header routing
  return webPool;                                          // default
}
// then pick one healthy server within the chosen pool (see below).

Balancing algorithms

Once the balancer has a chosen pool of healthy servers, it needs a rule for which one gets the next request. The rules trade simplicity against how well they handle uneven work.

AlgorithmHow it picksProsConsUse when
Round robinNext server in rotation.Dead simple; even for uniform work.Ignores that some requests are heavier.Requests are roughly equal in cost.
Least connectionsServer with fewest open connections.Adapts to uneven request durations.Needs live connection counts.Long-lived or variable requests.
WeightedProportional to server capacity.Mixes big and small machines fairly.You must set and maintain weights.Heterogeneous hardware.
IP / consistent hashSame client maps to same server.Sticky without shared session store.Uneven if client distribution is skewed.You need affinity but not a session DB.
Round robin: rotate through healthy servers (javascript)
let cursor = 0;
function roundRobin(pool) {
  const alive = pool.filter(s => s.healthy);   // skip dead backends
  if (alive.length === 0) throw new Error('no healthy servers');
  const server = alive[cursor % alive.length]; // next in rotation
  cursor++;
  return server;
}
// Even and dead simple -- but it ignores that some requests are far
// heavier than others. Least-connections (below) adapts to that.

Round robin's blind spot is worth making concrete. Imagine six requests arrive: five are instant health pings and one is a giant report that takes ten seconds. Round robin hands them out in a strict rotation, so if the heavy one lands on server A, the next heavy one might land on A again purely by the luck of the rotation — while server B sits idle. Least connections fixes this by looking at reality instead of a counter: it sends the next request to whoever is currently juggling the fewest, so the server stuck on the ten-second report naturally stops getting new work until it catches up.

Least-connections selection (pseudocode)
def pick_server(pool):
    alive = [s for s in pool if s.healthy]
    if not alive:
        raise NoHealthyServers
    # choose the server currently handling the fewest requests
    return min(alive, key=lambda s: s.active_connections)

The sticky-session trap

If a server keeps a user's session in local memory, the balancer must send that user back to the same server every time — sticky sessions. It works, but it ties scaling and failover in knots: when that server dies, the session dies with it. The cleaner design is stateless servers with session state in a shared store (a cache or database), so any server can handle any request and the balancer is free to pick optimally.

Here's why 'stateless' is the magic word. If every server stores a logged-in user's session (their cart, their auth token) only in its own memory, then that user is handcuffed to that one server — the balancer loses its freedom to route optimally, a crash logs the user out, and you can't smoothly add or remove servers. Move that session into a shared store that all servers can read, and suddenly every server is interchangeable. The balancer can send any request anywhere, failover is seamless, and scaling out is just 'add another identical box.'

Stateless servers read session from a shared store (javascript)
// BAD: session lives in this server's memory -> user is stuck here forever
// sessions[userId] = { cart, authToken };   // lost if this server dies

// GOOD: any server can serve any request by reading shared state
async function handle(req) {
  const session = await redis.get(`session:${req.cookies.sid}`);
  // ... process using session ...
  await redis.set(`session:${req.cookies.sid}`, session, 'EX', 3600);
}
// Now the load balancer is free to pick the best server every time.

Choosing: a quick decision guide

SituationReach forWhy
Plain web tier, similar requestsL7 + round robinSimple, even, and you get HTTP-aware routing for free.
Long or variable request timesLeast connectionsRoutes by real load, not a blind rotation.
Mixed old and new hardwareWeightedBigger boxes earn a larger share of traffic.
Raw TCP / very high throughputL4No HTTP parsing overhead; fastest forwarding.
Need path/header routing, TLS terminationL7Only L7 can read the request to decide.

Load balancing is the hinge that horizontal scaling turns on — without it, 'just add more servers' is a wish, not a plan, because something has to decide where each request goes and route around what's broken.

Why it matters

  • It's what makes a pool of servers look like one endpoint, so you can scale out transparently.
  • It's a core availability mechanism: health checks pull dead backends out before users feel them.
  • The algorithm and session choices quietly decide how evenly work spreads and how cleanly failover works.

If ignored

  • One server stays the ceiling and the single point of failure no matter how many you've provisioned.
  • Sticky sessions tie users to a node, so when it dies their session dies with it and failover stalls.
  • The balancer itself becomes an unmonitored SPOF that takes everything down when it falls over.

Where it fits

  • Sits at the front of the request path, between clients (or the CDN/gateway) and the server pool.
  • Pairs with stateless servers plus a shared session store so any server can handle any request.
  • Leans on health checks and replication so routing always lands on a live, capable backend.

Related topics

  • Scalability: load balancing is the mechanism horizontal scaling depends on
  • API gateway: often sits just behind the balancer and adds API-level concerns
  • Caching: where stateless servers keep session state so the balancer stays free
  • Availability & reliability: health checks and redundancy are how a balancer improves uptime

Interview lens

Questions it unlocks

  • How do you scale a web tier horizontally?
  • What breaks if one of your app servers goes down mid-request?
  • Why are stateless servers easier to scale?

60-second answer

I'd put a Layer 7 load balancer in front of a pool of stateless app servers, with session state in a shared cache so any server can handle any request. Health checks eject dead backends in seconds. For picking, least-connections handles uneven request durations better than round robin. I'd make the balancer itself redundant as an active-passive pair so it isn't a SPOF. I'd avoid sticky sessions unless forced, because they couple failover to a single node.

Common traps

  • Treating the load balancer as free and forgetting it's a SPOF.
  • Defaulting to sticky sessions instead of externalizing state.
  • Using round robin for workloads with very uneven request costs.

Search topics

↑↓ to move · Enter to open · Esc to close