SD/Lesson 2 of 8/5 min read
Load Balancing and Proxies
Load balancers, L4 vs L7, balancing algorithms, health checks, sticky sessions, reverse proxies, API gateways, CDNs and DNS-based global load balancing.
On this page
Load Balancer
A load balancer distributes incoming requests across a pool of servers so no single server is overwhelmed. It also removes unhealthy servers from rotation, giving availability as well as capacity.
┌──────────────┐
clients ──▶ │ load balancer│ ──▶ server 1
└──────────────┘ ──▶ server 2
──▶ server 3Typical placements: between clients and web servers, between web servers and internal services, and in front of database read replicas.
The load balancer itself must not be a single point of failure: run an active-passive pair sharing a virtual IP, or an active-active fleet behind DNS or anycast.
L4 vs L7
L4 Load Balancer
Works at the transport layer. It sees IP addresses and ports, not HTTP. It forwards TCP or UDP connections, often by rewriting addresses with NAT.
L7 Load Balancer
Works at the application layer. It terminates the connection, parses HTTP, and makes routing decisions on content.
- Route
/api/*to one pool and/static/*to another, route by host header, A/B tests, canaries. - Can terminate TLS, compress, cache, rewrite headers and retry failed requests.
- More CPU per request than L4.
| L4 | L7 | |
|---|---|---|
| Sees | IP, port | URL, headers, cookies, body |
| Speed | Faster | Slower |
| TLS termination | No (passthrough) | Yes |
| Examples | AWS NLB, LVS | AWS ALB, Nginx, HAProxy, Envoy |
Load Balancing algorithms
| Algorithm | How it works | Good for |
|---|---|---|
| Round robin | Each server in turn | Identical servers, uniform requests |
| Weighted round robin | Bigger servers get more turns | Mixed hardware |
| Least Connections | Server with fewest active connections | Long-lived or uneven requests |
| Least response time | Fastest recent responses | Latency-sensitive services |
| IP hash | Hash of client IP picks the server | Crude session affinity |
| Consistent hashing | Hash ring, minimal remapping | Caches, stateful shards |
| Random with two choices | Pick two at random, use the less loaded | Large fleets, low coordination |
"Power of two random choices" is surprisingly close to optimal and needs no global state.
Health Check
The load balancer periodically probes each server:
- Active: send
GET /healthzevery few seconds; mark unhealthy after N failures, healthy again after M successes. - Passive: watch real traffic; eject servers returning errors or timing out.
A good health endpoint checks the process can serve requests, but should not fail just because a shared dependency is down, or every server will be ejected at once.
Sticky Session
Sticky sessions (session affinity) send all requests from one client to the same server, usually via a cookie set by the load balancer.
- Needed when servers keep in-memory session state.
- Downsides: uneven load, and sessions are lost when that server dies.
Better: make servers stateless and store sessions in Redis or a signed token.
Reverse Proxy
A reverse proxy sits in front of servers and accepts requests on their behalf. Clients talk to the proxy and do not know which backend served them. (A forward proxy sits in front of clients instead.)
Functions:
- Load balancing across backends.
- TLS termination so backends speak plain HTTP inside the private network.
- Caching static and cacheable responses.
- Compression, request buffering, rate limiting.
- Hiding backend topology and absorbing slow clients.
Nginx, HAProxy, Envoy and Caddy are common reverse proxies. A load balancer is a reverse proxy whose main job is distribution.
API Gateway
An API gateway is a reverse proxy specialized for APIs, typically the single entry point to a set of microservices.
- Routing to the right service, request and response transformation.
- Authentication, authorization and API keys.
- Rate limiting, quotas, request validation.
- Aggregating several backend calls into one response (backend-for-frontend).
- Centralized logging, metrics and tracing.
Risk: it becomes a bottleneck and a place where business logic piles up. Keep it thin.
CDN
A Content Delivery Network caches content on edge servers close to users.
- Push CDN: you upload content to the CDN ahead of time. Good for content that rarely changes.
- Pull CDN: the edge fetches from your origin on the first miss and caches it per
Cache-Control. Simpler, the common default.
Benefits: lower latency (the edge is a few ms away instead of 150 ms), less load on the origin, and absorption of traffic spikes and DDoS traffic. Modern CDNs also run code at the edge and cache API responses.
Invalidation: version asset URLs (app.3f9c1.js) so a new deploy simply references new files, instead of purging.
Global load balancing
DNS-based
The authoritative DNS returns different IPs based on the resolver's location, health and load (GeoDNS). Simple, but DNS caching means failover takes up to the record's TTL.
Anycast
Anycast advertises the same IP address from many locations via BGP. Routers send each user to the topologically nearest site. Used by CDNs and public DNS (1.1.1.1, 8.8.8.8). Failover is as fast as BGP convergence.
Quick revision
- Load balancers spread load and remove unhealthy servers; make the LB itself redundant.
- L4 routes by IP and port (fast); L7 routes by HTTP content and can terminate TLS.
- Round robin for uniform load, least connections for uneven load, consistent hashing for caches.
- Prefer stateless servers over sticky sessions.
- Reverse proxy fronts servers; API gateway adds auth, rate limiting and routing for APIs.
- CDNs cache at the edge; version asset URLs instead of purging.
- Global routing uses GeoDNS or anycast.