AlgoViz

Layer 4 and layer 7 load balancers

medium 26 min

A layer 4 load balancer chooses a server from addresses and ports and keeps a whole connection on it.

Video lesson · Chapter 1 of 5

Follow one encrypted connection

0:00 / 4:11

Label or contents: layer 4 and layer 7 in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A load balancer receives traffic for a service and hands it to one of several servers. The important question is how much of the traffic it reads before it decides. The numbers 4 and 7 name how far up the network layers it looks.

At layer 4 it reads IP addresses, ports and the protocol, TCP or UDP. It picks a server once per connection, or per UDP flow, and then passes everything along. At layer 7 it understands the application protocol, usually HTTP. It receives the whole request, reads the host, path, headers and cookies, and can pick a different server for every request.

Why it exists

Reading less is cheap. A layer 4 balancer keeps little memory per connection and can work for any protocol that runs on TCP or UDP, including databases, games and mail.

Reading more is useful. If /api and /images live on different servers behind one name, somebody must read the path. The same place can hold certificates, add headers, limit requests and send one percent of users to a new version. That needs decryption and parsing, so it costs processor time.

A short history

  1. May 1994

    RFC 1631 describes Network Address Translation: rewriting addresses in packets on the way through. Many layer 4 balancers use the same idea.

  2. August 2016

    AWS launches the Application Load Balancer, a layer 7 service that routes by the content of a request.

  3. September 2017

    AWS launches the Network Load Balancer, a layer 4 service built for very many connections.

  4. January 2019

    The Network Load Balancer gains TLS listeners. Decrypting and reading HTTP turn out to be two separate decisions.

Words to know

Five-tuple
Protocol, source address, source port, destination address and destination port. Together they name one flow.
VIP
Virtual IP: the one address clients connect to, held by the load balancer.
NAT
Network Address Translation: changing addresses or ports in a packet as it passes.
Flow table
The memory of which flow belongs to which server.
TLS termination
Ending the encrypted connection here, so the bytes inside can be read.
Full proxy
A balancer that holds two connections, one to the client and one to the server.
SNI
Server Name Indication: the host name a client sends at the start of a TLS handshake, normally readable without decryption.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask what must be read. Address and port, or host, path and cookie

Understand it

Start here

The parcel sorting story

Imagine a sorting room full of parcels. Some sorters only read the label outside. Others open the box and look at what is inside. The first is quicker. The second can make choices the first cannot.

Sorting parcels
Three closed parcelsDOOR 2DOOR 2DOOR 2

Reading the label is fast. Opening the box is informed. Big sorting rooms do one and then the other.

The layers

Where 4 and 7 come from

The seven layers of the OSI model

LayerNameExamplesWhich balancer
7ApplicationHTTP, WebSocket, gRPCLayer 7
6PresentationEncoding. TLS is often drawn here
5SessionRPC sessions, NetBIOS
4TransportTCP, UDPLayer 4
3NetworkIP, ICMPRead by layer 4 balancers too
2Data linkEthernet, MAC addresses
1PhysicalCables, radio
The model is a map, not a law. TLS sits between layers 4 and 7 in practice, and the internet does not use separate layers 5 and 6.

HTTPS is HTTP inside TLS inside TCP. HTTP/3 is HTTP inside QUIC, which runs on UDP and has TLS built in. So "layer 7" for a website means the balancer ends TLS as well.

Layer 4

How a layer 4 balancer works

Layer 4: one choice per connection

Clients connect to a virtual address on a layer 4 load balancer. Inside it the flow table remembers which flow belongs to which server. It forwards packets to server 1 and server 2 on port 8443. The TLS connection stays closed until it reaches a server.
The encrypted bytes pass through. Only addresses and ports are read.
  1. 1

    A SYN arrives

    The client opens a TCP connection to the virtual IP. The first packet is a SYN.

  2. 2

    Read the headers

    Source and destination address, source and destination port, protocol, and TCP flags such as SYN, ACK and FIN.

  3. 3

    Choose a server

    Round robin, least connections, weights, or a hash of the five-tuple or source address.

  4. 4

    Remember it

    Write the flow in the flow table, so later packets of the connection go to the same server.

  5. 5

    Forward

    With NAT, change the destination to the server's address and port, for example from 198.51.100.7:443 to 10.0.0.1:8443.

  6. 6

    The reply

    It returns through the balancer, which changes the source back. With direct server return the server answers the client itself.

