System Design: Load Balancing

Master traffic distribution, Layer 4 vs Layer 7 proxies, routing algorithms, consistent hashing rings, GSLB, and high-availability health checks.

1. What is Load Balancing?

A Load Balancer acts as a high-performance traffic director positioned in front of your server infrastructure. It accepts incoming network requests from clients and distributes them efficiently across multiple backend servers to ensure no single server becomes a bottleneck.

Core Load Balancer Architecture

System Design

Traffic distribution across a monitored cluster with automated health checks

100%
Loading system design canvas…

Scalability & Horizontal Scaling

Enables web applications to scale horizontally by adding commodity servers to a pool rather than upgrading a single expensive machine.

High Availability & Resilience

Prevents single points of failure (SPOF). If a server crashes or requires maintenance, traffic is automatically routed to surviving nodes.

Security & TLS Offloading

Offloads resource-intensive TLS/SSL decryption from application servers and shields backend servers from direct public internet exposure.

Traffic Management & Rate Limiting

Provides centralized entry points for throttling malicious traffic, managing DDoS attacks, and enforcing web application firewall (WAF) rules.

2. Layer 4 vs Layer 7 Load Balancing

Load balancers operate primarily at two distinct layers of the OSI model: Layer 4 (Transport Layer) and Layer 7 (Application Layer). Choosing the right layer determines the proxy's performance, flexibility, and operational overhead.

Layer 4 vs Layer 7 Traffic Routing

System Design

Transport-level packet forwarding vs Application-level content inspection

100%
Loading system design canvas…
FeatureLayer 4 (Transport Layer)Layer 7 (Application Layer)
Inspection DepthIP headers & TCP/UDP port numbers onlyFull HTTP headers, URLs, cookies, & JSON body payloads
Performance & ThroughputUltra-high throughput, near-zero CPU latency (Packet NAT)Moderate throughput, requires CPU for TLS decryption & parsing
Content AwarenessNo awareness of HTTP requests, cookies, or routesPath-based routing (e.g. /api vs /static), header routing
TLS TerminationPasses raw encrypted bytes through to backend serversTerminates TLS at proxy; encrypts or forwards cleartext internally
Example ImplementationsHAProxy (TCP mode), AWS Network Load Balancer (NLB), IPVSNginx, Envoy, AWS Application Load Balancer (ALB), Traefik

3. Load Balancing Algorithms

A load balancing algorithm dictates how incoming connections are selected and distributed across the available backend servers.

1. Round Robin

Distributes requests sequentially down the list of servers. Simple and stateless, but assumes all servers have equal capacity and equal job execution times.

Round Robin Request Distribution

System Design

Requests are handed out in a fixed, repeating order across the server list

100%
Loading system design canvas…

2. Weighted Round Robin

Assigns a numeric weight to each node based on hardware specs (e.g. Server A = weight 3, Server B = weight 1). Server A receives 3x more requests.

Weighted Round Robin Distribution

System Design

Higher-capacity nodes are assigned a larger share of incoming traffic

100%
Loading system design canvas…

3. Least Connections

Directs new requests to the server with the fewest active open connections. Optimal for long-lived connections such as WebSockets or database pools.

Least Connections Routing

System Design

New requests go to whichever server currently has the fewest open connections

100%
Loading system design canvas…

4. IP Hash

Hashes the client's IPv4/IPv6 address to deterministically route the client to the same server node every time, providing basic session persistence.

IP Hash Routing

System Design

A hash of the client IP deterministically maps that client to the same backend server

100%
Loading system design canvas…

Consistent Hashing & Virtual Nodes

Standard modulo hashing (Hash(Key) % N) fails catastrophically when a server node is added or removed because N changes, causing almost 100% of keys to re-map and invalidating distributed caches (cache stampede).

Consistent Hashing maps both servers and keys onto a circular hash ring (0 to 232-1). A key is assigned to the first server encountered moving clockwise on the ring. When a server is added or removed, only K / N keys are remapped on average!

