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.

See it run

Follow a connection and a request, and see what each balancer reads before it chooses.

Operations

Layer 4 connection

A TCP connection from its first packet to the reply. Only addresses and ports are read.

Step 1 of 5

A SYN arrives

Our systemClientLayer 4reads headersServer 110.0.0.1Server 210.0.0.2Server 310.0.0.3

packet

TCP · 203.0.113.9:50123 · 198.51.100.7:443

Client 203.0.113.9 opens a TCP connection to port 443 on the virtual address.

Step 1: A SYN arrives

def on_packet(p):    key = (p.proto, p.src, p.sport, p.dst, p.dport)    if key not in flows:        flows[key] = servers[hash(key) % len(servers)]    p.dst, p.dport = flows[key]      # NAT    forward(p)
Chooses per
Connection
Reads
Addresses, ports

Say that the flow table is what keeps later packets on the same server.

In the real world

The same layer 4 and layer 7 load balancers doing real jobs. Pick one and step through it.

A shop sends a small share of requests to a new version, by cookie.

Step 1 of 3

All on version 1

Our systemClientLayer 7100 and 0Version 1100%Version 20%Spareidle

Every request goes to the first server.

Step 1: All on version 1

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Balancing gRPC by connection

    critical

    Many calls share one connection, so one server becomes hot while others idle.

    Wrong
    server = pick(servers)      # once, at connect
    Right
    for call in stream:    server = pick(servers)  # per call
  • Trusting a client's forwarding header

    critical

    Anyone can write any address in it, and so dodge limits or pretend to be internal.

    Wrong
    ip = headers["X-Forwarded-For"].split(",")[0]
    Right
    ip = peerif peer in trusted_proxies:    ip = rightmost_untrusted(headers)
  • Matching half a path segment

    major

    A bare prefix test sends /apiary to the API pool.

    Wrong
    path.startswith("/api")
    Right
    path == "/api" or path.startswith("/api/")
  • Leaving flows in the table forever

    major

    Closed connections fill the memory until new flows fail.

    Wrong
    flows[key] = server
    Right
    flows[key] = (server, now)expire_idle_and_closed(flows)

Interview tips

  • How to explain it

    • Layer 4 reads the label, layer 7 opens the box.
    • One chooses per connection, the other per request.
  • Choose layer 4

    • UDP, databases, games, very many connections.
    • You must not decrypt here.
  • Choose layer 7

    • Routing by host, path or cookie.
    • Canary releases, firewalls, request retries.
  • Check before you ship

    • Who ends TLS, and who holds the key?
    • How does the server learn the client's address?
    • What happens to long connections on a deploy?