FullStack AI Hub
Studio
System Design · 02. Scaling
12 min
12 steps
Beginner

Load Balancing

Distribute incoming requests across a server fleet without creating a new bottleneck.

System Design02. ScalingLesson 2 of 5
12 minBeginner12 steps

Load Balancing

Distribute incoming requests across a server fleet without creating a new bottleneck.

USERS
12,400
REQUESTS/S
1,800
P95 LATENCY
1,420 ms
ERRORS
18.4%
HEALTHY SERVERS
1 / 3 used
12,400 usersServer A96%DNS targetServer B2%Server C2%100% of traffic hits Server A
request
heavy request
health check
failed request
In This LessonStep 1 of 12
What You Will Master
  • ✓Spread traffic evenly across multiple servers with a load balancer
  • ✓Choose between round robin and least connections under uneven workloads
  • ✓Eliminate single points of failure with health checks and standby failover
  • ✓Route by URL path (L7) and drain connections cleanly during deploys

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Round Robin / Weighted RRHomogeneous stateless APIs with fast, uniform request costsBlind to slow heavy requests—one host can build a deep local queue
Least ConnectionsMixed workloads (8 ms JSON + 3 s PDF exports) or uneven host speedsRequires tracking in-flight connections per backend inside the balancer
Layer 7 Path RoutingTerminating TLS and splitting /api, /media, and /checkout pools cleanlySlightly higher CPU cost than L4 TCP passthrough because HTTP is parsed
Active-Passive VIP + DrainingEliminating balancer SPOFs (1–3 s failover) and zero-502 rolling deploysNeeds VRRP/Keepalived heartbeats and a bounded drain timeout (e.g. 30 s)

Step-by-Step Architectural Breakdown (12 Steps)

Full architectural walkthrough transcript and state transitions for Load Balancing.

STEP 01 · PROBLEMJump to step →

Three servers, one hot spot

You spun up three identical application servers—Server A, Server B, and Server C—to handle a surge in afternoon traffic. Yet latency is spiking and requests are timing out.

Because your DNS record points directly to **Server A**, every single client lands on the same machine while **Server B** and **Server C** sit completely idle at 0% CPU.

watch:Adding extra machines does nothing until a routing layer directs clients across them.

Hot SpotHorizontal FleetStatic DNS Pinning
STEP 02 · SOLUTIONJump to step →

Place a Load Balancer in front

We insert a **Load Balancer** at the front door of the fleet. Clients now talk to one stable public IP owned by the balancer rather than to individual servers.

Behind that single entry point, the balancer maintains a live pool of backend targets and forwards each incoming connection to one of your three servers.

idea:Decoupling client addresses from backend servers lets you add, replace, or restart nodes invisibly.

Load BalancerReverse ProxyBackend Pool
STEP 03 · TECHNIQUEJump to step →

Round robin distribution

The simplest routing policy is **Round Robin**: request 1 goes to Server A, request 2 to Server B, request 3 to Server C, and then the pointer wraps back to A.

It requires almost zero memory or coordination—just an atomic counter. When requests take roughly equal CPU time and servers have identical hardware, load stays balanced within a few percent.

good:Weighted Round Robin extends this easily: give a 2× larger machine weight 2 so it receives twice as many turns.

Round RobinWeighted Round Robin
STEP 04 · PROBLEMJump to step →

Heavy requests break round robin

Real traffic is rarely uniform. Some requests fetch a tiny JSON profile in 8 ms, while others export a PDF report or run a complex search that holds a worker thread for 3 seconds.

Because **Round Robin** ignores active in-flight work, it keeps dealing fresh requests to **Server B** even after several slow exports land there. Server B hits 97% CPU with **23 queued** requests while A and C coast.

watch:Equal request counts do not mean equal work—a handful of slow requests creates a deep local backlog.

Head-of-Line BacklogRequest HeterogeneityTail Latency
STEP 05 · SOLUTIONJump to step →

Switch to Least Connections

With **Least Connections**, the load balancer tracks how many open requests each server is currently processing and sends every new arrival to the machine with the smallest active count.

When Server B gets stuck on heavy PDF exports, its open connection count stays elevated—so the balancer naturally steers quick requests toward **Server A** and **Server C** until B catches up.