Consistent Hashing Ring Architecture

System Design

Virtual nodes ensure uniform distribution across the 32-bit hash space

100%
Loading system design canvas…

Virtual Nodes (VNodes)

To prevent non-uniform key distribution (hotspots) due to sparse physical node placement, each physical server is mapped to dozens or hundreds of virtual positions (virtual nodes) across the ring.

Consistent Hashing Algorithm in Python

Virtual node mapping, circular ring placement, and clockwise lookup

4. Hardware vs Software Load Balancers

Hardware Load Balancers

  • Description:Specialized physical rack appliances built with custom ASICs or FPGAs.
  • Vendors:F5 BIG-IP, Citrix ADC (NetScaler), A10 Networks.
  • Pros:Unmatched raw throughput, gigabit-per-second packet processing, hardware TLS chips.
  • Cons:Extremely expensive ($10k–$100k+), complex physical management, poor flexibility in automated CI/CD pipelines.

Software Load Balancers

  • Description:Applications running on standard Linux VMs, bare-metal servers, or cloud containers.
  • Technologies:Nginx, HAProxy, Envoy Proxy, Traefik, AWS ALB/NLB.
  • Pros:Open-source, highly flexible, programmable via API/IaC (Terraform), cost-effective.
  • Cons:Bound by general-purpose CPU and Linux kernel OS networking stack limits.

Production Nginx Reverse Proxy & Load Balancer Config

Upstream pool configuration, IP hashing, weights, and health check locations

5. Global Server Load Balancing (GSLB)

While traditional load balancers manage traffic inside a single data center, Global Server Load Balancing (GSLB) routes user traffic across multiple geographically distributed data centers around the globe.

Global Server Load Balancing (GSLB) Architecture

System Design

GeoDNS routing user queries to nearest data center cluster

100%
Loading system design canvas…

GeoDNS Routing

Inspects the client's DNS resolver IP address and returns the IP of the data center nearest to the user, minimizing round-trip time (RTT).

BGP Anycast

Announces the exact same IP address from multiple data centers worldwide. Internet routers automatically pick the shortest network path via BGP.

6. Health Checks and Failover

Load balancers continuously send probe requests to backend nodes to verify operational health. If a node fails a set number of consecutive checks, it is temporarily removed from the active routing pool until health is restored.

Health Check & Automated Failover Sequence

System Design

Active probe polling, failure threshold detection, and automatic traffic migration

100%
Loading system design canvas…

Active Health Checks

The load balancer proactively pings endpoints (e.g. GET /health) every N seconds. Requires backend HTTP 200 OK response within a timeout period.

Passive Health Checks

Monitors real user traffic. If a backend node generates 500 Internal Server Errors or connection timeouts on real client requests, it is marked down.

7. Sticky Sessions (Session Affinity)

Sticky Sessions (or Session Affinity) ensure that all subsequent requests from a specific client browser are directed to the same physical backend server throughout the session.

How Cookie-Based Stickiness Works

On the initial request, the Layer 7 load balancer injects a unique HTTP cookie (e.g., SERVERID=node_A). On subsequent requests, the browser sends the cookie back, telling the load balancer to route directly to node_A.

Architectural Best Practice: Statelessness

Sticky sessions create uneven traffic distribution and prevent smooth failover if the sticky server crashes. Modern microservices store session state in a centralized Redis cache instead of local server RAM!

Load Balancing Knowledge Verification

1. What is the primary operational distinction between Layer 4 and Layer 7 Load Balancing?

2. Why is Consistent Hashing superior to standard Hash (Key % N) modulo routing in distributed server pools?

3. Which Load Balancing algorithm is best suited when backend servers have different hardware capacities (e.g., 64GB RAM vs 16GB RAM)?

4. What mechanism does Global Server Load Balancing (GSLB) primarily rely on to route users to the geographically nearest data center?

5. What is a major trade-off when using Sticky Sessions (Session Affinity) via load balancer cookies in stateful applications?