ayushsalampuriya.xyzRevise

HLD · Traffic

Load Balancing

Distribute incoming traffic across multiple servers for scale and availability.

In simple words: A load balancer chooses which server should handle each request. It spreads work across healthy servers so one machine does not receive all the traffic. Example: during a sale, 50,000 requests per second can be split across ten app servers instead of overloading one.

1. Why load balancing exists

One server has limited CPU, memory, and concurrent connections. A load balancer (LB) sits in front of a server pool and sends each request to a healthy backend server.

Example: During a sale, an e-commerce site receives 50,000 requests per second (RPS). If one VM handles 5,000 RPS, ten or more VMs behind an LB can share the load. If one VM fails, the LB stops sending requests to it.

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 routing depends on HTTP data, such as sending /api to API servers and /images to an image service. Use L4 when routing only needs an IP address and port, such as a raw TCP service.

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.

Use a cheap health endpoint. A liveness check asks whether the process is alive. A readiness check asks whether it is ready to receive traffic.

Concrete example: A new Java server may be alive while it warms its caches. Its liveness check passes, but its readiness check fails until warm-up ends, so the LB does not send user requests too early.

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.
  • Readiness: Do not route traffic until a server is ready.
  • Sessions: Prefer external session store over sticky LB.
  • SPOF: Managed LB or HA pair for the balancer itself.