Layer 4 can see

  • Source and destination IP address
  • Source and destination port
  • Protocol: TCP or UDP
  • TCP flags: SYN, ACK, FIN
  • The SNI host name, if it peeks at the TLS greeting

Layer 4 does not use

  • The URL path
  • HTTP headers and the Host header
  • Cookies
  • The request body
  • The content type

A layer 4 connection

The handshake really happens with the server. The balancer only rewrites addresses.

Choosing by hash

server=h(five-tuple) mod n\text{server} = h(\text{five-tuple}) \bmod n
The same flow always gives the same answer while nn stays the same. When a server is added, plain modulo moves most new lookups, so balancers also keep a flow table or use consistent hashing.

Layer 7

How a layer 7 balancer works

Layer 7: one choice per request

Clients send HTTPS to a layer 7 load balancer. Inside it, TLS ends and routing rules read the request. Requests under /api go to the API pool, which is one API server box, and requests under /static go to the static pool, which is one file server box.
TLS ends at the balancer, so it can read the path and send each request to the right pool.
  1. 1

    Accept the connection

    The balancer itself completes the TCP handshake with the client.

  2. 2

    End TLS

    It holds the certificate and key for the host, and decrypts.

  3. 3

    Parse the request

    Method, host, path, query string, headers, cookies. The body only if a rule needs it.

  4. 4

    Match the rules

    In a fixed order. The first match, or the most specific, gives a pool of servers.

  5. 5

    Change it if needed

    Add X-Forwarded-For and a request ID, rewrite the path, remove headers that must not come from outside.

  6. 6

    Forward and answer

    Use a connection that is already open to a server. The response can be compressed, cached or given new headers on the way back.

What layer 7 can route by

