Course contents

03. Scaling and Load Balancing Lesson 3 of 8

Load Balancing

See how a load balancer spreads traffic, why round robin overloads slow servers, how least connections and health checks work, and what N+1 capacity means.

15 minBeginner12 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A load balancer gives clients one stable address and spreads requests across servers.
  • Round robin is fair by count, not by capacity; least connections adapts to slow servers.
  • Health checks remove failed servers, but only after interval × threshold.
  • Survivors must be able to carry the load of a failed server (N+1).
  • The balancer is itself a dependency: run it redundantly.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A load balancer sits between clients and a group of servers that do the same job. Clients connect to the balancer's address; for every request (or connection) it picks one server, forwards the traffic and relays the answer back. To the client the group looks like one server.

Why it exists

One machine has a ceiling: a fixed number of requests it can work on at once and a time per request. Past that ceiling, requests wait and then fail. Running more copies of the service raises the ceiling, but only if traffic actually reaches the copies. The load balancer is the piece that does that, and it also hides servers that are down.

How it works

Layer 4 or layer 7. A layer-4 balancer works with TCP/UDP connections: it picks a server per connection and forwards bytes without reading them. A layer-7 balancer terminates HTTP, so it can route by path, host or header, retry idempotent requests and add headers, at the cost of more work per request.

Choosing a server. Common algorithms:

  • Round robin takes turns. Cheap and predictable; fair only when servers and requests are similar.
  • Weighted round robin gives bigger servers more turns. You must keep the weights right.
  • Least connections (or least outstanding requests) picks the server with the fewest requests in progress. Slow servers and slow requests show up as more work in progress, so it adapts without configuration.
  • Random, or "power of two choices" picks two servers at random and takes the less loaded one; it avoids a herd of balancers all picking the same idle server.
  • Hashing (by client IP, user or key) sends the same key to the same server, useful for caches; consistent hashing limits how many keys move when servers change.

Health checks. The balancer probes each server on an interval (a TCP connect, or an HTTP request to a health endpoint). After a number of consecutive failures the server is taken out of rotation; after a number of successes it is put back. Many balancers also use passive checks: real requests that fail count against the server.

When to use it

Whenever more than one instance serves the same traffic: web and API tiers, internal services, database read replicas. Also when you need a stable entry point while servers come and go (deployments, autoscaling).

When not to

  • A single instance with no need for redundancy: a balancer adds a hop and another thing to run.
  • When clients can balance themselves well (gRPC clients with service discovery, or a service mesh sidecar); a central balancer may be redundant there.
  • For stateful protocols where any server cannot handle any request, until the state is moved out of the servers.

Trade-offs

Choice You gain You pay
Layer 7 instead of layer 4 Routing by content, retries, observability CPU per request, TLS termination to manage
Least connections instead of round robin Adapts to slow servers and requests Needs connection tracking; misleads with long-lived connections
Short health check interval Faster detection More probe traffic, more false alarms from brief hiccups
Sticky sessions Simple in-memory sessions Uneven load; users lose sessions when a server dies

Alternatives

  • DNS round robin: several IP addresses for one name. Free and global, but clients cache answers, so failover is slow and uneven.
  • Client-side balancing: the client knows all instances (from service discovery) and picks one. No extra hop; every client needs the logic.
  • Anycast: the same IP is announced from many locations and the network routes to the nearest. Used by CDNs and global front doors.

Failure modes

  • Detection gap: between a crash and the server's removal, requests sent to it fail. Size it as interval × threshold.
  • No headroom: removing a dead server moves its traffic onto the others. If they were already near capacity, the failure of one becomes the overload of all (cascading failure).
  • Flapping: a server that passes and fails checks alternately keeps entering and leaving rotation. Require several consecutive successes before restoring it.
  • Health check lies: an endpoint that returns 200 while the app cannot reach its database keeps a broken server in rotation. Check what matters, but not so deeply that one shared dependency fails every server at once.
  • The balancer itself can fail or saturate.

In production

Run balancers as a redundant pair (with a floating IP or virtual router protocol) or use a managed, multi-zone balancer. Drain connections before taking a server out for deployment. Monitor per-backend error rate and latency, not just the total. Keep sessions and other state in a shared store so any server can handle any request.

Common misconceptions

  • "Round robin is fair." It is fair by count. If one server is slower, or some requests are much heavier, equal counts mean unequal load.
  • "More servers always means lower latency." Only while the bottleneck is the servers. If the database is saturated, more application servers add load to it.
  • "Health checks make failures invisible." They shorten the impact; requests in the detection window still fail unless clients retry.
  • "A load balancer removes single points of failure." A single balancer is one.

Interview angle

Interviewers expect you to place a balancer in front of every stateless tier without being asked, then probe: which algorithm and why, layer 4 vs 7, how health checks and draining work, how you avoid the balancer being a single point of failure, how sessions are handled, and whether the remaining servers can absorb a failure. Mentioning capacity in numbers ("each instance does ~75 req/s, peak is 160, so four instances leave N+1 headroom") stands out.

Model assumptions

