What is the difference between a layer 4 and a layer 7 load balancer?
Show the answer
Say this first
A layer 4 load balancer decides with IP addresses and ports only. It forwards or NATs TCP and UDP connections without reading the payload, so it is fast, works with any protocol and needs no certificates. A layer 7 load balancer terminates the client's TCP and usually TLS, parses HTTP or gRPC, and picks a server by host, path, header or cookie. It can rewrite headers, insert X-Forwarded-For, compress and run a WAF, at the cost of more CPU and holding the certificates.
Go deeper
Layer 4 modes
- NAT: rewrites the destination VIP to a server address, one TCP connection end to end.
- Full proxy at layer 4: separate client-side and server-side TCP connections, no payload parsing.
- Direct server return: only the request passes the load balancer.
Layer 7
Always a full proxy with two connections. It can reuse server-side connections, speak HTTP/2 to clients and HTTP/1.1 to servers, and make per-request decisions on the same client connection.
TLS choices
| Mode | Who decrypts | Use |
|---|---|---|
| Passthrough | The server | Layer 4, end-to-end TLS, no inspection |
| Termination (offload) | The load balancer | Layer 7 routing, plain HTTP to servers |
| Re-encryption | Both | Layer 7 routing with encrypted server-side traffic |
Same idea on different products
HAProxy mode tcp vs mode http, F5 FastL4 vs a standard virtual server with an HTTP profile, AWS NLB vs
ALB, NGINX stream vs http.
They will ask next
Can a layer 4 load balancer route by hostname?
Only by peeking at the TLS ClientHello for the SNI (HAProxy
req.ssl_sni), without decrypting. That stops working if the client uses Encrypted Client Hello.
Traps
- Saying layer 7 is always better. Layer 4 is the right choice for non-HTTP protocols and raw throughput.