FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Reverse Proxies & Load Balancing

Nginx & Traefik TLS termination, keep-alive connections, and upstream load-balancing.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Configure Nginx and Traefik reverse proxies for microservices
  • ✓Manage TLS termination and HTTP keep-alive connection pools
Full Technical Reference Document

Mental model

A Reverse Proxy (Nginx, Traefik, Envoy, Caddy) sits at the network ingress boundary in front of application containers—terminating public TLS 1.3 handshakes and HTTP/2/HTTP/3 multiplexing, dispatching paths cleanly across decoupled backend services (such as Next.js SSR + separate MCP server), draining unhealthy instances via active/passive healthchecks, and multiplexing connections over persistent upstream keep-alive TCP sockets. Treating a reverse proxy as a mindless forwarding pipe leaves huge performance and security bugs behind: HTTP/1.0 upstream socket thrashing, client IP spoofing via untrusted X-Forwarded-For, and stalled AI streaming chunks.

Public HTTPS / HTTP2 Request
Edge Reverse Proxy TLS Termination
Validate & Strip Untrusted X-Forwarded Headers
Load Balance (Least Conn) + Keep-Alive Pool
Forward Clean Request to Healthy Upstream Pod
Conceptual teaching model synthesized from:nginx-docs,traefik-docs

Theory

Two architecture styles dominate modern self-hosted and containerized reverse proxies: static high-speed event-driven configs (Nginx) and dynamic service-discovery ingress routers (Traefik watching Docker labels or Kubernetes Ingress/Gateway CRDs).

Proxy CapabilityStatic Nginx PatternDynamic Traefik / Envoy PatternProduction Impact
Service DiscoveryStatic upstream blocks or DNS resolver valid=10s rewritesReal-time Docker socket / Kubernetes API endpoint watchesEliminates stale upstream IPs cleanly during rolling container restarts
Upstream Connection ReuseExplicit proxy_http_version 1.1; proxy_set_header Connection ""; + keepalive 64;Automatic HTTP/1.1 & HTTP/2 ServersTransport connection poolingAvoids ephemeral TIME_WAIT port exhaustion & internal TCP handshake tax
Load Balancing Algorithmleast_conn, round_robin, consistent hash $request_uriWeighted Round Robin (WRR), Power-of-Two-Choices, Sticky Cookiesleast_conn protects mixed-duration AI inference pods better than naive Round Robin
TLS & ACME CertificatesCertbot/ACME reload workflows (nginx -s reload)Built-in automated Let's Encrypt HTTP-01 / DNS-01 rotationZero expired cert outages across multi-domain ingress routes

Upstream Keep-Alive Pitfalls, Header Trust Boundaries, and Rolling Drains

Three production details separate resilient reverse proxy configs from fragile boilerplate:

  1. Always Set proxy_http_version 1.1 + Clear Connection "" in Nginx: By default, Nginx speaks HTTP/1.0 to upstreams and closes every single backend TCP socket after one response! At 3,000 req/s, opening and tearing down thousands of local TCP connections per second exhausts Linux ephemeral ports (ip_local_port_range stuck in TIME_WAIT) and spikes Uvicorn/Node CPU. Pairing keepalive 64; inside upstream with HTTP/1.1 and proxy_set_header Connection ""; turns upstream traffic into fast pooled reuse (while handling WebSockets via a conditional $connection_upgrade map!).
  2. Never Blindly Trust Caller X-Forwarded-For Headers: If a spoofed client sends X-Forwarded-For: 127.0.0.1 straight to a proxy that unconditionally appends ($proxy_add_x_forwarded_for) and an upstream app naively reads the first IP from that comma-separated list, attackers trivially bypass IP rate limiters and admin allowlists! Strip or overwrite incoming X-Forwarded-* headers at the public edge (set_real_ip_from / trustedIPs exclusively listing verified CDN/Cloudflare CIDRs!).
  3. Tune Idle Timeouts Asymmetric Toward Proxy: Set backend server keep-alive timeouts (Uvicorn --timeout-keep-alive 75, Node server.keepAliveTimeout) slightly higher than the proxy's upstream idle pool expiry (keepalive_timeout 60s), preventing subtle 502 Bad Gateway races where the backend closes a reused socket cleanly milliseconds before Nginx sends bytes down it.
