Load balancing is the distribution of network traffic across a pool of backend resources. It is implemented at either the Transport Layer (L4) or the Application Layer (L7).

L4 vs. L7 Load Balancing

FeatureL4 (Transport)L7 (Application)
OSI LayerLayer 4 (TCP/UDP)Layer 7 (HTTP/gRPC/TLS)
VisibilityIP, Port, ProtocolPath, Headers, Cookies, Body
PerformanceHigh (No packet inspection)Lower (Parsing overhead)
FeaturesSimple routing, NATContent-based routing, TLS termination
ExampleAWS NLB, IPVS, HAProxy (TCP)AWS ALB, Nginx, Envoy

Selection Algorithms

  1. Round Robin: Sequential assignment. Best for homogeneous backend capacity.
  2. Least Connections: Assigns to the node with the fewest active sessions. Best for long-lived connections (e.g., WebSockets).
  3. Consistent Hashing: Maps requests to nodes using a hash ring.
    • Math: A request with key k is assigned to node n = \text{argmin}_{i} (\text{hash}(n_i) \geq \text{hash}(k)).
    • Benefit: Minimizes cache invalidation when nodes join/leave; only $1/N$ of keys are remapped.

Health Check Mechanics

A load balancer must proactively prune unhealthy nodes from its rotation.

Failure Thresholds:

Advanced Patterns

1. TLS Termination vs. Passthrough

2. Draining (Graceful Shutdown)

When a node is marked for removal, the LB stops sending new requests but allows in-flight requests to complete before closing the connection. Mandatory for zero-downtime deployments.

3. Sticky Sessions (Session Affinity)

Ensures a client is routed to the same backend for the duration of a session.

Common Failure Modes