Layer 4 vs Layer 7 Load Balancing
What you'll learn: How load balancers operate at different network layers and what capabilities each layer provides.
Core Idea
Load balancers can work at different levels of the network stack, primarily Layer 4 (Transport Layer) and Layer 7 (Application Layer) of the OSI model. Each layer sees different information and offers different routing capabilities.
Layer 4 Load Balancing (Transport Layer)
Layer 4 load balancers make routing decisions based on TCP or UDP information:
- Source and destination IP addresses
- Port numbers
- Basic connection state
Think of it like a mail sorting center that only looks at the address on the envelope—it doesn't open the package to see what's inside.
Characteristics:
- Fast and efficient (less data to inspect)
- Protocol-agnostic (works with any application protocol)
- Cannot make decisions based on message content
- Lower latency overhead
Layer 7 Load Balancing (Application Layer)
Layer 7 load balancers inspect the actual HTTP request content:
- URL paths
- HTTP headers
- Cookies
- Request methods (GET, POST, etc.)
This is like opening the envelope and reading the letter to determine where it should go based on its content.
Characteristics:
- Intelligent routing (e.g., send
/api/requests to API servers,/images/to media servers) - Can modify requests/responses
- SSL termination at load balancer
- Higher latency (more processing required)
When to Use Each
Use Layer 4 when you need raw speed and don't need content-based routing.
Use Layer 7 when you need sophisticated routing logic based on request content.
Key Takeaway: Layer 4 load balancers route based on network connection information (fast but simple), while Layer 7 load balancers route based on application message content (slower but more intelligent).