idea:Least Connections adapts to variable request cost automatically without needing servers to report CPU telemetry.

Least ConnectionsPower of Two ChoicesIn-Flight Tracking
STEP 06 · TECHNIQUEJump to step →

Detect dead servers with health checks

Machines crash, run out of memory, or hang on bad deployments. If **Server B** stops responding, a blind load balancer keeps routing a third of your users into a black hole.

Active **Health Checks** send a lightweight `GET /health` probe to every server every few seconds. After two consecutive failures, the balancer ejects Server B from the pool and shifts all traffic to A and C.

good:Keep /health fast and shallow—check that the process can serve traffic, not every downstream third-party API.

Active Health ChecksPassive Health ChecksCircuit Ejection
STEP 07 · PROBLEMJump to step →

When the Load Balancer itself fails

We protected ourselves against individual backend crashes, yet we quietly introduced a brand-new **Single Point of Failure (SPOF)** right at the front of the architecture.

If the sole Load Balancer suffers a hardware fault or kernel panic, all three healthy backend servers become completely unreachable and error rate jumps straight to **100%**.

watch:Never remove a single point of failure in one tier only to create an unguarded single point of failure in front of it.

Single Point of Failure (SPOF)Blast Radius
STEP 08 · SOLUTIONJump to step →

Add an Active-Passive standby balancer

To remove the front-door SPOF, we deploy a second **Standby Load Balancer** alongside the primary. Both share a **Virtual IP (VIP)** managed by a heartbeat protocol like VRRP or Keepalived.

During normal operation, the primary owns the VIP and serves every request while sending sub-second heartbeats to the passive standby.

idea:At even larger scale, teams run Active-Active balancers using BGP ECMP or DNS round-robin so every balancer carries live traffic.

Active-Passive HAVirtual IP (VIP)Heartbeat Protocol
STEP 09 · SOLUTIONJump to step →

Automatic failover in seconds

Now watch what happens when **LB Primary** dies: the heartbeat stops, and within a couple of seconds **LB Standby** claims the floating Virtual IP.

Clients never have to wait for slow DNS caches to expire. Traffic flows straight through the promoted balancer to all three servers with only a brief blip.

good:Virtual IP takeover completes in ~1–3 seconds, whereas DNS TTL propagation can take minutes.

Automatic FailoverVIP TakeoverHigh Availability
STEP 10 · TECHNIQUEJump to step →

Route by URL path (Layer 7)

A **Layer 4** balancer only inspects IP addresses and TCP ports—it forwards raw packets fast, without reading HTTP headers. A **Layer 7** balancer terminates TLS and reads the full HTTP request.

Because it can see the URL path, one L7 balancer routes `/api/*` to your API service, `/media/*` to your image workers, and `/checkout/*` to an isolated payments pool.

idea:L7 routing also unlocks TLS termination, cookie stickiness, header rewriting, and canary traffic splits.

Layer 4 vs Layer 7Path-Based RoutingTLS Termination
STEP 11 · TRADE-OFFJump to step →

Zero-downtime deploy with connection draining

Killing a server mid-request drops active checkouts and causes sudden 502 errors. Instead, the load balancer puts **Server B** into **connection draining**: it stops sending any new traffic while letting in-flight requests finish.

Once active connections hit zero, Server B boots the new release (`v2.4`), passes its health checks, and re-enters rotation cleanly.

watch:Always cap the drain timeout (e.g., 30 seconds) so a single hanging WebSocket cannot stall a deployment forever.

Connection DrainingGraceful ShutdownRolling Deployment
STEP 12 · RECAPJump to step →

Load Balancing recap

A production load-balancing tier does far more than split traffic evenly. Paired with **Least Connections**, **Health Checks**, and **Active-Passive VIP failover**, it turns fragile individual hosts into a resilient service.

At the application layer, **L7 path routing** isolates workloads by domain, while **connection draining** lets your team ship code throughout the day with zero user-facing errors.

good:Rule of thumb: start with managed L7 load balancers using Least Connections, shallow /health probes, and 30s connection draining.

Load Balancing ArchitectureResilient Front Door

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.