Reverse Proxies and Load Balancers
Understand the server that sits in front of your app: TLS termination, routing, load balancing and buffering.
Intermediate · about 3 hours · difficulty 2/5
Learn first: HTTPS and TLS, Where Backends Run: Hosting Options
In production, clients rarely talk to your application process directly. A reverse proxy accepts the connection and forwards it to one of your app instances. This layer does jobs that application frameworks do poorly or should not do at all.
What the front layer does
- TLS termination: handles certificates and HTTPS so your app speaks plain HTTP on a private network.
- Load balancing across instances with algorithms like round robin, least connections or consistent hashing.
- Routing by host or path (
api.example.comto the API,/staticto files). - Serving static files and compressing responses efficiently.
- Buffering slow clients so your app process is not tied up.
- Basic protection: connection limits, request size limits, rate limiting and timeouts.
Layer 4 vs layer 7
- L4 load balancers route TCP/UDP connections without reading HTTP (fast, protocol-agnostic).
- L7 load balancers understand HTTP and can route by path, header or cookie, retry, and add headers.
Cloud load balancers (AWS ALB/NLB, Google Cloud Load Balancing) and HAProxy, Nginx, Caddy, Envoy or Traefik all fill this role.
Things your app must handle behind a proxy
- The client IP arrives in
X-Forwarded-FororForwarded; configure your framework to trust only your proxy. - The original scheme arrives in
X-Forwarded-Proto, which matters for redirects and secure cookies. - Health checks from the load balancer decide whether an instance gets traffic.
- WebSockets and long requests need matching timeouts at every hop.
You are ready to move on when you can draw the path of a request from browser to app instance, naming where TLS ends and how the real client IP is preserved.
Key concepts
- Forward vs reverse proxy
- TLS termination
- Load balancing algorithms
- L4 vs L7 load balancing
- X-Forwarded-For and trusted proxies
- Health checks
- HAProxy, Envoy and Traefik
Mini project
Run two instances of your API behind a reverse proxy locally, verify round-robin balancing, log the real client IP correctly, and kill one instance to watch health checks remove it.
Check yourself
Why is it dangerous for your app to trust X-Forwarded-For from any client?
Free resources
- What is a reverse proxy? (Cloudflare)
- What is load balancing? (Cloudflare)
- MDN: X-Forwarded-For (MDN)