Sub topic 3
Layer 4 vs Layer 7 load balancing
This chapter assumes you know how a TCP connection is opened, what an IP address and port are, and what an HTTP request looks like (method, path, headers, status code). It also assumes you can read a short configuration file.
A load balancer can make its routing decision at different points in the network stack. The two common choices are Layer 4 (the transport layer, TCP and UDP) and Layer 7 (the application layer, usually HTTP). The choice affects what the balancer can see, what it can route on, how much work it does per request, and which failures you will meet.
The layers in one minute
The OSI model numbers the layers of a network protocol stack. Load balancing uses two of them:
- Layer 4 carries connections. A Layer 4 device sees source and destination IP addresses, source and destination ports, and the protocol (TCP or UDP). It does not read the bytes inside the connection.
- Layer 7 carries application messages. A Layer 7 device reads the HTTP request: the method, URL path, Host header, cookies, and other headers.
The rest of this chapter uses "L4" and "L7" as shorthand.
How a Layer 4 balancer works
An L4 balancer picks a backend when a new connection arrives. It uses only the connection's addressing information and the chosen algorithm. After that it forwards every packet of that connection to the same backend.
There are two common ways to forward:
- Network address translation (NAT) mode. The balancer rewrites the destination address of each packet to the backend's address. Replies return through the balancer, which rewrites the source address back. The client believes it is talking to one server.
- Direct server return (DSR). Requests pass through the balancer, but the backend sends replies straight to the client. Replies are often much larger than requests, so DSR keeps the balancer from carrying the bulk of the traffic. It needs backends configured to accept the balancer's virtual IP address, and the balancer and backends usually must share a network segment.
Some L4 balancers act as a TCP proxy instead. They accept the client connection, open a second connection to the backend, and copy bytes between the two. This is still L4 because the balancer does not interpret the bytes.
Because L4 does little work per connection, it is fast and handles very high connection rates. It also works for any protocol on top of TCP or UDP: databases, MQTT, SMTP, game traffic, DNS, or HTTP that you do not want to inspect.
How a Layer 7 balancer works
An L7 balancer is a reverse proxy. It terminates the client's TCP connection, reads the full HTTP request, then chooses a backend and sends the request over a separate connection. The response travels back along the same path.
Since the balancer can read the request, it can route on its content:
- Path-based routing:
/api/goes to one pool,/static/to another. - Host-based routing:
shop.example.comandblog.example.comgo to different backends. - Header or cookie rules: send requests with a beta cookie to a canary pool.
- Request rewriting: add
X-Forwarded-For, strip headers, redirect HTTP to HTTPS. - Per-request balancing: with HTTP keep-alive, one client connection can carry many requests, and the balancer can send each to a different backend.
The cost is more CPU and memory per request, and the balancer must understand the protocol. If it does not speak the protocol, it cannot balance it at L7.
Comparing the two
| Aspect | Layer 4 | Layer 7 |
|---|---|---|
| Decision based on | IPs, ports, protocol | URL, headers, cookies, body |
| Unit balanced | Connection | Request |
| Protocols | Any TCP or UDP | Protocols the balancer parses (HTTP, gRPC, and so on) |
| Per-request cost | Low | Higher |
| TLS | Can pass through unchanged | Must terminate to read requests |
| Content routing | No | Yes |
| Health checks | Connection-level (can the port be reached?) | Can check HTTP status and response content |
| Client IP seen by backend | Preserved in DSR and some modes, lost in proxy mode | Lost unless passed in a header |
Why the unit matters: connections versus requests
At L4 the unit of balancing is the connection, and this has a consequence that surprises people. Suppose a client opens one HTTP/2 or keep-alive connection and sends thousands of requests. An L4 balancer sends all of them to one backend, because they share a connection. Many such long-lived connections can load the backends unevenly even when the connection counts look equal.
gRPC is the usual example. It runs over HTTP/2, which multiplexes many calls on one long-lived connection. An L4 balancer places that connection on one backend, and the rest sit idle. An L7 balancer that understands HTTP/2 can spread the individual calls.
The reverse also applies. At L7 the balancer holds two sets of connections, one to clients and one to backends. Reusing backend connections (keep-alive to the pool) lowers the cost of opening new ones but means the balancer holds state for each.
Preserving the client address
When an L7 balancer proxies a request, the backend sees the balancer's IP as the source. The original client address is lost unless the balancer passes it on. Two standard methods exist:
- The
X-Forwarded-ForHTTP header, which an L7 balancer adds. The NGINX example later in this tutorial sets it withproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;. - The PROXY protocol, a short header the balancer prepends to the TCP stream, carrying the original source and destination addresses. It works for L4 proxying and for non-HTTP protocols. Both sides must be configured for it, because a backend that does not expect the header will treat it as garbage and fail the connection.
A TCP-level configuration
Here is an L4 setup in HAProxy. It forwards raw TCP to two database-style backends and never reads the contents:
frontend db_in
mode tcp
bind *:5432
default_backend db_pool
backend db_pool
mode tcp
balance leastconn
option tcp-check
server db1 10.0.0.21:5432 check
server db2 10.0.0.22:5432 checkThe key line is mode tcp. In this mode HAProxy does not parse the bytes, so any protocol works. The tcp-check option tests that the port accepts connections. It cannot tell whether the database is actually answering queries correctly unless you add a scripted check.
For comparison, the HTTP-mode configuration in the HAProxy example elsewhere in this tutorial uses mode http, which lets it use option httpchk, cookies, and header rules. The same software can act at L4 or L7, depending on that one setting.
Routing at Layer 7
This HAProxy fragment sends API calls and everything else to different pools. It shows what L4 cannot do:
frontend web
mode http
bind *:80
acl is_api path_beg /api/
use_backend api_pool if is_api
default_backend site_pool
backend api_pool
mode http
balance leastconn
server api1 10.0.0.31:9000 check
server api2 10.0.0.32:9000 check
backend site_pool
mode http
balance roundrobin
server web1 10.0.0.11:8080 check
server web2 10.0.0.12:8080 checkThe acl line defines a condition (the path begins with /api/), and use_backend applies it. Each pool can then use a different algorithm, which is another benefit of content routing: you tune the policy for each kind of traffic.
TLS and the choice of layer
An L7 balancer must read the HTTP request, and HTTPS encrypts it. So an L7 balancer has to terminate TLS: it holds the certificate and private key, decrypts the traffic, and usually sends plain or re-encrypted HTTP to the backend. An L4 balancer can instead pass the encrypted bytes through untouched, so the backend keeps the key and the balancer never sees the content. A later chapter covers this trade-off in full. For now, remember that the layer you choose limits your TLS options.
L4 balancers can sometimes route on the TLS Server Name Indication (SNI), the hostname a client sends in the unencrypted start of the handshake. That allows host-based routing without decryption, but nothing finer such as path-based routing.
Failure modes and edge cases
- Connection-level health checks pass while the application fails. A TCP check succeeds if the port is open, even when the application returns errors on every request. Use an HTTP check where you can.
- Uneven load from long-lived connections. As described above, L4 balancing of multiplexed protocols concentrates load. Check per-backend request rates, not only connection counts.
- Reply path breakage in DSR. If a backend does not have the virtual IP configured correctly, replies come from the wrong address and the client drops them. Symptoms are connections that hang after the first packet.
- Lost client IP in proxy modes. Logs and rate limits on the backend then see only the balancer's address. Add
X-Forwarded-Foror the PROXY protocol. - Mismatched PROXY protocol settings. Enabling it on only one side breaks every connection.
- Timeout mismatch. The balancer's idle timeout must be longer than the client's keep-alive and shorter than the backend's. Otherwise a backend can close a connection the balancer still thinks is open, which shows up as sporadic 502 errors.
- Parsing limits at L7. Very large headers or request bodies, or unusual protocol use, can be rejected by the balancer with errors the backend never sees.
Choosing between them
Use L4 when:
- The protocol is not HTTP, or you do not want the balancer to parse it.
- You need the highest connection throughput with the least latency.
- You want end-to-end encryption with no decryption in the balancer.
- Routing by address and port is enough.
Use L7 when:
- You need routing by path, host, header, or cookie.
- You want one public address serving many services.
- You need request rewriting, redirects, or response-aware health checks.
- You want to balance each request, for example for gRPC or HTTP/2 clients.
Many deployments use both. An L4 tier at the edge spreads connections across several L7 balancers, and the L7 tier then routes requests to services. This separates the high-volume packet handling from the content-aware logic, and it lets the L7 tier scale out like any other pool.
Exercise
A team runs gRPC services behind an L4 balancer using round robin. Dashboards show one backend at high CPU and two nearly idle, even though each backend has the same number of connections. What is the likely cause, and what change would fix it?
Show answer
gRPC uses HTTP/2, which sends many calls over one long-lived connection. An L4 balancer assigns whole connections, so all calls on a busy connection land on one backend while the connection counts still look equal. Switch to an L7 balancer that understands HTTP/2 and balances individual calls (or use client-side balancing), so requests are spread per call instead of per connection.
Exercise
You need to send /api/ traffic to one pool and everything else to another, and the traffic is HTTPS. Can an L4 balancer with TLS passthrough do this? Explain.
Show answer
No. With passthrough the balancer cannot read the URL path because it is encrypted, so it cannot route by path. At most it can route by SNI hostname. To route by path you need an L7 balancer that terminates TLS (optionally re-encrypting to the backends).