Layer 4 and layer 7 load balancers
medium 26 minA 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
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
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
criticalMany calls share one connection, so one server becomes hot while others idle.
Wrongserver = pick(servers) # once, at connectRightfor call in stream: server = pick(servers) # per callTrusting a client's forwarding header
criticalAnyone can write any address in it, and so dodge limits or pretend to be internal.
Wrongip = headers["X-Forwarded-For"].split(",")[0]Rightip = peerif peer in trusted_proxies: ip = rightmost_untrusted(headers)Matching half a path segment
majorA bare prefix test sends /apiary to the API pool.
Wrongpath.startswith("/api")Rightpath == "/api" or path.startswith("/api/")Leaving flows in the table forever
majorClosed connections fill the memory until new flows fail.
Wrongflows[key] = serverRightflows[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?