ayushsalampuriya.xyzRevise

HLD · Traffic

Load Balancing

Distribute incoming traffic across multiple servers for scale and availability.

1. Why load balancing exists

One server handles limited concurrent connections and CPU. A load balancer (LB) sits in front of a pool of identical app servers and routes each request to a healthy backend.

Example: An e-commerce site during a sale gets 50k RPS. One VM caps at 5k RPS. Ten VMs behind an LB share the load; if one dies, traffic shifts to the rest.

2. Layer 4 vs Layer 7

TypeOperates onCan route by URL?Example
L4 (transport)IP + TCP/UDP portNoAWS NLB, HAProxy TCP mode
L7 (application)HTTP headers, path, cookiesYesNGINX, AWS ALB, Envoy

Interview tip: Use L7 when you need path-based routing (/api → API fleet, /static → CDN). Use L4 for raw TCP, WebSockets at scale, or lowest latency.

3. Load balancing algorithms

Example: Video upload API uses least connections because uploads take 30–120s. A checkout API uses round robin because requests are short and uniform.

4. Health checks

LBs probe backends (GET /health) every few seconds. Unhealthy nodes are removed from rotation automatically.

Always implement a cheap health endpoint that verifies critical dependencies (DB ping optional — sometimes you want the node up but draining).

5. Session stickiness (affinity)

Stateful apps may require the same user on the same server (in-memory cart). Options:

6. Scaling pattern (interview walkthrough)

  1. DNS → LB (single entry point)
  2. LB → N stateless app servers (auto-scaling group)
  3. Shared DB + cache behind apps
  4. Scale horizontally until DB becomes bottleneck → read replicas, sharding

7. Failure modes

Quick revision

  • Purpose: Scale out, fault tolerance, single entry point.
  • L4 vs L7: IP/port vs HTTP-aware routing.
  • Algorithms: RR, weighted RR, least conn, consistent hash.
  • Health checks: Remove bad nodes automatically.
  • Sessions: Prefer external session store over sticky LB.
  • SPOF: Managed LB or HA pair for the balancer itself.