Skip to main content

Load Balancing

Load balancers distribute incoming traffic across multiple servers to improve availability, reliability, and performance.

Benefits

Loading diagram...
BenefitDescription
High AvailabilityIf one server fails, others handle traffic
ScalabilityAdd servers to handle more load
PerformanceDistribute work evenly across servers
FlexibilityPerform maintenance without downtime
SecurityHide backend server IPs, absorb DDoS

Layer 4 vs Layer 7 Load Balancing

Layer 4 (Transport Layer)

Routes based on IP address and TCP/UDP port.

Loading diagram...

Operation:

  • Examines source/destination IP and port
  • No inspection of packet contents
  • Uses NAT to forward packets

Advantages: Very fast, low resource usage Disadvantages: Cannot route based on content (URLs, headers, cookies)

Layer 7 (Application Layer)

Routes based on HTTP content: URL paths, headers, cookies.

Loading diagram...

Operation:

  • Terminates TCP connection
  • Inspects HTTP request
  • Makes routing decision based on content
  • Opens new connection to backend

Advantages: Smart routing, request modification, SSL termination Disadvantages: Higher latency, more resource intensive

Comparison

AspectLayer 4Layer 7
SpeedFasterSlower
CPU usageLowHigher
Content inspectionNoYes
URL-based routingNoYes
SSL terminationNoYes
Request modificationNoYes
WebSocket supportBasicFull
Sticky sessionsIP-based onlyCookie-based

Load Balancing Algorithms

Round Robin

Distributes requests sequentially across servers.

Loading diagram...

Advantages: Simple, even distribution when servers are equal Disadvantages: Ignores server capacity and current load

Weighted Round Robin

Assigns weights based on server capacity.

Loading diagram...

Use case: Heterogeneous server fleet (different CPU/memory)

Least Connections

Routes to server with fewest active connections.

Loading diagram...

Advantages: Adapts to varying request duration Disadvantages: Does not account for connection weight

Least Response Time

Routes to server with fastest response time.

Advantages: Optimizes for user experience Disadvantages: Requires constant health monitoring

IP Hash

Hashes client IP to consistently route to same server.

Loading diagram...

Advantages: Session persistence without cookies Disadvantages: Uneven distribution if IPs are clustered

Algorithm Comparison

AlgorithmBest ForDrawback
Round RobinHomogeneous servers, stateless appsIgnores server load
Weighted Round RobinMixed server capacitiesManual weight tuning
Least ConnectionsLong-lived connectionsOverhead of tracking
Least Response TimeLatency-sensitive appsMonitoring overhead
IP HashSession persistenceUneven distribution
RandomSimple deploymentsUnpredictable

Session Persistence (Sticky Sessions)

Ensures user requests go to the same server.

Loading diagram...

Methods

MethodMechanismAdvantagesDisadvantages
Cookie-basedLB inserts server ID in cookieSurvives IP changesRequires cookie support
IP-basedHash client IPNo cookie neededBreaks with NAT/proxies
URL parameterServer ID in URLWorks everywhereURL modification

Recommended approach: Design stateless applications and store sessions in Redis/database.

Health Checks

Load balancers detect unhealthy servers through health checks.

Loading diagram...

Health Check Types

TypeVerificationUse Case
TCPPort is openBasic connectivity
HTTPEndpoint returns 200Web servers
Custom scriptApplication-specific logicComplex health criteria

Configuration Parameters

ParameterTypical ValueDescription
Interval5-30 secondsCheck frequency
Timeout2-5 secondsMax wait for response
Unhealthy threshold2-3 failuresFailures before removal
Healthy threshold2-3 successesSuccesses before restoration

High Availability for Load Balancers

Load balancers require redundancy to avoid being a single point of failure.

Active-Passive (Failover)

Loading diagram...

Operation:

  • Primary handles all traffic
  • Secondary monitors via heartbeat
  • On failure, secondary takes over VIP

Active-Active

Loading diagram...

Operation:

  • Both load balancers handle traffic
  • DNS distributes across LBs
  • More capacity, but complex state sync

Load Balancer Technologies

TechnologyTypeUse Case
NginxSoftware L7Web traffic, reverse proxy
HAProxySoftware L4/L7High performance, TCP/HTTP
AWS ALBManaged L7AWS applications
AWS NLBManaged L4Ultra-low latency
CloudflareCDN + LBGlobal distribution
F5 BIG-IPHardwareEnterprise, high throughput

Common Patterns

SSL Termination

Loading diagram...

Benefits:

  • Backend servers freed from SSL overhead
  • Centralized certificate management
  • Enables HTTP inspection for L7 routing

Global Load Balancing (GSLB)

Loading diagram...

Use case: Route users to nearest data center for lower latency.