SYS ARCHITECTLearning Platform
Settings
Theory

Layer 4 vs. Layer 7 Load Balancing

📋 Overview

Load balancing is the process of distributing network traffic across multiple servers. In the OSI model, this can happen at the Transport Layer (Layer 4) or the Application Layer (Layer 7). Choosing between L4 and L7 is a trade-off between the raw speed and efficiency of connection-level routing versus the intelligence and flexibility of content-aware routing.


🏗️ Core Principles & Characteristics

  • Layer 4 (Transport):
    • Data Used: IP addresses and TCP/UDP ports.
    • Action: Forwards packets blindly without "looking inside" the data.
    • NAT: Uses Network Address Translation to redirect traffic.
  • Layer 7 (Application):
    • Data Used: HTTP headers, Cookies, URLs, and JSON payloads.
    • Action: Terminates the connection, parses the request, and makes a routing decision based on the content.

⚖️ Trade-offs: Pros & Cons

  • Layer 4 Pros:
    • Ultra-Fast: Minimal CPU overhead since it doesn't parse application data.
    • Protocol Agnostic: Works for any TCP/UDP service (MySQL, DNS, SMTP).
  • Layer 7 Pros:
    • Smart Routing: Can send /images to one server and /api to another.
    • Security: Can detect and block malicious payloads (WAF) or handle SSL termination.
    • Stickiness: More reliable "Sticky Sessions" based on cookies rather than just IP.

🌍 Real-World Implementation

  • L4 Use Case: Handling massive, low-level traffic for a database cluster or a gaming server where latency is the #1 priority. (Tools: HAProxy, AWS NLB).
  • L7 Use Case: Modern microservices where different URL paths are served by different teams/pods. (Tools: Nginx, AWS ALB, Traefik).

💡 Interview "Gotchas" & Tips

  • The "Termination" Point: L7 load balancers terminate the TCP connection, while L4 balancers just forward the packets. This means L7 is inherently a "Man-in-the-Middle."
  • Latency: L7 is slower because it has to wait for the full HTTP request to arrive before it can decide where to send it.
  • SSL Termination: If the LB handles SSL, it must be at least L7 (or L4 with SSL Passthrough) to read the encrypted headers.

📐 Suggested Architecture Primitives

  • Network Load Balancer (NLB): For L4 high-throughput needs.
  • Application Load Balancer (ALB): For L7 feature-rich needs.
  • Reverse Proxy: The base technology for L7 balancing.
  • WAF (Web Application Firewall): Usually sits on top of an L7 balancer.
Canvas