7. Load Balancers, Reverse Proxies and API Gateways
7.2 What's the difference between a layer 4 and a layer 7 load balancer?
At the airport: One kind of queue manager only looks at your boarding pass number and sends you to the next free counter. It's very fast. Another kind reads your ticket: "business class? counter 1. Extra baggage? counter 9." It's slower, but much smarter.
In the system: The "layers" come from the networking model: layer 4 is the transport (TCP, UDP), layer 7 is the application (HTTP).
Figure: layer 4 reads the envelope; layer 7 opens it and reads the letter.
- A layer 4 (L4) load balancer sees only IP addresses and ports. It forwards TCP or UDP connections without looking inside. Very fast and works for any protocol (databases, game servers, MQTT), but it can't route on the URL, headers or cookies.
- A layer 7 (L7) load balancer understands HTTP. It can see the method, path, host, headers and cookies, so it can:
- send
/api/*to API servers and/images/*to image servers; - send
shop.example.comandblog.example.comto different pools; - terminate TLS (7.6), add headers, retry a failed request on another server, and make sessions sticky with a cookie (7.5).
- send
The cost of L7 is more work per request, because it must decrypt and parse HTTP. Many large systems use both: a fast L4 layer at the edge, then L7 proxies behind it.
Memory code: "L4 reads the envelope, L7 reads the letter."