nginx
map $http_upgrade $connection_upgrade {
default ""; # Preserve persistent HTTP/1.1 keepalive on standard requests
"~*websocket" "upgrade";
}
​
upstream ai_api_pool {
least_conn; # Prevent slow LLM requests from piling onto busy pods
server 10.0.2.10:8000 max_fails=3 fail_timeout=10s;
server 10.0.2.11:8000 max_fails=3 fail_timeout=10s;
keepalive 64; # Persistent socket pool per worker process
}
​
server {
listen 443 ssl;
http2 on;
server_name api.fullstackaihub.com;
​
# TLS certs & intermediate config omitted for brevity
location /v1/chat/stream {
proxy_pass http://ai_api_pool;
proxy_http_version 1.1;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off; # Crucial for real-time SSE token delivery
proxy_read_timeout 300s;
}
}

Alternatives and trade-offs

  • Nginx (Static/Templated Edge): Unrivaled raw static-file speed, low predictable RAM footprint, battle-tested rate/cache directives; requires explicit reload triggers (SIGHUP) or paid Nginx Plus / Lua hooks for dynamic DNS upstream re-resolution without Nginx caching old Docker container IPs forever.
  • Traefik (Dynamic Docker/Kubernetes Router): Zero-reload container discovery, native priority routing rules (routing /mcp to Node while / stays on Next.js transparently), automated Let's Encrypt TLS, first-class OpenTelemetry tracing; slightly higher per-request Go GC latency overhead than static C Nginx at ultra-high L7 RPS.
  • Cloud Managed Load Balancers (AWS ALB / Cloudflare Edge): Eliminates single-VM reverse proxy patching and absorbs massive DDoS floods upstream of your origin IP, at ongoing egress/LCU billing costs and limited per-path Lua customization.

Failure modes and misconceptions

  1. Docker/K8s Upstream IP Stale DNS Caching in Plain Nginx: Writing proxy_pass http://api-service:8000; directly inside location tells open-source Nginx to resolve DNS once at process startup—causing total 502 Bad Gateway outages the moment api-service redeploys onto a new container IP! Always configure resolver 127.0.0.11 valid=5s; + variable indirection (set $upstream http://api-service:8000;) or use Traefik's live Docker provider.
  2. proxy_buffering on (Nginx Default) Freezing SSE & Agent Streams: Default Nginx output buffering holds partial JSON/token chunks until proxy_buffer_size fills or upstream closes—destroying interactive time-to-first-token UX. Set proxy_buffering off; (or X-Accel-Buffering: no) specifically on streaming locations.
  3. Spurious 502 Spikes When Proxy keepalive_timeout Exceeds Backend keepAliveTimeout: Whenever Node (5 s legacy default) or Uvicorn (5 s default!) drops an idle pooled TCP connection while Nginx/Traefik tries reusing it, clients see random 502 resets. Keep backend keep-alive strictly longer than proxy pool expiry.
  4. Trusting Spoofed X-Forwarded-For Client IP Headers: Allowing untrusted public clients to prepend fake internal IPs onto X-Forwarded-For bypasses geo-blocks, admin IP ACLs, and per-IP rate limits unless the edge proxy explicitly resets/validates forwardedHeaders.trustedIPs.
Reflect before revealing the guide

Decision scenario

Your production VPS runs a Docker Compose stack serving Next.js SSR (:3000) and a standalone MCP/OpenAPI TypeScript server (:3100) behind one HTTPS domain (fullstackaihub.com), handling SSE LLM streams, OAuth authorize splits, and rolling container swaps with zero downtime. Deploy Traefik (or dynamically resolved Nginx) as the single public :80/:443 edge proxy managing automated Let's Encrypt TLS (http2), attach explicit priority-ordered path rules routing /mcp, /oauth/token, and /openapi.json to :3100 while /oauth/authorize and / stay on :3000, enforce trustedIPs on X-Forwarded-* strictly to your edge CDN CIDR, disable proxy buffering on streaming paths, and configure upstream Docker healthchecks + graceful container drain timeouts (stop_grace_period: 30s) above backend keep-alive lifecycles.

Learning outcomes

  • Contrast static Nginx performance tuning against Traefik's dynamic container/service discovery and ACME automation.
  • Prevent TIME_WAIT socket exhaustion and random 502 races using HTTP/1.1 keepalive pools and asymmetric keep-alive timeouts.
  • Secure real-client IP resolution against X-Forwarded-For spoofing via explicit trustedIPs allowlists.
  • Eliminate Docker DNS caching outages and SSE chunk stalls using dynamic resolver / Traefik rules and proxy_buffering off.

Trade-offs

Putting Nginx or Traefik at the edge adds a negligible (< 1 ms) network hop while unifying TLS termination, HTTP/2 multiplexing, zero-downtime draining, and streaming-safe connection pooling cleanly outside individual application workers.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next