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.
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 Capability | Static Nginx Pattern | Dynamic Traefik / Envoy Pattern | Production Impact |
|---|---|---|---|
| Service Discovery | Static upstream blocks or DNS resolver valid=10s rewrites | Real-time Docker socket / Kubernetes API endpoint watches | Eliminates stale upstream IPs cleanly during rolling container restarts |
| Upstream Connection Reuse | Explicit proxy_http_version 1.1; proxy_set_header Connection ""; + keepalive 64; | Automatic HTTP/1.1 & HTTP/2 ServersTransport connection pooling | Avoids ephemeral TIME_WAIT port exhaustion & internal TCP handshake tax |
| Load Balancing Algorithm | least_conn, round_robin, consistent hash $request_uri | Weighted Round Robin (WRR), Power-of-Two-Choices, Sticky Cookies | least_conn protects mixed-duration AI inference pods better than naive Round Robin |
| TLS & ACME Certificates | Certbot/ACME reload workflows (nginx -s reload) | Built-in automated Let's Encrypt HTTP-01 / DNS-01 rotation | Zero 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:
- Always Set
proxy_http_version 1.1+ ClearConnection ""in Nginx: By default, Nginx speaks HTTP/1.0 to upstreams and closes every single backend TCP socket after one response! At3,000 req/s, opening and tearing down thousands of local TCP connections per second exhausts Linux ephemeral ports (ip_local_port_rangestuck inTIME_WAIT) and spikes Uvicorn/Node CPU. Pairingkeepalive 64;insideupstreamwith HTTP/1.1 andproxy_set_header Connection "";turns upstream traffic into fast pooled reuse (while handling WebSockets via a conditional$connection_upgrademap!). - Never Blindly Trust Caller
X-Forwarded-ForHeaders: If a spoofed client sendsX-Forwarded-For: 127.0.0.1straight 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 incomingX-Forwarded-*headers at the public edge (set_real_ip_from/trustedIPsexclusively listing verified CDN/Cloudflare CIDRs!). - Tune Idle Timeouts Asymmetric Toward Proxy: Set backend server keep-alive timeouts (Uvicorn
--timeout-keep-alive 75, Nodeserver.keepAliveTimeout) slightly higher than the proxy's upstream idle pool expiry (keepalive_timeout 60s), preventing subtle502 Bad Gatewayraces where the backend closes a reused socket cleanly milliseconds before Nginx sends bytes down it.
nginxmap $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 podsserver 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 brevitylocation /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 deliveryproxy_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
/mcpto 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
- Docker/K8s Upstream IP Stale DNS Caching in Plain Nginx: Writing
proxy_pass http://api-service:8000;directly insidelocationtells open-source Nginx to resolve DNS once at process startup—causing total502 Bad Gatewayoutages the momentapi-serviceredeploys onto a new container IP! Always configureresolver 127.0.0.11 valid=5s;+ variable indirection (set $upstream http://api-service:8000;) or use Traefik's live Docker provider. proxy_buffering on(Nginx Default) Freezing SSE & Agent Streams: Default Nginx output buffering holds partial JSON/token chunks untilproxy_buffer_sizefills or upstream closes—destroying interactive time-to-first-token UX. Setproxy_buffering off;(orX-Accel-Buffering: no) specifically on streaming locations.- Spurious
502Spikes When Proxykeepalive_timeoutExceeds BackendkeepAliveTimeout: Whenever Node (5 slegacy default) or Uvicorn (5 sdefault!) drops an idle pooled TCP connection while Nginx/Traefik tries reusing it, clients see random502resets. Keep backend keep-alive strictly longer than proxy pool expiry. - Trusting Spoofed
X-Forwarded-ForClient IP Headers: Allowing untrusted public clients to prepend fake internal IPs ontoX-Forwarded-Forbypasses geo-blocks, admin IP ACLs, and per-IP rate limits unless the edge proxy explicitly resets/validatesforwardedHeaders.trustedIPs.
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_WAITsocket exhaustion and random502races using HTTP/1.1keepalivepools and asymmetric keep-alive timeouts. - Secure real-client IP resolution against
X-Forwarded-Forspoofing via explicittrustedIPsallowlists. - Eliminate Docker DNS caching outages and SSE chunk stalls using dynamic
resolver/ Traefik rules andproxy_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.