ByExample ruleUse
URL path/api/* to API serversSeveral services under one name
Hostapi.example.com to the API poolMany sites on one balancer
HeaderAccept: image/* to media serversSplit by what the client wants
Cookiegroup=beta to version 2Keep a tester on one version
Query stringregion=us to US serversExplicit choice in the link
MethodPOST to the write poolSeparate reads and writes
A query string or a language header is only what the client says. Do not use it as proof of where someone is.

What else it can do

  • TLS termination

    One place for certificates. See load balancer security for the choices.

  • Change requests

    Add, change or remove headers, and rewrite URLs.

  • Cache and compress

    Answer repeated reads itself, and shrink responses.

  • Protect

    Rate limits per client or endpoint, and a web application firewall.

  • Split traffic

    Send 10% of requests to a new version, for A/B tests and canaries.

  • Retry

    Send a safe request to another server when the first one fails.

Balance

Connections are not requests

Layer 4 spreads connections. HTTP/2 and gRPC put many requests on one long connection, so equal connections can mean very unequal work. Layer 7 spreads requests.

Three clients, three servers

layer 4: 1000,;100,;100layer 7: 1000+100+1003=400 each\text{layer 4: } 1000,;100,;100 \qquad \text{layer 7: } \frac{1000+100+100}{3} = 400 \text{ each}
Each client holds one connection. They send 1,000, 100 and 100 requests a second. With layer 4, one server does ten times the work of the others.

One busy connection

Fixes: a layer 7 balancer, balancing in the client, or a maximum age for connections so that clients reconnect.

Side by side

Layer 4 and layer 7 compared

QuestionLayer 4Layer 7
ProtocolsAny TCP or UDPHTTP, gRPC, WebSocket, or others it understands
Chooses perConnection or flowRequest
Added delayLowerHigher: decrypt, parse, second connection
Work per byteLessMore
TLSUsually passes through. Some products can end itUsually ends it
URL and host rulesNo. SNI only, if it peeksYes
Change headersNoYes
CacheNoSome products
Application firewallNo: it has no request to inspectYes
Stay on one serverFlow table or source addressCookie or header as well
Health checksTCP connect, often HTTP tooHTTP status and body
Retry a requestNoYes, when it is safe
Client address at the serverKept, or PROXY protocolX-Forwarded-For or Forwarded
The health check and the traffic are separate. A layer 4 balancer may check /health over HTTP and still forward TCP.

Forwarding

Pass through or full proxy

WayWhat happensServer sees the client as
NATRewrite the destination. Replies must come back this wayThe client, if only the destination changes
Full NATRewrite source and destinationThe balancer
Direct server returnDeliver unchanged to a server that also holds the VIPThe client. The reply skips the balancer
TCP proxyTwo TCP connections, bytes copied between themThe balancer, unless PROXY protocol is used
HTTP proxyTwo connections and full requestsThe balancer. The client is in a header

Connections from one proxy address to one server port

65535−1023=6451265535 - 1023 = 64512
Ports 1024 to 65535 at most: the operating system usually offers fewer. More proxy addresses, more server ports or reused connections raise the limit.

Products

Where you meet them

ProductLayer 4Layer 7
AWSNetwork Load BalancerApplication Load Balancer
AzureAzure Load BalancerApplication Gateway
Google CloudNetwork Load BalancersApplication Load Balancers
NGINXstream modulehttp module
HAProxymode tcpmode http
EnvoyNetwork filtersHTTP filters
TraefikTCP and UDP routersHTTP routers
F5 BIG-IPYesYes
Kong is an API gateway, Istio is a service mesh that uses Envoy, and Cloudflare is an edge network. All three make layer 7 choices and do other jobs too.

Uses

What each is good at

Reach for layer 4

  • Databases and other protocols that are not HTTP
  • Games and voice over UDP
  • DNS queries over UDP
  • Very many connections with little processing
  • Media ingest over TCP, such as RTMP
  • You must not decrypt here

Reach for layer 7

  • Version 1 and version 2 of an API under one host
  • /users and /orders on different services
  • One host name per tenant
  • A/B tests and canary releases
  • Static files and dynamic pages split
  • Headers, limits or a firewall at the edge

Together

Layer 4 in front of layer 7

Two tiers

Clients reach a layer 4 load balancer. It spreads connections over two layer 7 proxies, each its own machine. Both proxies route requests to a users service and an orders service.
The first tier gives a stable address and survives the loss of a proxy. The second tier reads requests.

Decrypting is the expensive part, so it is spread over several proxies. The layer 4 tier hides them behind one address and stops sending new connections to one that fails. Global and local load balancing adds a tier above this one, between regions.

Decide

A quick guide

Which layer?

Where does TLS end?

See load balancer security.

Good habits

Do and do not

Do

  • Use layer 4 for high-volume TCP and UDP
  • Use layer 7 when content decides
  • Give each layer a fitting health check
  • Reuse connections from layer 7 to servers
  • Combine the two in a large system
  • Plan certificates before you end TLS

Do not

  • Put an HTTP balancer before a protocol it does not know
  • Rely on source address alone for state
  • Forget the cost of decrypting and parsing
  • Forget WebSocket upgrades and long timeouts
  • Trust a client's forwarding headers
  • Retry a payment without an idempotency key

Summary

The whole topic in one minute.

Layer 4 chooses by address and port, once per connection. It works for any TCP or UDP protocol and does little work, but it cannot see a path, a header or a cookie. Long connections can leave it unbalanced.

Layer 7 chooses by the content of each request. It can route, rewrite, retry, cache and protect, and it pays for that with decryption, parsing and a second connection. Large systems often place layer 4 in front of a group of layer 7 proxies.

  • Layer 4 reads addresses and ports and chooses once per connection.
  • Layer 7 reads the request and can choose for every request.
  • Long HTTP/2 or gRPC connections unbalance layer 4.
  • Ending TLS and reading HTTP are separate choices.
  • Layer 4 in front of several layer 7 proxies is a common pair.

Sources