The simulation in this lesson is a simplified model, not a benchmark. Each server has 6 workers, an 80 ms mean service time (lognormal, cv 0.35) and room for 12 waiting requests; the older server runs at half speed. Arrivals are random (Poisson). Network hops take a fixed 5–25 ms. Health checks probe every 500 ms; 2 failures eject, 3 successes restore. Utilisation is the fraction of busy workers, not CPU. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every request goes to one server

    Users send about 30 requests per second to a single application server. It can work on six requests at once and needs about 80 ms per request.

    At this load it is busy about 40% of the time. Requests rarely wait, so latency is close to the network time plus the 80 ms of work.

    Scene: Users connect directly to App 1. App 1 is about 40% busy and every request succeeds.

    Key idea: A server has a fixed capacity: how many requests it can work on at once, times how fast it finishes them.

  2. 2. Traffic doubles

    A few seconds in, traffic climbs to 60 requests per second. The server is now busy around 80% of the time.

    Watch the queue counter under App 1. When all six workers are busy, new requests wait their turn, and that waiting time is added to every one of them. P95 latency rises long before anything fails.

    Scene: Traffic rises from 30 to 60 requests per second. App 1 becomes about 80% busy and requests start to queue.

    Key idea: Latency starts climbing well before 100% utilisation, because requests queue whenever the server is momentarily full.

  3. 3. The server is saturated

    At 90 requests per second we ask for more than the server can do (about 75 per second). Its workers never rest, the waiting line fills up, and once it is full the server answers new requests with an error straight away (HTTP 503).

    Red packets are those rejections. A faster server would only push the limit further out; at some point one machine is not enough.

    Scene: At 90 requests per second App 1 is overloaded: 100% busy, its queue is full and some requests fail with 503.

    Key idea: Past capacity, a server cannot go faster: extra requests either wait longer or are rejected.

  4. 4. Two more servers… doing nothing

    We start two more copies of the application. But users still know only one address, App 1’s, so the new servers receive no traffic at all.

    Adding capacity is only half of horizontal scaling. Something has to spread the requests across the copies.

    Scene: App 2 and App 3 are running but idle; all traffic still goes to App 1, which stays overloaded.

    Key idea: Extra servers help only if traffic can reach them.

  5. 5. A load balancer in front

    Users now talk to a load balancer: one stable address that forwards each request to one of the servers and passes the response back.

    Each server gets about a third of the 90 requests per second and settles near 40% busy. The rejections stop and latency drops back to the single-server level.

    Scene: Users send requests to the load balancer, which forwards each one to App 1, 2 or 3. All three are about 40% busy and nothing fails.

    Key idea: A load balancer gives clients one address and spreads their requests over many servers.

  6. 6. Round robin: take turns

    This balancer uses round robin: App 1, App 2, App 3, App 1, … It needs no information about the servers, which makes it cheap and predictable.

    Traffic grows to 120 requests per second. Each server gets exactly a third, about 40 per second, and is roughly half busy.

    Scene: At 120 requests per second round robin gives each server about 40 requests per second; all three are about half busy.

    Key idea: Round robin spreads requests evenly by count. That is only fair when servers and requests are alike.

  7. 7. One server is slower

    App 2 runs on older hardware and needs twice as long per request, so it can handle only about 37 requests per second.

    Round robin does not know that. It keeps sending App 2 its third, about 40 per second. App 2 saturates and rejects requests while App 1 and App 3 have spare capacity. P95 latency is now set by the slowest server.

    Scene: App 2 is slower and overloaded with a full queue; App 1 and App 3 are only about half busy. Some requests to App 2 fail.

    Key idea: Equal shares are not fair shares: round robin overloads the weakest server first.

  8. 8. Least connections: ask who is free

    Switch the balancer to least connections: each request goes to the server with the fewest requests in progress right now.

    A slow server holds on to its requests longer, so its count stays high and it is picked less often. Work shifts to App 1 and App 3 on its own, the rejections stop and P95 drops.

    Scene: With least connections, App 2 receives fewer requests than App 1 and App 3. Nothing is rejected and latency drops.

    Key idea: Least connections adapts to slow servers and slow requests by looking at work in progress, not at turns.

  9. 9. A server crashes

    One and a half seconds in, App 3 crashes. The balancer does not know yet: it keeps sending App 3 its share, and those requests fail.

    It finds out through health checks: every 500 ms it probes each server, and two failed probes in a row take a server out of rotation. Until then, users see errors. That gap is the price of detection.

    Scene: App 3 crashes. Requests sent to it fail until the load balancer’s health checks mark it unhealthy, after about one second, and stop routing to it.

    Key idea: Failure detection takes time: probe interval × failures needed. Shorter intervals detect faster but cost more probes and risk false alarms.

  10. 10. The survivors carry everything

    App 3 is out of rotation, so all 120 requests per second go to App 1 and the slow App 2. Together they can do about 112.

    The balancer did its job, but the system is still overloaded: queues fill and some requests are rejected. Removing a failed server only helps if the remaining ones have room for its traffic.

    Scene: With App 3 down, App 1 and App 2 take all traffic and are both near or above full capacity; some requests are rejected.

    Key idea: Plan for N+1: with one server gone, the rest must still handle peak traffic.

  11. 11. App 3 comes back

    App 3 restarts one second in. The balancer does not trust it immediately: it must pass three health checks in a row first. Its tag shows that progress.

    Waiting avoids sending traffic to a server that is still starting up or flapping between up and down. Once healthy, least connections fills it up quickly because it has no work in progress.

    Scene: App 3 recovers. After three good health checks the load balancer routes to it again and the overload clears.

    Key idea: Bring servers back gradually: require several good checks, then let them warm up.

  12. 12. What a load balancer does not solve

    The balancer is now a component everything depends on. In production it runs as a pair or a managed service so that it is not a single point of failure.

    Other things to decide: layer 4 (connections) or layer 7 (HTTP, can route by path or header); whether sticky sessions are needed (they weaken balancing; keep sessions in a shared store instead); and that least connections can mislead with long-lived connections like WebSockets.

    Scene: All three servers are healthy behind the load balancer using least connections. The load balancer is highlighted as the remaining single point of failure.

    Key idea: Balancing spreads load. Capacity, detection time and the balancer’s own availability are still your design problems.