Card 05/ 10

ConceptDifficulty: Intermediate2 min

Layer 4 and Layer 7 Load Balancing

One sees addresses and ports; the other reads the URL, the headers and the cookies.

A layer 4 load balancer routes on what it can see in a connection's packets: the client's address and port, and the destination port. A layer 7 load balancer reads the HTTP request itself: the URL path, the headers and the cookies. What a balancer can route on is what it can read, and reading more costs more work.

Where the names come from. Networking is described in layers. Layer 4 is the transport layer, where TCP, the protocol that carries a stream of bytes between two machines, lives. Layer 7 is the application layer, where HTTP lives. A layer 4 balancer forwards a TCP connection without looking inside it; a layer 7 balancer reads each HTTP request.

What each sees in the same request for https://shop.example.com/cart

Layer 4addresses and ports

Client address 198.51.100.7, port 52144. Destination port 443. Everything else is encrypted bytes it does not open. It can route by client or by port, and nothing more.

Layer 7the whole HTTP request

Path /cart, host shop.example.com, the session cookie, the User-Agent header. It can send /cart to one group of servers and /images to another, or route by cookie.

What reading costs. Most traffic is encrypted with TLS, Transport Layer Security. To read the path, a layer 7 balancer has to decrypt the request, which takes processing and means it holds the site's certificate. A layer 4 balancer passes the encrypted bytes through untouched, so it is faster and can carry protocols other than HTTP, such as a game's own protocol or a database connection.

Where you meet each. AWS's Network Load Balancer works at layer 4 and keeps each connection on one server for its whole life. AWS's Application Load Balancer works at layer 7 and routes by path, host and header. NGINX and HAProxy can be configured as either.

Choosing. Reach for layer 7 when routing depends on the request: different paths to different services, or a cookie that must reach the same server. Reach for layer 4 when the traffic is not HTTP, when connections are long-lived, or when raw throughput matters more than routing rules.

So ask what the routing rule has to read: if it needs the path or a header, the balancer has to work at layer 7.