Load Balancing

How traffic gets divided across servers: L4 vs L7, algorithms, health checks, sticky sessions.

Beginner7 min read
Language
Theme
Load BalancerL7: path / headersServer 1Server 2Server 3Health checksremove dead serversAlgorithms: round robin / least connections / IP hash / weighted
Key idea at a glance
INTERACTIVE

Playground: the load balancer

Send traffic and watch each algorithm pick a server. Kill a server and watch health checks kick it out of rotation.

Client
→
Load
Balancer

Why the load balancer exists

Horizontal scaling means many app servers. Someone must decide which server takes each request: that is the load balancer. It does three jobs at once: distribute (spread load evenly), protect (stop sending traffic to dying servers), and hide (clients see one address, servers can be added/removed behind it).

L4 vs L7, with the real difference

  • L4 (transport): sees only IP + port, forwards TCP/UDP streams without parsing them. Extremely fast (millions of connections per box), but blind: cannot route /api vs /images differently. Examples: AWS NLB, classic hardware LB.
  • L7 (application): terminates the connection and reads HTTP: path, headers, cookies, method. Enables path routing (/api -> API pool, /static -> CDN origin), header-based routing (mobile app versions), cookie stickiness, and request-level retries. Examples: NGINX, HAProxy, AWS ALB, Envoy, Cloudflare.

The tradeoff: L7 costs CPU (TLS termination + parsing) but buys routing intelligence. Modern systems default to L7; L4 sits in front when raw connection throughput is the bottleneck.

Distribution algorithms and when each wins

  • Round robin: next server in line. Fine when requests cost about the same and servers are identical.
  • Least connections: send to the server with fewest active requests. Wins when request durations vary wildly (some 10 ms, some 10 s): long requests do not pile up on one unlucky server.
  • Consistent/IP hash: same client always hits the same server. Good for local caching, but creates hot spots and complicates rebalancing.
  • Weighted: server with 2x capacity gets 2x traffic. Also the canary-deploy tool: route 5% to the new version, watch errors, ramp to 100%.

Health checks: the part that keeps users happy

The LB pings each server (TCP connect or HTTP /health) every few seconds. Two failures in a row: server leaves the rotation, traffic silently flows to the rest. Recovering server passes checks again: it rejoins. Tuning matters: too sensitive and flapping servers bounce in and out; too slow and users hit dead servers for seconds. Typical: 2-5s interval, 2-3 failure threshold, and a /health endpoint that actually checks dependencies (DB reachable, disk not full) rather than always returning 200.

The LB's own availability

"What if the LB dies?" is a mandatory follow-up. Answers: active-passive LB pairs with virtual-IP failover, DNS-level balancing across LB instances, Anycast (many LBs worldwide share one IP, BGP routes to the nearest), or a managed cloud LB that handles this internally. Never draw one LB box without its failover story.

Worked example

API at 20k RPS, request cost 5-500 ms (mixed). Choice: L7 ALB/NGINX, least-connections (because durations vary), HTTP health checks at 3s interval with 2-failure threshold, /health verifying DB connectivity, 2 LB instances via the cloud's multi-AZ setup. Sessions in Redis so any app server can take any request.

Common interview traps

  • One LB box with no failover answer.
  • Sticky sessions as the session strategy instead of a shared session store.
  • Round robin for a workload with wildly uneven request costs.
  • Health checks that return 200 even when the server cannot reach the DB.

Interview Q&A

Q: How do you deploy a new app version with zero downtime?
A: Rolling/blue-green behind the LB: spin up new-version servers, add them to the pool once healthy, drain old servers (stop new connections, finish in-flight ones), remove. Weighted routing turns this into a canary: 5% traffic first, watch error rates, then ramp.

Q: All servers are "healthy" but users see timeouts. What is wrong?
A: Classic cases: the LB's connection pool to backends is exhausted, health checks pass but the app is slow (check latency, not just liveness), or keep-alive settings make the LB hold stale connections to recently restarted servers.

Key takeaways

Interview pointer

Do not just draw a load balancer box. Say which type (L7), which algorithm (least connections), how health checks work, and what the LB's own redundancy is. That depth is what gets noticed.